memstead-cli 0.11.0

Command-line interface for Memstead — query and mutate typed entity graphs from the shell. Default build produces the full `memstead` binary (multi-mem, git-backed); `--no-default-features` builds the lean folder-only surface.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
use std::path::PathBuf;

use clap::{Parser, ValueEnum};
use serde_json::json;

use crate::CliError;
use crate::output::{ExitKind, print_json, print_markdown};
use crate::setup::{CliContext, CliEngine};

/// Export the write mem as markdown (in place), as a portable `.mem`
/// archive, or as a structured JSON document on stdout.
///
/// `--format markdown` is supported only on folder-backed mems; use
/// `--format mem` for archive export on git-branch backends. Targeting
/// a mem on an incompatible backend returns
/// `MARKDOWN_EXPORT_UNSUPPORTED_BACKEND`; workspace-wide markdown export
/// in a mixed-backend workspace completes the folder mounts and lists
/// the declined mounts under `skipped_mounts`.
///
/// `--format json` is the bulk read: one engine boot emits the complete
/// entity set — per entity the same structured envelope `memstead entity
/// --json` produces — grouped per mem, backend-uniform, observably
/// read-only. External projections and check scripts consume this
/// instead of per-entity CLI calls (which pay the engine boot per
/// entity) or raw git against the mem-repo.
#[derive(Parser, Debug)]
pub struct Args {
    /// Output format. `markdown` regenerates the mem directory in place
    /// (folder-backed mems only); `mem` writes a portable `.mem` zip
    /// suitable for sharing (every backend); `json` prints every
    /// non-stub entity of the selected mem(s) as one structured JSON
    /// document on stdout (every backend, read-only); `html` writes one
    /// self-contained page; `llms-txt` prints the whole mem as one
    /// agent-readable Markdown document (every backend, read-only) —
    /// the same shape a Memstead deployment serves at `/llms-full.txt`,
    /// rendered by the same engine code so the two cannot drift.
    #[arg(long, value_enum, default_value_t = Format::Markdown)]
    pub format: Format,

    /// Output path for `--format mem` (default `./<name>-<version>.mem`)
    /// and `--format html` (default `./<mem>.html`). Optional for
    /// `--format llms-txt`, which prints to stdout when omitted.
    /// Ignored for `--format markdown`; refused for `--format json`
    /// (that document goes to stdout).
    #[arg(long, short = 'o', value_name = "PATH")]
    pub output: Option<PathBuf>,

    /// Which mem to export (by name). For `--format markdown`, omitting
    /// this argument runs a workspace-wide export and reports any
    /// declined mounts under `skipped_mounts`. For `--format mem`,
    /// required when more than one write mem is loaded; defaults to
    /// the first writable mem otherwise. For `--format json`, omitting
    /// it exports every writable mem; naming a read-only mount exports
    /// that mount (read-mems are excluded from the workspace-wide
    /// default — they are someone else's published content).
    #[arg(long = "mem", value_name = "NAME")]
    pub mem_name: Option<String>,

    /// For `--format mem`: make the archive self-contained by dropping
    /// every `## Relationships` row whose target lives in another mem,
    /// then re-pack and strictly validate it (the same pass `install`
    /// runs). Without it, a mem that references its sibling mems exports
    /// with `DANGLING_CROSS_MEM_EDGE_IN_EXPORT` warnings and `install`
    /// refuses the archive; with it, every dropped edge is reported as
    /// `CROSS_MEM_EDGE_DROPPED` instead. Section text, body wiki-links
    /// included, is never touched: an alias row synthesised from a body
    /// link loses nothing the body does not still say.
    #[arg(long)]
    pub self_contained: bool,

    /// Absolute base URL for entity links in `--format llms-txt` (e.g.
    /// `https://example.com`). With it, references render as absolute
    /// links exactly as the served document does; without it they target
    /// the document-relative `entity/<id>`. There is no third form.
    /// Ignored by every other format.
    #[arg(long = "base-url", value_name = "URL")]
    pub base_url: Option<String>,
}

