Skip to main content

memd/cli/
mod.rs

1//! CLI mode for direct operation invocation
2//!
3//! Provides command-line interface for manual testing and debugging
4//! through the local executable.
5
6use serde_json::json;
7use tracing::info;
8
9use crate::error::{MemdError, Result};
10use crate::store::metadata::MetadataStore;
11use crate::store::writer_lock::acquire_writer_lock;
12use crate::store::{Store, TenantManager};
13use crate::types::{ChunkId, ChunkStatus, TenantId};
14
15mod args;
16mod audit;
17mod batch;
18mod call;
19mod cleanup_plan;
20mod consolidate;
21mod doctor;
22mod eval_counterfactual;
23mod eval_outcome_ranking;
24mod eval_retrieval;
25mod eval_write_quality;
26mod experience;
27mod experience_check;
28mod maintenance;
29mod memory_md;
30mod ops_bridge;
31mod outcome_scan;
32mod paths;
33mod provenance;
34mod purge;
35mod read_commands;
36mod render;
37mod report;
38mod scope;
39mod search;
40mod session_start;
41mod warm;
42mod write_commands;
43
44pub use args::{
45    CliCommand, CliQueryMode, ExportFormat, NativeHookHarness, ReportFormat, SearchReranker,
46    StoreAccess, WarmCommand, WarmMode, WarmProcessConfig,
47};
48use args::{ProjectScopeConfig, SearchRerankerOptions, TenantScopeConfig};
49use audit::{render_audit_report, run_audit, strict_should_fail, AuditOptions};
50use batch::{read_batch_input, run_batch_jsonl, stream_batch_jsonl};
51use call::parse_call_arguments;
52use cleanup_plan::{render_cleanup_plan, run_cleanup_plan, CleanupPlanOptions};
53use consolidate::{
54    run_consolidate, run_consolidate_review, ConsolidateOptions, ConsolidateReviewOptions,
55};
56use doctor::{failing_checks, run_doctor, DoctorOptions};
57use eval_counterfactual::{run_eval_counterfactual, EvalCounterfactualOptions};
58use eval_outcome_ranking::{run_eval_outcome_ranking, EvalOutcomeRankingOptions};
59use eval_retrieval::{run_eval_retrieval, EvalRetrievalOptions};
60use eval_write_quality::{run_eval_write_quality, EvalWriteQualityOptions};
61pub use experience::{emit_case_if_requested, prepare_experience_command, ExperienceCommand};
62use memory_md::{
63    refresh_memory_md_with_health, run_memory_md_eval, MemoryMdEvalOptions, MemoryMdOptions,
64};
65use ops_bridge::cli_call_tool;
66use outcome_scan::{run_outcome_scan, OutcomeScanOptions};
67use paths::{
68    absolutize_project_dir, normalize_absolute, path_is_inside, read_omf_input,
69    read_stdin_to_string, reject_if_any_symlink_inside_outdir, resolve_data_dir,
70    resolve_export_markdown_data_dirs,
71};
72pub use provenance::{
73    capture_execution_context, capture_tracked_diff_sha256, enrich_operation_arguments,
74    prepare_execution_context,
75};
76use purge::{
77    inspect_purge_archive, render_purge_archive_inspection, run_purge, PurgeArchiveInspectOptions,
78    PurgeOptions,
79};
80use read_commands::collect_all_chunks;
81use render::{
82    render_agent_context, render_export, render_guardrail_block, render_search_payload,
83    unwrap_content_payload, upsert_guardrail_file, write_cli_log, write_rendered,
84};
85use report::{cli_report_rendered, ReportOptions};
86pub use scope::resolve_command_scope;
87use search::{
88    apply_search_reranker, cli_agent_context_payload, cli_search_payload, export_format_name,
89    finalize_search_episode,
90};
91use session_start::{
92    native_hook_project_dir, read_native_hook_context, run_session_start, SessionStartOptions,
93};
94use warm::run_warm_worker;
95pub use warm::{run_warm_admin, try_run_warm_client, warm_socket_path};
96use write_commands::{
97    cli_add_rendered, cli_delete_rendered, cli_import_omf_rendered, CliAddRenderOptions,
98};
99
100/// Run a CLI command
101///
102/// Executes the specified command against the store and prints JSON output.
103pub async fn run_cli<S: Store>(
104    store: &S,
105    tenant_manager: Option<&TenantManager>,
106    cmd: CliCommand,
107) -> Result<()> {
108    match cmd {
109        CliCommand::Experience { .. } => {
110            return Err(MemdError::ValidationError(
111                "experience commands require client-side preparation".into(),
112            ));
113        }
114        CliCommand::Add {
115            tenant_id,
116            text,
117            chunk_type,
118            project_id,
119            tags,
120            source_uri,
121            source_path,
122            warm: _,
123        } => {
124            let tenant_id = scope::require_tenant(tenant_id)?;
125            let rendered = cli_add_rendered(
126                store,
127                tenant_manager,
128                CliAddRenderOptions {
129                    tenant_id,
130                    text,
131                    chunk_type,
132                    project_id,
133                    tags,
134                    source_uri,
135                    source_path,
136                },
137            )
138            .await?;
139            print!("{rendered}");
140        }
141
142        CliCommand::Search {
143            tenant_id,
144            query,
145            query_positional,
146            k,
147            project_id,
148            task_id,
149            thread_id,
150            compact,
151            dedupe_by_source,
152            token_budget,
153            mode,
154            no_text,
155            include_artifact,
156            include_superseded,
157            format,
158            output,
159            reranker,
160            reranker_model,
161            reranker_device,
162            reranker_batch_size,
163            reranker_timeout_seconds,
164            reranker_python,
165            warm: _,
166        } => {
167            let tenant_id = scope::require_tenant(tenant_id)?;
168            let episode_tenant_id = tenant_id.clone();
169            // `main` folds the positional form into `query` via
170            // `normalize_positional_aliases`, and clap requires one of the two.
171            // A direct library caller can still skip that, so fail loudly here
172            // rather than silently searching for the empty string.
173            let query = query.or(query_positional).ok_or_else(|| {
174                MemdError::ValidationError(
175                    "search requires --query or a positional query".to_string(),
176                )
177            })?;
178            let mut payload = cli_search_payload(
179                store,
180                tenant_id,
181                project_id,
182                query.clone(),
183                k,
184                compact,
185                dedupe_by_source,
186                token_budget,
187                mode,
188                no_text,
189                include_artifact,
190                include_superseded,
191                task_id,
192                thread_id,
193            )
194            .await?;
195            payload = apply_search_reranker(
196                payload,
197                &query,
198                &SearchRerankerOptions {
199                    reranker,
200                    model: reranker_model,
201                    device: reranker_device,
202                    batch_size: reranker_batch_size,
203                    timeout_seconds: reranker_timeout_seconds,
204                    python: reranker_python,
205                },
206            )?;
207            finalize_search_episode(store, &episode_tenant_id, &payload).await?;
208            write_rendered(output.as_deref(), &render_search_payload(&payload, format)?)?;
209        }
210
211        CliCommand::AgentContext {
212            tenant_id,
213            project_id,
214            task_id,
215            thread_id,
216            query,
217            k,
218            token_budget,
219            mode,
220            no_text,
221            include_artifact,
222            format,
223            output,
224            log_dir,
225            warm: _,
226        } => {
227            let tenant_id = scope::require_tenant(tenant_id)?;
228            let payload = cli_agent_context_payload(
229                store,
230                &tenant_id,
231                project_id.as_deref(),
232                task_id.as_deref(),
233                thread_id.as_deref(),
234                &query,
235                k,
236                token_budget,
237                mode,
238                no_text,
239                include_artifact,
240            )
241            .await?;
242            write_cli_log(log_dir.as_deref(), "memd_search", &payload)?;
243            write_rendered(output.as_deref(), &render_agent_context(&payload, format)?)?;
244        }
245
246        CliCommand::MemoryMd {
247            tenant_id,
248            project_id,
249            project_dir,
250            output,
251            project_limit,
252            global_limit,
253            candidate_k,
254            explain_output,
255        } => {
256            let result = refresh_memory_md_with_health(
257                store,
258                tenant_manager,
259                MemoryMdOptions {
260                    tenant_id,
261                    project_id,
262                    project_dir,
263                    output,
264                    project_limit,
265                    global_limit,
266                    candidate_k,
267                    explain_output,
268                },
269            )
270            .await?;
271            println!("{}", serde_json::to_string_pretty(&result)?);
272        }
273
274        CliCommand::EvalMemoryMd {
275            tenant_id,
276            project_id,
277            project_dir,
278            output,
279            project_limit,
280            candidate_k,
281            top_n,
282            min_useful_ratio,
283            max_generated_wrappers,
284            agent_usefulness,
285            gold_file,
286        } => {
287            let result = run_memory_md_eval(
288                store,
289                tenant_manager,
290                MemoryMdEvalOptions {
291                    tenant_id,
292                    project_id,
293                    project_dir,
294                    output,
295                    project_limit,
296                    candidate_k,
297                    top_n,
298                    min_useful_ratio,
299                    max_generated_wrappers,
300                    agent_usefulness,
301                    gold_file,
302                },
303            )
304            .await?;
305            println!("{}", serde_json::to_string_pretty(&result)?);
306        }
307
308        CliCommand::EvalRetrieval {
309            tenant_id,
310            project_id,
311            project_dir,
312            queries,
313            k,
314            min_precision_at_k,
315            min_hit_rate_at_k,
316            min_known_recall_at_k,
317            min_mrr,
318        } => {
319            let result = run_eval_retrieval(
320                store,
321                EvalRetrievalOptions {
322                    tenant_id,
323                    project_id,
324                    project_dir,
325                    queries_path: queries,
326                    k,
327                    min_precision_at_k,
328                    min_hit_rate_at_k,
329                    min_known_recall_at_k,
330                    min_mrr,
331                },
332            )
333            .await?;
334            println!("{}", serde_json::to_string_pretty(&result)?);
335        }
336
337        CliCommand::EvalWriteQuality {
338            project_dir,
339            min_rejection_or_downgrade_rate,
340            min_duplicate_reuse_rate,
341            max_total_chunks,
342            max_disk_bytes,
343            require_retention_compaction,
344        } => {
345            let result = run_eval_write_quality(EvalWriteQualityOptions {
346                project_dir,
347                min_rejection_or_downgrade_rate,
348                min_duplicate_reuse_rate,
349                max_total_chunks,
350                max_disk_bytes,
351                require_retention_compaction,
352            })
353            .await?;
354            println!("{}", serde_json::to_string_pretty(&result)?);
355        }
356
357        CliCommand::Consolidate {
358            tenant_id,
359            project_id,
360            project_dir,
361            max_region,
362            dry_run,
363            background,
364            force,
365            promote,
366            legacy_immediate,
367            warm: _,
368        } => {
369            let result = run_consolidate(
370                store,
371                ConsolidateOptions {
372                    tenant_id,
373                    project_id,
374                    project_dir,
375                    max_region,
376                    dry_run,
377                    background,
378                    force,
379                    promote,
380                    legacy_immediate,
381                },
382            )
383            .await?;
384            println!("{}", serde_json::to_string_pretty(&result)?);
385        }
386
387        CliCommand::ConsolidateReview {
388            run_id,
389            tenant_id,
390            project_id,
391            list,
392            limit,
393            accept,
394            reject,
395            warm: _,
396        } => {
397            let result = run_consolidate_review(
398                store,
399                ConsolidateReviewOptions {
400                    run_id,
401                    tenant_id,
402                    project_id,
403                    list,
404                    limit,
405                    accept,
406                    reject,
407                },
408            )
409            .await?;
410            println!("{}", serde_json::to_string_pretty(&result)?);
411        }
412
413        CliCommand::Outcome {
414            episode_id,
415            tenant_id,
416            outcome,
417            verifier,
418            used,
419            harmful,
420            evidence,
421            event_time_ms,
422            warm: _,
423        } => {
424            let value = cli_call_tool(
425                store,
426                tenant_manager,
427                "memory.record_outcome",
428                json!({
429                    "tenant_id": scope::require_tenant(tenant_id)?,
430                    "episode_id": episode_id,
431                    "outcome": outcome,
432                    "verifier_type": verifier,
433                    "used_chunk_ids": used,
434                    "harmful_chunk_ids": harmful,
435                    "evidence_reference": evidence,
436                    "event_time_ms": event_time_ms,
437                }),
438            )
439            .await
440            .map_err(|error| MemdError::ProtocolError(error.to_string()))?;
441            let payload = unwrap_content_payload(value.clone()).unwrap_or(value);
442            println!("{}", serde_json::to_string_pretty(&payload)?);
443        }
444
445        CliCommand::OutcomeScan {
446            project_dir,
447            sessions_dir,
448            since_days,
449            dry_run,
450        } => {
451            let result = run_outcome_scan(
452                store,
453                OutcomeScanOptions {
454                    project_dir,
455                    sessions_dir,
456                    since_days,
457                    dry_run,
458                },
459            )
460            .await?;
461            println!("{}", serde_json::to_string_pretty(&result)?);
462        }
463
464        CliCommand::EvalCounterfactual {
465            tenant_id,
466            project_id,
467            project_dir,
468            queries,
469            k,
470        } => {
471            let result = run_eval_counterfactual(
472                store,
473                EvalCounterfactualOptions {
474                    tenant_id,
475                    project_id,
476                    project_dir,
477                    queries_path: queries,
478                    k,
479                },
480            )
481            .await?;
482            println!("{}", serde_json::to_string_pretty(&result)?);
483        }
484
485        CliCommand::EvalOutcomeRanking {
486            tenant_id,
487            project_id,
488            project_dir,
489            queries,
490            k,
491            report_json,
492        } => {
493            let result = run_eval_outcome_ranking(
494                store,
495                EvalOutcomeRankingOptions {
496                    tenant_id,
497                    project_id,
498                    project_dir,
499                    queries_path: queries,
500                    k,
501                    report_json,
502                },
503            )
504            .await?;
505            println!("{}", serde_json::to_string_pretty(&result)?);
506        }
507
508        CliCommand::SessionStart {
509            mut project_dir,
510            native_hook,
511        } => {
512            let execution_context = native_hook
513                .map(|harness| read_native_hook_context(harness, &project_dir))
514                .transpose()?;
515            if let Some(context) = execution_context.as_ref() {
516                project_dir = native_hook_project_dir(&project_dir, context);
517            }
518            let result = run_session_start(
519                store,
520                SessionStartOptions { project_dir },
521                execution_context,
522            )
523            .await?;
524            println!("{}", serde_json::to_string_pretty(&result)?);
525        }
526
527        CliCommand::Doctor {
528            project_dir,
529            format,
530            strict,
531        } => {
532            let report = run_doctor(
533                store,
534                DoctorOptions {
535                    project_dir,
536                    // The resolved global --data-dir: doctor must
537                    // diagnose the store this process actually uses.
538                    data_dir: tenant_manager.map(|tm| tm.data_dir().to_path_buf()),
539                    format,
540                },
541            )
542            .await?;
543            if strict && !failing_checks(&report).is_empty() {
544                std::process::exit(2);
545            }
546        }
547
548        CliCommand::Call {
549            tool,
550            json,
551            input,
552            output,
553            warm: _,
554        } => {
555            let arguments = parse_call_arguments(json.as_deref(), input.as_deref())?;
556            let arguments = scope::apply_operation_scope(
557                arguments,
558                &mut scope::OperationScopeCache::default(),
559            )?;
560            let value = cli_call_tool(store, tenant_manager, &tool, arguments)
561                .await
562                .map_err(|e| MemdError::ProtocolError(e.to_string()))?;
563            let payload = unwrap_content_payload(value.clone()).unwrap_or(value);
564            write_rendered(
565                output.as_deref(),
566                &(serde_json::to_string_pretty(&payload)? + "\n"),
567            )?;
568        }
569
570        CliCommand::Batch {
571            jsonl,
572            stream,
573            continue_on_error,
574            output,
575            warm: _,
576        } => {
577            if stream {
578                stream_batch_jsonl(
579                    store,
580                    tenant_manager,
581                    jsonl.as_deref(),
582                    output.as_deref(),
583                    continue_on_error,
584                )
585                .await?;
586            } else {
587                let input = read_batch_input(jsonl.as_deref())?;
588                let rendered =
589                    run_batch_jsonl(store, tenant_manager, &input, continue_on_error).await?;
590                write_rendered(output.as_deref(), &rendered)?;
591            }
592        }
593
594        CliCommand::Warm { .. } => {
595            return Err(MemdError::ValidationError(
596                "internal error: warm admin commands must run before store initialization"
597                    .to_string(),
598            ));
599        }
600
601        CliCommand::WarmWorker {
602            socket,
603            embedding_model,
604            search_variant,
605        } => {
606            run_warm_worker(
607                store,
608                tenant_manager,
609                &socket,
610                embedding_model.as_deref(),
611                search_variant.as_deref(),
612            )
613            .await?;
614        }
615
616        CliCommand::Maintenance {
617            data_dir,
618            tenant_id,
619            dry_run,
620            aggressive,
621        } => {
622            // Resolution order (Codex Phase 5 HIGH): explicit subcommand
623            // --data-dir wins, then the top-level --data-dir / config
624            // (already resolved into tenant_manager), then the default
625            // discovery. Without this chain, `memd --data-dir /x
626            // maintenance` would silently operate on $HOME/.memd/data.
627            let data_dir = match data_dir {
628                Some(p) => p,
629                None => match tenant_manager {
630                    Some(tm) => tm.data_dir().to_path_buf(),
631                    None => resolve_data_dir(None)?,
632                },
633            };
634            std::fs::create_dir_all(&data_dir)?;
635            let _writer_lock = acquire_writer_lock(&data_dir)?;
636            let report = maintenance::run(&data_dir, tenant_id.as_deref(), dry_run, aggressive)?;
637            let rendered = maintenance::render_report(&report, dry_run, aggressive);
638            print!("{}", rendered);
639        }
640
641        CliCommand::Get {
642            tenant_id,
643            chunk_id,
644            chunk_id_positional,
645        } => {
646            let tenant_id = scope::require_tenant(tenant_id)?;
647            let tenant = TenantId::new(&tenant_id)?;
648            let chunk_id = chunk_id.or(chunk_id_positional).ok_or_else(|| {
649                MemdError::ValidationError(
650                    "get requires --chunk-id or a positional chunk id".to_string(),
651                )
652            })?;
653            let cid = ChunkId::parse(&chunk_id)?;
654            let chunk = store
655                .get(&tenant, &cid)
656                .await?
657                .filter(|chunk| chunk.status != ChunkStatus::Candidate);
658
659            if let Some(c) = chunk {
660                info!(chunk_id = %cid, "chunk found");
661                println!("{}", serde_json::to_string_pretty(&c)?);
662            } else {
663                info!(chunk_id = %cid, "chunk not found");
664                println!("null");
665            }
666        }
667
668        CliCommand::Delete {
669            tenant_id,
670            chunk_id,
671            warm: _,
672        } => {
673            let tenant_id = scope::require_tenant(tenant_id)?;
674            let rendered = cli_delete_rendered(store, &tenant_id, &chunk_id).await?;
675            print!("{rendered}");
676        }
677
678        CliCommand::Stats { tenant_id } => {
679            let tenant_id = scope::require_tenant(tenant_id)?;
680            let tenant = TenantId::new(&tenant_id)?;
681            let stats = store.stats(&tenant).await?;
682
683            info!(tenant_id = %tenant, "stats retrieved");
684
685            let mut output = json!({
686                "total_chunks": stats.total_chunks,
687                "deleted_chunks": stats.deleted_chunks,
688                "chunk_types": stats.chunk_types,
689            });
690
691            // Add disk stats if available
692            if let Some(tm) = tenant_manager {
693                if let Ok(disk_stats) = tm.tenant_disk_stats(&tenant) {
694                    output["disk_stats"] = json!({
695                        "total_bytes": disk_stats.total_bytes,
696                        "segment_count": disk_stats.segment_count,
697                    });
698                }
699            }
700
701            println!("{}", serde_json::to_string_pretty(&output)?);
702        }
703
704        CliCommand::Audit {
705            tenant_id,
706            project_id,
707            format,
708            strict,
709            output,
710            page_size,
711            duplicate_examples,
712            top_projects,
713        } => {
714            let report = run_audit(
715                store,
716                tenant_manager,
717                AuditOptions {
718                    tenant_id,
719                    project_id,
720                    page_size,
721                    duplicate_examples,
722                    top_projects,
723                },
724            )
725            .await?;
726            write_rendered(output.as_deref(), &render_audit_report(&report, format)?)?;
727            if strict && strict_should_fail(&report) {
728                std::process::exit(2);
729            }
730        }
731
732        CliCommand::Report {
733            tenant_id,
734            project_id,
735            since,
736            format,
737            strict,
738            top,
739            output,
740            warm: _,
741        } => {
742            let (rendered, warn_count) = cli_report_rendered(
743                store,
744                tenant_manager,
745                ReportOptions {
746                    tenant_id,
747                    project_id,
748                    since,
749                    top,
750                    format,
751                    served_via_worker: false,
752                },
753            )
754            .await?;
755            write_rendered(output.as_deref(), &rendered)?;
756            if strict && warn_count > 0 {
757                std::process::exit(2);
758            }
759        }
760
761        CliCommand::CleanupPlan {
762            tenant_id,
763            project_id,
764            project_dir,
765            format,
766            output,
767            archive_dir,
768            older_than_days,
769            candidate_limit,
770            page_size,
771            top_projects,
772        } => {
773            let report = run_cleanup_plan(
774                store,
775                tenant_manager,
776                CleanupPlanOptions {
777                    tenant_id,
778                    project_id,
779                    project_dir,
780                    archive_dir,
781                    older_than_days,
782                    candidate_limit,
783                    page_size,
784                    top_projects,
785                },
786            )
787            .await?;
788            write_rendered(output.as_deref(), &render_cleanup_plan(&report, format)?)?;
789        }
790
791        CliCommand::Purge {
792            tenant_id,
793            project_id,
794            older_than_days,
795            limit,
796            include_unreadable_active,
797            archive,
798            apply,
799            vacuum_metadata,
800            rewrite_segments,
801            warm: _,
802        } => {
803            let result = run_purge(
804                store,
805                PurgeOptions {
806                    tenant_id,
807                    project_id,
808                    older_than_days,
809                    limit,
810                    include_unreadable_active,
811                    archive,
812                    apply,
813                    vacuum_metadata,
814                    rewrite_segments,
815                },
816            )
817            .await?;
818            println!("{}", serde_json::to_string_pretty(&result)?);
819        }
820
821        CliCommand::PurgeArchive {
822            archive,
823            expect_tenant_id,
824            expect_project_id,
825            min_records,
826            format,
827            output,
828        } => {
829            let report = inspect_purge_archive(PurgeArchiveInspectOptions {
830                archive,
831                expect_tenant_id,
832                expect_project_id,
833                min_records,
834            })?;
835            write_rendered(
836                output.as_deref(),
837                &render_purge_archive_inspection(&report, format)?,
838            )?;
839        }
840
841        CliCommand::Export {
842            tenant_id,
843            format,
844            output,
845            page_size,
846        } => {
847            let tenant_id = scope::require_tenant(tenant_id)?;
848            let tenant = TenantId::new(&tenant_id)?;
849            let page_size = page_size.clamp(1, 10_000);
850            let chunks = collect_all_chunks(store, &tenant, page_size).await?;
851            let rendered = render_export(&chunks, &tenant, format)?;
852
853            if let Some(path) = output {
854                std::fs::write(&path, rendered)?;
855                let summary = json!({
856                    "tenant_id": tenant.to_string(),
857                    "format": export_format_name(format),
858                    "chunks_exported": chunks.len(),
859                    "output_path": path,
860                });
861                println!("{}", serde_json::to_string_pretty(&summary)?);
862            } else {
863                print!("{rendered}");
864            }
865        }
866
867        CliCommand::ExportMarkdown {
868            tenant_id,
869            outdir,
870            project_id,
871            include_history,
872            data_dir,
873        } => {
874            let tenant_id = scope::require_tenant(tenant_id)?;
875            let tenant = TenantId::new(&tenant_id)?;
876            let ps = store.as_persistent().ok_or_else(|| {
877                crate::error::MemdError::StorageError(
878                    "export-markdown requires a persistent store".to_string(),
879                )
880            })?;
881
882            // Containment guard: refuse if the user pointed `--outdir` at
883            // a path inside memd's data directory. We use a textual
884            // normalise (no `canonicalize`) so the guard works before the
885            // outdir exists — std `Path::canonicalize` would error out.
886            // Containment guard refuses if `outdir` is inside ANY of
887            // the known memd data directories. When `--data-dir` is
888            // explicit, the list is just that path. When it's absent,
889            // the list is `[<discovered from tenant_scope.json>?,
890            // $HOME/.memd/data]` — discovery AUGMENTS the default
891            // fallback, it doesn't replace it, so an untrusted
892            // ancestor config can't turn off the guard for the
893            // default-install data directory (Codex Item 4 HIGH).
894            let effective_data_dirs = resolve_export_markdown_data_dirs(data_dir.as_deref())?;
895            let outdir_abs = normalize_absolute(&outdir);
896            for candidate in &effective_data_dirs {
897                let data_dir_abs = normalize_absolute(candidate);
898                if path_is_inside(&outdir_abs, &data_dir_abs) {
899                    return Err(crate::error::MemdError::ValidationError(format!(
900                        "refusing to write markdown export into memd data directory: \
901                         outdir={} data_dir={}",
902                        outdir_abs.display(),
903                        data_dir_abs.display()
904                    )));
905                }
906            }
907
908            // Walk metadata in pages so a tenant with > 10k chunks
909            // doesn't silently lose its tail. `list` supports an
910            // offset; `list_recent_for_project` doesn't, but the
911            // project-scoped branch already limits the candidate set by
912            // project, so a 10k-row page is usually sufficient. For
913            // whole-tenant exports we paginate `list` until we stop
914            // seeing new rows. (Codex G3 review MEDIUM: silent cap.)
915            const PAGE_SIZE: usize = 10_000;
916            let mut metas = Vec::new();
917            match project_id.as_deref() {
918                Some(pid) => {
919                    metas = ps
920                        .metadata()
921                        .list_recent_for_project(&tenant, Some(pid), PAGE_SIZE)?;
922                }
923                None => {
924                    let mut offset = 0;
925                    loop {
926                        let page = ps.metadata().list(&tenant, PAGE_SIZE, offset)?;
927                        if page.is_empty() {
928                            break;
929                        }
930                        let got = page.len();
931                        metas.extend(page);
932                        if got < PAGE_SIZE {
933                            break;
934                        }
935                        offset += got;
936                    }
937                }
938            };
939            let mut chunks = Vec::with_capacity(metas.len());
940            for meta in metas {
941                // Match the G2 handler's visibility rule: only Final,
942                // non-superseded rows; tier filter depends on flag.
943                if meta.status != crate::types::ChunkStatus::Final
944                    || meta.lifecycle.superseded_by.is_some()
945                {
946                    continue;
947                }
948                if !include_history
949                    && meta.lifecycle.tier == crate::types::lifecycle::MemoryTier::History
950                {
951                    continue;
952                }
953                if let Some(pid) = project_id.as_deref() {
954                    if meta.project_id.as_deref() != Some(pid) {
955                        continue;
956                    }
957                }
958                if let Some(chunk) = <crate::store::persistent::PersistentStore as Store>::get(
959                    ps,
960                    &tenant,
961                    &meta.chunk_id,
962                )
963                .await?
964                {
965                    chunks.push(chunk);
966                }
967            }
968
969            let files = crate::markdown_export::render_markdown_tree(&chunks);
970            std::fs::create_dir_all(&outdir_abs).map_err(|e| {
971                crate::error::MemdError::StorageError(format!(
972                    "failed to create outdir {}: {e}",
973                    outdir_abs.display()
974                ))
975            })?;
976
977            let mut written_paths: Vec<String> = Vec::with_capacity(files.len());
978            for f in &files {
979                // RenderedFile.path is a POSIX relative string; join it
980                // onto the outdir so we write into the right bucket.
981                let mut target = outdir_abs.clone();
982                for segment in f.path.split('/').filter(|s| !s.is_empty()) {
983                    target.push(segment);
984                }
985                // Refuse before any filesystem write if a pre-existing
986                // symlink planted inside outdir would redirect the
987                // write off to an attacker-chosen path. Runs before
988                // create_dir_all because create_dir_all happily walks
989                // through existing symlinked directories (Item 3).
990                reject_if_any_symlink_inside_outdir(&target, &outdir_abs)?;
991                if let Some(parent) = target.parent() {
992                    std::fs::create_dir_all(parent).map_err(|e| {
993                        crate::error::MemdError::StorageError(format!(
994                            "failed to create parent {}: {e}",
995                            parent.display()
996                        ))
997                    })?;
998                }
999                std::fs::write(&target, &f.content).map_err(|e| {
1000                    crate::error::MemdError::StorageError(format!(
1001                        "failed to write {}: {e}",
1002                        target.display()
1003                    ))
1004                })?;
1005                written_paths.push(target.display().to_string());
1006            }
1007
1008            let summary = json!({
1009                "tenant_id": tenant.to_string(),
1010                "outdir": outdir_abs.display().to_string(),
1011                "files_written": written_paths.len(),
1012                "paths": written_paths,
1013            });
1014            println!("{}", serde_json::to_string_pretty(&summary)?);
1015        }
1016
1017        CliCommand::ExportOmf {
1018            tenant_id,
1019            project_id,
1020            output,
1021            include_history,
1022            include_superseded,
1023            include_expired,
1024        } => {
1025            let tenant_id = scope::require_tenant(tenant_id)?;
1026            let tenant = TenantId::new(&tenant_id)?;
1027            let ps = store.as_persistent().ok_or_else(|| {
1028                crate::error::MemdError::StorageError(
1029                    "export-omf requires a persistent store".to_string(),
1030                )
1031            })?;
1032
1033            let opts = crate::omf::export::ExportOptions {
1034                project_id,
1035                include_history,
1036                include_superseded,
1037                include_expired,
1038            };
1039            let doc = crate::omf::export::export_omf(ps, &tenant, opts).await?;
1040            let rendered = serde_json::to_string_pretty(&doc)?;
1041
1042            if let Some(path) = output {
1043                std::fs::write(&path, format!("{rendered}\n"))?;
1044                let summary = json!({
1045                    "tenant_id": tenant.to_string(),
1046                    "memories": doc.memories.len(),
1047                    "output_path": path,
1048                });
1049                println!("{}", serde_json::to_string_pretty(&summary)?);
1050            } else {
1051                println!("{rendered}");
1052            }
1053        }
1054
1055        CliCommand::ImportOmf {
1056            tenant_id,
1057            input,
1058            include_archived,
1059            fuzzy_threshold,
1060            dry_run,
1061            warm: _,
1062        } => {
1063            let tenant_id = scope::require_tenant(tenant_id)?;
1064            let raw = read_omf_input(input.as_deref())?;
1065            let rendered = cli_import_omf_rendered(
1066                store,
1067                tenant_manager,
1068                &tenant_id,
1069                &raw,
1070                include_archived,
1071                fuzzy_threshold,
1072                dry_run,
1073            )
1074            .await?;
1075            print!("{rendered}");
1076        }
1077
1078        CliCommand::Init {
1079            tenant_id,
1080            project_dir,
1081            project_id,
1082            memd_command,
1083            memd_data_dir,
1084            write_agent_files,
1085        } => {
1086            let tenant = TenantId::new(&tenant_id)?;
1087            let project_dir = absolutize_project_dir(&project_dir)?;
1088            let memd_dir = project_dir.join(".memd");
1089            std::fs::create_dir_all(&memd_dir)?;
1090
1091            let effective_data_dir = resolve_data_dir(memd_data_dir.as_deref())?;
1092            // Always persist data_dir so `memd export-markdown` (and any
1093            // future CLI tool that needs the containment guard) can
1094            // auto-discover the daemon's data directory from a
1095            // nearest-ancestor `.memd/tenant_scope.json`.
1096            let scope_config = TenantScopeConfig {
1097                primary_tenant: tenant.to_string(),
1098                write_tenant: tenant.to_string(),
1099                data_dir: Some(effective_data_dir.display().to_string()),
1100            };
1101            let guardrail_block = render_guardrail_block(&scope_config, &memd_command);
1102
1103            let guardrail_path = memd_dir.join("memory_guardrails.md");
1104            let tenant_scope_path = memd_dir.join("tenant_scope.json");
1105            let project_scope_path = memd_dir.join("project_scope.json");
1106            let project_scope = ProjectScopeConfig {
1107                tenant_id: tenant.to_string(),
1108                project_id,
1109                interface: "cli".to_string(),
1110                cli_command: memd_command.clone(),
1111                agent_context_output: ".memd/context.md".to_string(),
1112                project_dir: project_dir.display().to_string(),
1113            };
1114
1115            std::fs::write(&guardrail_path, &guardrail_block)?;
1116            std::fs::write(
1117                &tenant_scope_path,
1118                format!("{}\n", serde_json::to_string_pretty(&scope_config)?),
1119            )?;
1120            std::fs::write(
1121                &project_scope_path,
1122                format!("{}\n", serde_json::to_string_pretty(&project_scope)?),
1123            )?;
1124
1125            let mut updated_files = Vec::new();
1126
1127            if write_agent_files {
1128                let agents_path = project_dir.join("AGENTS.md");
1129                let claude_path = project_dir.join("CLAUDE.md");
1130
1131                upsert_guardrail_file(&agents_path, &guardrail_block)?;
1132                upsert_guardrail_file(&claude_path, &guardrail_block)?;
1133                updated_files.push(agents_path);
1134                updated_files.push(claude_path);
1135            }
1136
1137            let result = json!({
1138                "tenant_id": tenant.to_string(),
1139                "project_dir": project_dir,
1140                "generated": {
1141                    "guardrail_markdown": guardrail_path,
1142                    "tenant_scope": tenant_scope_path,
1143                    "project_scope": project_scope_path
1144                },
1145                "scope": scope_config,
1146                "updated_files": updated_files,
1147                "interface": "cli"
1148            });
1149            println!("{}", serde_json::to_string_pretty(&result)?);
1150        }
1151    }
1152
1153    Ok(())
1154}
1155
1156#[cfg(test)]
1157mod tests;