#[derive(ValueEnum, Clone, Copy, Debug)]
pub enum Format {
    /// Regenerate markdown files in place.
    Markdown,
    /// Write a `.mem` zip archive to `--output`.
    Mem,
    /// Print the full entity set as one JSON document on stdout.
    Json,
    /// Write one self-contained HTML file — the read surface for
    /// non-operators: no server, no scripts, zero network requests.
    Html,
    /// Write the whole mem as one agent-readable Markdown document —
    /// the `/llms-full.txt` shape, rendered by the same engine code the
    /// served endpoint uses, so the two cannot drift.
    LlmsTxt,
}

pub fn run(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    if matches!(args.format, Format::Json) {
        return run_json(ctx, args);
    }
    if matches!(args.format, Format::Html) {
        return run_html(ctx, args);
    }
    if matches!(args.format, Format::LlmsTxt) {
        return run_llms_txt(ctx, args);
    }
    match ctx.cli_engine()? {
        #[cfg(feature = "mem-repo")]
        CliEngine::MemRepo(engine) => match args.format {
            Format::Markdown => run_markdown(ctx, &engine, args.mem_name.as_deref()),
            Format::Mem => run_mem(ctx, &engine, args),
            Format::Json => unreachable!("dispatched to run_json above"),
            Format::Html => unreachable!("dispatched to run_html above"),
            Format::LlmsTxt => unreachable!("dispatched to run_llms_txt above"),
        },
        CliEngine::Filesystem(engine) => match args.format {
            // `--format markdown` regenerates files in place. The
            // filesystem engine's writer would do the same, but
            // there's no `export_markdown` accessor today; surface
            // the gap as a clear validation error rather than a
            // silent no-op.
            Format::Markdown => Err(CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                "--format markdown is not yet supported on filesystem-mem `memstead export` — entities are already on disk in their canonical form",
            )
            .into()),
            Format::Mem => run_mem_filesystem(ctx, &engine, args),
            Format::Json => unreachable!("dispatched to run_json above"),
            Format::Html => unreachable!("dispatched to run_html above"),
            Format::LlmsTxt => unreachable!("dispatched to run_llms_txt above"),
        },
    }
}

/// Version marker on the `--format json` document, following the
/// `workspace-dump/v0` convention: consumers assert the marker before
/// parsing so a future shape change fails loudly instead of silently.
const JSON_EXPORT_FORMAT: &str = "memstead-export/v1";

/// `--format json` — the bulk read. Backend-uniform (both engine
/// flavours serve it via [`CliEngine::base`]) and observably read-only:
/// pure store iteration, no engine mutation path is touched. Each
/// entity rides as the same structured envelope `memstead entity --json`
/// emits (plus mem-level grouping), so a consumer parses one entity
/// shape across both surfaces. Entities are sorted by id within each
/// mem for deterministic output; stubs are excluded (they are
/// unresolved references, not content).
fn run_json(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    // `-o` only means something for archive export. Refusing beats
    // silently ignoring: an operator who passed `-o dump.json` would
    // otherwise wait on a file that never appears.
    if args.output.is_some() {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            "--output applies only to --format mem — the JSON document goes to stdout; redirect it instead",
        )
        .into());
    }

    let cli_engine = ctx.cli_engine()?;
    let engine = cli_engine.base();

    let all_names: Vec<String> = engine.mem_names().into_iter().map(String::from).collect();
    // Named mem: any loaded mount qualifies, read-only included — an
    // explicit name is the opt-in. Workspace-wide default: writable
    // mems only; read-only mounts are someone else's published content.
    let selected: Vec<String> = match &args.mem_name {
        Some(name) => {
            if !all_names.iter().any(|n| n == name) {
                return Err(CliError::new(
                    ExitKind::NotFound,
                    "UNKNOWN_MEM",
                    format!(
                        "unknown mem '{name}' — loaded mems: {}",
                        all_names.join(", ")
                    ),
                )
                .with_details(json!({ "mem": name, "loaded": all_names }))
                .into());
            }
            vec![name.clone()]
        }
        None => all_names
            .iter()
            .filter(|n| engine.mem_router().is_writable(n))
            .cloned()
            .collect(),
    };

    let mut mems = serde_json::Map::new();
    for mem_name in &selected {
        // The authoritative schema pin lives in the mem's own config;
        // carried once at the group level rather than per entity.
        let schema_pin = engine
            .mem_configs_named()
            .find(|(name, _)| name == mem_name)
            .and_then(|(_, c)| c.schema.as_ref())
            .map(|s| s.to_string());

        let mut entities: Vec<&memstead_base::Entity> = engine
            .store()
            .all_entities()
            .filter(|e| !e.stub && e.mem == *mem_name)
            .collect();
        entities.sort_by(|a, b| a.id.as_ref().cmp(b.id.as_ref()));

        let envelopes: Vec<serde_json::Value> = entities
            .iter()
            .map(|entity| {
                let body = memstead_base::render::render_entity_markdown(entity, None);
                let tokens = memstead_base::chunking::estimate_tokens(&body);
                let outgoing = engine.store().outgoing(&entity.id);
                // Export is a canonical-form surface — computed
                // signals are a serving projection and stay out.
                memstead_base::render::build_entity_envelope(
                    entity,
                    tokens,
                    None,
                    None,
                    None,
                    engine.mem_origin_class(entity.id.mem()),
                    outgoing,
                    None,
                    None,
                    None,
                )
            })
            .collect();

        let mut group = serde_json::Map::new();
        if let Some(s) = schema_pin {
            group.insert("schema".to_string(), json!(s));
        }
        group.insert(
            "read_only".to_string(),
            json!(!engine.mem_router().is_writable(mem_name)),
        );
        group.insert("entity_count".to_string(), json!(envelopes.len()));
        group.insert("entities".to_string(), serde_json::Value::Array(envelopes));
        mems.insert(mem_name.clone(), serde_json::Value::Object(group));
    }

    print_json(&json!({
        "format": JSON_EXPORT_FORMAT,
        "mems": mems,
    }))
}

#[cfg(feature = "mem-repo")]
fn run_markdown(
    ctx: &CliContext,
    engine: &memstead_base::Engine,
    mem_filter: Option<&str>,
) -> anyhow::Result<()> {
    // The engine returns a
    // typed `MARKDOWN_EXPORT_UNSUPPORTED_BACKEND` when `--mem`
    // targets a mem whose backend doesn't support markdown
    // regeneration. The workspace-wide path returns counts plus a
    // structured `skipped_mounts` list.
    let result = engine
        .export_markdown(mem_filter, None)
        .map_err(CliError::from_engine_op)?;

    if ctx.json {
        let mut body = json!({
            "written": result.written,
            "unchanged": result.unchanged,
        });
        if !result.skipped_mounts.is_empty() {
            body["skipped_mounts"] = serde_json::to_value(&result.skipped_mounts)
                .unwrap_or_else(|_| serde_json::Value::Array(Vec::new()));
        }
        print_json(&body)?;
    } else {
        let mut block = format!(
            "# Export — markdown\n\n- Written: {}\n- Unchanged: {}",
            result.written, result.unchanged,
        );
        if !result.skipped_mounts.is_empty() {
            block.push_str("\n\n## Skipped mounts\n");
            for m in &result.skipped_mounts {
                block.push_str(&format!(
                    "\n- `{}` — backend `{}` ({}); use `--format mem` for archive export",
                    m.mem, m.active_backend, m.reason,
                ));
            }
        }
        print_markdown(&block);
    }
    Ok(())
}

#[cfg(feature = "mem-repo")]
fn run_mem(ctx: &CliContext, engine: &memstead_base::Engine, args: Args) -> anyhow::Result<()> {
    let mem_name = resolve_mem_name(engine, args.mem_name)?;
    let config = engine
        .mem_configs_named()
        .find(|(name, _)| *name == mem_name)
        .map(|(_, c)| c)
        .ok_or_else(|| {
            CliError::new(
                ExitKind::NotFound,
                "UNKNOWN_MEM",
                format!("mem config not found for '{mem_name}'"),
            )
        })?;

    let output = match args.output {
        Some(p) => p,
        None => default_output_path(&mem_name, config)?,
    };

    let mut result = engine
        .export_mem(&mem_name, &output)
        .map_err(CliError::from_engine_op)?;

    // `--self-contained`: drop the cross-mem rows the archive cannot
    // resolve, re-pack, strictly validate, and write the result over the
    // just-written file. The dropped edges replace the dangling warnings
    // in the report: they are the same edges, now gone instead of
    // refused later.
    let dropped = if args.self_contained {
        let self_contained = make_self_contained_on_disk(&output)?;
        result.size_bytes = self_contained.bytes.len() as u64;
        result.dangling_cross_mem_edges.clear();
        Some(self_contained.dropped)
    } else {
        None
    };

    // Surface each cross-mem edge
    // whose target won't travel inside the single-mem archive — these
    // are exactly what `install` will refuse, so showing them at export
    // time lets the operator act before sharing.
    let dangling = &result.dangling_cross_mem_edges;

    if ctx.json {
        let mut warnings: Vec<_> = dangling
            .iter()
            .map(|e| {
                json!({
                    "code": "DANGLING_CROSS_MEM_EDGE_IN_EXPORT",
                    "entity": e.entity_path,
                    "target_id": e.target_id,
                    "target_mem": e.target_mem,
                })
            })
            .collect();
        if let Some(dropped) = &dropped {
            warnings.extend(dropped.iter().map(|e| {
                json!({
                    "code": "CROSS_MEM_EDGE_DROPPED",
                    "entity": e.entity_path,
                    "target_id": e.target_id,
                    "target_mem": e.target_mem,
                })
            }));
        }
        print_json(&json!({
            "archive_path": result.archive_path,
            "name": result.name,
            "version": result.version,
            "entity_count": result.entity_count,
            "size_bytes": result.size_bytes,
            "self_contained": args.self_contained,
            "warnings": warnings,
        }))?;
    } else {
        let mut block = format!(
            "# Exported `{}` v{}\n\n- Archive: `{}`\n- Entities: {}\n- Size: {} bytes",
            result.name,
            result.version,
            result.archive_path,
            result.entity_count,
            result.size_bytes,
        );
        if args.self_contained {
            block.push_str("\n- Self-contained: yes");
        }
        if !dangling.is_empty() {
            block.push_str("\n\n## Warnings\n");
            for e in dangling {
                block.push_str(&format!(
                    "\n- **DANGLING_CROSS_MEM_EDGE_IN_EXPORT**: `{}` → `{}` (mem `{}`) — \
                     target lives outside this archive; `memstead install` will reject it unless \
                     mem `{}` is also present.",
                    e.entity_path, e.target_id, e.target_mem, e.target_mem,
                ));
            }
        }
        if let Some(dropped) = &dropped
            && !dropped.is_empty()
        {
            block.push_str("\n\n## Dropped cross-mem edges\n");
            for e in dropped {
                block.push_str(&format!(
                    "\n- **CROSS_MEM_EDGE_DROPPED**: `{}` → `{}` (mem `{}`): the relationship \
                     row does not travel; a body wiki-link to the same target still does.",
                    e.entity_path, e.target_id, e.target_mem,
                ));
            }
        }
        print_markdown(&block);
    }
    Ok(())
}

/// Apply [`memstead_base::validator::make_archive_self_contained`] to
/// the archive at `path`, writing the self-contained bytes back in place.
fn make_self_contained_on_disk(
    path: &std::path::Path,
) -> anyhow::Result<memstead_base::validator::SelfContainedArchive> {
    let bytes = std::fs::read(path).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("read {}: {e}", path.display()),
        )
    })?;
    let out = memstead_base::validator::make_archive_self_contained(&bytes).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "ARCHIVE_VALIDATION_FAILED",
            format!("self-contained re-pack of {}: {e}", path.display()),
        )
    })?;
    std::fs::write(path, &out.bytes).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("write {}: {e}", path.display()),
        )
    })?;
    Ok(out)
}

#[cfg(feature = "mem-repo")]
fn resolve_mem_name(
    engine: &memstead_base::Engine,
    explicit: Option<String>,
) -> anyhow::Result<String> {
    if let Some(name) = explicit {
        return Ok(name);
    }
    let writable: Vec<String> = engine
        .mem_configs_named()
        .filter(|(name, _)| engine.mem_router().is_writable(name))
        .map(|(name, _)| name.to_string())
        .collect();

    match writable.len() {
        0 => Err(CliError::new(
            ExitKind::Generic,
            "NO_WRITABLE_MEM",
            "no writable mem loaded — nothing to export",
        )
        .into()),
        1 => Ok(writable.into_iter().next().unwrap()),
        _ => Err(CliError::new(
            ExitKind::Validation,
            "AMBIGUOUS_MEM",
            format!(
                "multiple writable mems loaded ({}); pass --mem <name>",
                writable.join(", ")
            ),
        )
        .with_details(json!({ "mems": writable }))
        .into()),
    }
}

/// Filesystem-mem `memstead export --format mem` builds the `.mem`
/// archive bytes via [`memstead_base::filesystem::publish::assemble_archive`]
/// (the same path `memstead publish` uses on a filesystem-mem workspace)
/// and writes them to `--output` (defaulting to `<name>-<version>.mem`
/// in cwd). `--mem` is accepted for shape parity but only the
/// workspace's pinned mem matches.
fn run_mem_filesystem(
    ctx: &CliContext,
    engine: &memstead_base::Engine,
    args: Args,
) -> anyhow::Result<()> {
    let workspace_mem = engine
        .mem_names()
        .into_iter()
        .next()
        .map(String::from)
        .unwrap_or_default();
    if let Some(name) = args.mem_name.as_deref()
        && name != workspace_mem
    {
        return Err(CliError::new(
                ExitKind::NotFound,
                "UNKNOWN_MEM",
                format!(
                    "filesystem-mem is single-mem: workspace mem is `{workspace_mem}`, --mem `{name}` does not match"
                ),
            )
            .into());
    }

    // assemble_archive is engine-agnostic now — pass the discovered
    // workspace root directly.
    let workspace_root =
        crate::setup::find_filesystem_workspace_root(&std::env::current_dir().map_err(|e| {
            CliError::new(
                ExitKind::Generic,
                crate::INTERNAL_CODE,
                format!("current_dir: {e}"),
            )
        })?)
        .ok_or_else(|| {
            CliError::new(
                ExitKind::NotFound,
                "WORKSPACE_NOT_INITIALISED",
                "no filesystem-mem workspace found from cwd",
            )
        })?;
    let bytes =
        memstead_base::filesystem::publish::assemble_archive(&workspace_root).map_err(|e| {
            // F1: backend-symmetric typed envelope for the missing-
            // version case — the mem-repo path surfaces the same
            // MEM_CONFIG_INCOMPLETE via Engine::export_mem.
            if matches!(
                &e,
                memstead_base::filesystem::publish::AssembleError::Config(
                    memstead_schema::PublishConversionError::MissingVersion
                )
            ) {
                CliError::from_engine_op(memstead_base::EngineError::MemConfigIncomplete {
                    mem: workspace_mem.clone(),
                    missing_fields: vec!["version".to_string()],
                })
            } else {
                CliError::new(ExitKind::Generic, "ARCHIVE_ASSEMBLY_FAILED", e.to_string())
            }
        })?;

    let output = match args.output {
        Some(p) => p,
        None => {
            // Filesystem-mem config doesn't carry `version` today —
            // archive identity is `<mem_name>.mem` until the
            // assemble path threads a version through. Operator can
            // override with `-o`.
            PathBuf::from(format!(
                "{workspace_mem}.{}",
                memstead_schema::ARCHIVE_EXTENSION
            ))
        }
    };

    std::fs::write(&output, &bytes).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            crate::INTERNAL_CODE,
            format!("write {}: {e}", output.display()),
        )
    })?;
    let dropped = if args.self_contained {
        Some(make_self_contained_on_disk(&output)?.dropped)
    } else {
        None
    };
    let size_bytes = std::fs::metadata(&output)
        .map(|m| m.len() as usize)
        .unwrap_or(bytes.len());
    // Count only the exported mem's entities — the store also holds
    // mounted sibling mems (the multi-mount setup), which do not travel
    // in this archive.
    let entity_count = engine
        .store()
        .all_entities()
        .filter(|e| !e.stub && e.id.mem() == workspace_mem)
        .count();

    if ctx.json {
        let warnings: Vec<_> = dropped
            .iter()
            .flatten()
            .map(|e| {
                json!({
                    "code": "CROSS_MEM_EDGE_DROPPED",
                    "entity": e.entity_path,
                    "target_id": e.target_id,
                    "target_mem": e.target_mem,
                })
            })
            .collect();
        print_json(&json!({
            "archive_path": output.to_string_lossy(),
            "name": workspace_mem,
            "entity_count": entity_count,
            "size_bytes": size_bytes,
            "self_contained": args.self_contained,
            "warnings": warnings,
        }))?;
    } else {
        let mut block = format!(
            "# Exported `{workspace_mem}`\n\n- Archive: `{}`\n- Entities: {}\n- Size: {} bytes",
            output.display(),
            entity_count,
            size_bytes,
        );
        if args.self_contained {
            block.push_str("\n- Self-contained: yes");
            let n = dropped.as_ref().map(|d| d.len()).unwrap_or(0);
            if n > 0 {
                block.push_str(&format!("\n- Cross-mem edges dropped: {n}"));
            }
        }
        print_markdown(&block);
    }
    Ok(())
}

#[cfg(feature = "mem-repo")]
fn default_output_path(
    mem_name: &str,
    config: &memstead_schema::MemConfig,
) -> anyhow::Result<PathBuf> {
    let version = config.version.as_ref().ok_or_else(|| {
        // F1: typed envelope replaces the pre-fix INTERNAL-collapse
        // path (config lives at
        // `__MEMSTEAD:mems/<name>/config.json` for the mem-repo
        // backend). The recovery hint
        // names the engine-owned setter that mutates the right
        // surface for whichever backend serves the mem.
        CliError::from_engine_op(memstead_base::EngineError::MemConfigIncomplete {
            mem: mem_name.to_string(),
            missing_fields: vec!["version".to_string()],
        })
    })?;
    // The mem name is supplied by the caller (engine mem state)
    // rather than pulled from the now-optional in-config `name` field.
    let filename = format!(
        "{mem_name}-{version}.{}",
        memstead_schema::ARCHIVE_EXTENSION
    );
    Ok(PathBuf::from(filename))
}

/// `--format llms-txt` — the whole mem as one Markdown document an agent can
/// read in a single pass. Backend-uniform via [`CliEngine::base`] and
/// observably read-only, like `--format json`.
///
/// The document shape is the engine's, shared with the served
/// `/llms-full.txt` endpoint. This function supplies only what a *deployment*
/// would otherwise supply and a CLI cannot: the link base. It deliberately
/// supplies no authority and no wider-project block — a file exported from
/// someone's own workspace has no deployment vouching for it, and a header
/// claiming otherwise would put a false provenance line atop the one document
/// written to be read whole.
fn run_llms_txt(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    let engine_holder = ctx.cli_engine()?;
    let engine = engine_holder.base();
    let mem = resolve_single_mem(engine, args.mem_name.as_deref())?;

    let ctx_opts = memstead_base::engine::export_llms_txt::LlmsTxtContext {
        authority: None,
        href_prefix: args
            .base_url
            .clone()
            .map(|u| u.trim_end_matches('/').to_string())
            .unwrap_or_default(),
        wider_project: Vec::new(),
    };
    let doc = engine
        .render_llms_txt(&mem, &ctx_opts)
        .map_err(CliError::from_engine_op)?;

    match &args.output {
        Some(path) => {
            std::fs::write(path, &doc).map_err(|e| {
                CliError::new(
                    ExitKind::Generic,
                    "IO_ERROR",
                    format!("write {}: {e}", path.display()),
                )
            })?;
            if ctx.json {
                print_json(&serde_json::json!({
                    "mem": mem,
                    "written": path.display().to_string(),
                    "bytes": doc.len(),
                }))?;
            } else {
                println!("Wrote {} ({} bytes)", path.display(), doc.len());
            }
        }
        // No `-o` prints the document itself — it is text meant to be read or
        // piped, so stdout is the natural destination rather than a file the
        // caller then has to find.
        None => print!("{doc}"),
    }
    Ok(())
}

/// Resolve the one mem an export targets: an explicit `--mem` wins (read-only
/// mounts allowed); otherwise the sole writable mem, refusing when there is
/// none or several rather than picking one.
fn resolve_single_mem(
    engine: &memstead_base::Engine,
    requested: Option<&str>,
) -> Result<String, CliError> {
    if let Some(m) = requested {
        return Ok(m.to_string());
    }
    let writables: Vec<String> = engine
        .writable_mem_names()
        .iter()
        .map(|s| s.to_string())
        .collect();
    match writables.as_slice() {
        [one] => Ok(one.clone()),
        [] => Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            "no writable mem loaded — pass --mem <name>",
        )),
        _ => Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            format!(
                "multiple writable mems loaded ({}) — pass --mem <name>",
                writables.join(", ")
            ),
        )),
    }
}

/// `--format html` — one self-contained HTML file per mem (the read
/// surface for non-operators). Backend-uniform via [`CliEngine::base`]
/// and observably read-only. The export date is stamped once (UTC);
/// `--today` on `memstead due` has no analogue here because the date
/// only labels the export, it never filters.
fn run_html(ctx: &CliContext, args: Args) -> anyhow::Result<()> {
    let engine_holder = ctx.cli_engine()?;
    let engine = engine_holder.base();
    // Resolve the target mem like `--format mem`: explicit name wins
    // (read-only mounts allowed); otherwise the sole writable mem.
    let mem = match &args.mem_name {
        Some(m) => m.clone(),
        None => {
            let writables: Vec<String> = engine
                .writable_mem_names()
                .iter()
                .map(|s| s.to_string())
                .collect();
            match writables.as_slice() {
                [one] => one.clone(),
                [] => {
                    return Err(CliError::new(
                        ExitKind::Validation,
                        "INVALID_INPUT",
                        "no writable mem loaded — pass --mem <name>",
                    )
                    .into());
                }
                _ => {
                    return Err(CliError::new(
                        ExitKind::Validation,
                        "INVALID_INPUT",
                        format!(
                            "multiple writable mems loaded ({}) — pass --mem <name>",
                            writables.join(", ")
                        ),
                    )
                    .into());
                }
            }
        }
    };
    let now = time::OffsetDateTime::now_utc();
    let export_date = format!(
        "{:04}-{:02}-{:02}",
        now.year(),
        u8::from(now.month()),
        now.day()
    );
    let html = engine
        .render_html_export(&mem, &export_date)
        .map_err(CliError::from_engine_op)?;
    let out_path = args
        .output
        .clone()
        .unwrap_or_else(|| PathBuf::from(format!("{mem}.html")));
    std::fs::write(&out_path, &html).map_err(|e| {
        CliError::new(
            ExitKind::Generic,
            "IO_ERROR",
            format!("write {}: {e}", out_path.display()),
        )
    })?;
    if ctx.json {
        print_json(&serde_json::json!({
            "format": "html",
            "mem": mem,
            "path": out_path,
            "bytes": html.len(),
            "exported": export_date,
        }))?;
    } else {
        print_markdown(&format!(
            "# HTML export\n\n- Mem: `{mem}`\n- File: `{}`\n- Size: {} bytes\n- Exported: {export_date}\n\nSelf-contained — open it from anywhere, no server needed.\n",
            out_path.display(),
            html.len()
        ));
    }
    Ok(())
}

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

    /// Mem selection is `--mem`, converged onto the convention every
    /// other subcommand uses; the former `--mem-name` outlier is gone.
    #[test]
    fn export_mem_selection_flag_is_mem_not_mem_name() {
        let parsed = Args::try_parse_from(["export", "--mem", "specs", "--format", "mem"]).unwrap();
        assert_eq!(parsed.mem_name.as_deref(), Some("specs"));
        assert!(
            Args::try_parse_from(["export", "--mem-name", "specs"]).is_err(),
            "the retired --mem-name flag must not parse"
        );
    }
}