memstead-cli 0.18.1

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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
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. A `mem`
    /// archive's authoring provenance (`.memstead/provenance.json`) has
    /// every private-pattern span redacted to `[redacted:<class>]` —
    /// the leak scan's classes, one vocabulary — never stripped; the
    /// report counts redactions per class. Entity bodies are not
    /// rewritten.
    #[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>,

    /// Export only the chain reachable from this entity (`mem--slug`)
    /// instead of the whole mem — for `--format json`, `html` and
    /// `llms-txt`. Requires `--via`. The root itself is always included;
    /// each rendered entity keeps its metadata, sections, relationships
    /// and (json) its anchors with live state; stubs in the chain are
    /// marked; references to entities outside the chain render as
    /// unresolved markers, never as broken links. Without `--root` the
    /// export is the whole mem, byte-identical to before.
    #[arg(long, value_name = "ID")]
    pub root: Option<String>,

    /// Rel-types the chain follows, comma-separated or repeatable
    /// (`--via SUPPORTS,DERIVES_FROM`). Validated against the mem's
    /// schema vocabulary: an unknown name refuses `INVALID_REL_TYPE`
    /// naming the declared rel-types. Only with `--root`.
    #[arg(long, value_name = "REL", value_delimiter = ',')]
    pub via: Vec<String>,

    /// Direction applied at EVERY hop of the chain: `out` follows edges
    /// pointing away from the root (what the root rests on), `in`
    /// follows edges pointing at it (what rests on the root), `both`
    /// the undirected walk. A pure transitive closure in the chosen
    /// direction, the same contract `memstead search` uses.
    #[arg(long, value_enum, default_value_t = ChainDirection::Out)]
    pub direction: ChainDirection,

    /// Maximum hops from the root (default: unbounded). `--depth 1` is
    /// the root and its direct neighbours along `--via`.
    #[arg(long, value_name = "N")]
    pub depth: Option<usize>,

    /// 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>,

    /// Opt extra per-entity content into the `--format json` document
    /// (comma-separated). Keys: `anchors` — each entity envelope gains
    /// an `anchors` array with its stored provenance anchors, so the
    /// file-to-entity map a carving or sync pass starts from is one
    /// export instead of one `memstead anchors <id>` per entity. An
    /// unknown key refuses naming the allowed set; refused for every
    /// other format.
    #[arg(long, value_delimiter = ',', value_name = "KEY")]
    pub include: Vec<String>,
}

/// `--direction` for a chain export — the wire words of the engine's
/// `TraversalDirection`, one value each.
#[derive(clap::ValueEnum, Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChainDirection {
    Out,
    In,
    Both,
}

impl From<ChainDirection> for memstead_base::graph::query::TraversalDirection {
    fn from(d: ChainDirection) -> Self {
        match d {
            ChainDirection::Out => Self::Out,
            ChainDirection::In => Self::In,
            ChainDirection::Both => Self::Both,
        }
    }
}

/// The chain scope a caller asked for, or `None` for the whole mem.
fn chain_scope(args: &Args) -> Option<memstead_base::graph::chain::ChainScope> {
    args.root
        .as_deref()
        .map(|root| memstead_base::graph::chain::ChainScope {
            root: memstead_base::EntityId::canonical(root),
            via: args.via.clone(),
            direction: args.direction.into(),
            depth: args.depth.unwrap_or(usize::MAX),
        })
}

#[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<()> {
    // The chain flags travel together, refused typed (not as a clap usage
    // error) so an agent reads the same envelope every other refusal has.
    if args.root.is_some() && args.via.is_empty() {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            "--root selects a chain and needs --via <REL[,REL]>: the rel-types the chain follows",
        )
        .with_details(json!({ "field": "via" }))
        .into());
    }
    if args.root.is_none() && (!args.via.is_empty() || args.depth.is_some()) {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            "--via and --depth describe a chain and need --root <ID>",
        )
        .with_details(json!({ "field": "root" }))
        .into());
    }
    if args.root.is_some() && !matches!(args.format, Format::Json | Format::Html | Format::LlmsTxt)
    {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            "--root selects a chain within a rendered export (json, html, llms-txt); the \
             markdown regeneration and the .mem archive always carry the whole mem",
        )
        .into());
    }
    if !args.include.is_empty() && !matches!(args.format, Format::Json) {
        return Err(CliError::new(
            ExitKind::Validation,
            "INVALID_INPUT",
            "--include applies only to --format json",
        )
        .into());
    }
    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/v1` 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());
    }

    // Include-key validation — one key today; an unknown key refuses
    // naming the allowed set rather than silently exporting less than
    // the caller asked for.
    const JSON_INCLUDE_KEYS: &[&str] = &["anchors"];
    for key in &args.include {
        if !JSON_INCLUDE_KEYS.contains(&key.as_str()) {
            return Err(CliError::new(
                ExitKind::Validation,
                "INVALID_INPUT",
                format!(
                    "unknown --include key {key:?} — allowed: {}",
                    JSON_INCLUDE_KEYS.join(", ")
                ),
            )
            .into());
        }
    }
    let include_anchors = args.include.iter().any(|k| k == "anchors");

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

    // A chain is resolved once, against the root's mem (the mem is
    // implied by the root when `--mem` is omitted).
    let scope = chain_scope(&args);
    let chain = match &scope {
        Some(scope) => {
            let mem = args
                .mem_name
                .clone()
                .unwrap_or_else(|| scope.root.mem().to_string());
            Some((
                mem.clone(),
                engine
                    .chain_set(&mem, scope)
                    .map_err(CliError::from_engine_op)?,
            ))
        }
        None => None,
    };

    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 chain.as_ref().map(|(m, _)| m).or(args.mem_name.as_ref()) {
        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
            .mounts_with_optional_config()
            .find(|(name, _)| name == mem_name)
            .and_then(|(_, c)| c)
            .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)
            .filter(|e| chain.as_ref().is_none_or(|(_, c)| c.contains(&e.id)))
            .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.
                let mut envelope = memstead_base::render::build_entity_envelope(
                    entity,
                    tokens,
                    None,
                    None,
                    None,
                    engine.mem_origin_class(entity.id.mem()),
                    outgoing,
                    None,
                    None,
                    None,
                );
                // `--include anchors`: the stored provenance anchors ride
                // each envelope, so the file-to-entity map a carving pass
                // starts from is one export instead of one `memstead
                // anchors <id>` per entity. Canonical stored form, no
                // live resolution — this stays a pure read.
                if include_anchors && let Some(obj) = envelope.as_object_mut() {
                    let anchors = engine.entity_anchors(&entity.id);
                    obj.insert(
                        "anchors".to_string(),
                        serde_json::to_value(&anchors).unwrap_or(serde_json::Value::Null),
                    );
                }
                // A chain export is an auditor's read: every node carries
                // its anchors WITH live state (artifact, grain, class,
                // state), so one export answers what each link in the
                // chain rests on and whether it still holds.
                if chain.is_some()
                    && !include_anchors
                    && let Some(obj) = envelope.as_object_mut()
                {
                    let resolved = engine.entity_anchors_resolved(&entity.id);
                    obj.insert(
                        "anchors".to_string(),
                        serde_json::to_value(&resolved).unwrap_or(serde_json::Value::Null),
                    );
                }
                envelope
            })
            .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));
        // The chain itself: what was asked for, and the induced subgraph
        // (nodes in this mem, edges with both ends in the chain) — the
        // same node and edge set the ui-api topology endpoint returns for
        // the same scope, so the two surfaces can be compared directly.
        if let Some((_, chain_set)) = &chain {
            let topology = engine
                .mem_topology_scoped(mem_name, Some(chain_set))
                .map_err(CliError::from_engine_op)?;
            group.insert(
                "chain".to_string(),
                json!({
                    "root": chain_set.scope.root.to_string(),
                    "via": chain_set.scope.via,
                    "direction": chain_set.scope.direction.as_wire(),
                    "depth": (chain_set.scope.depth != usize::MAX).then_some(chain_set.scope.depth),
                    "nodes": topology.nodes.iter().map(|n| &n.id).collect::<Vec<_>>(),
                    "edges": topology.edges,
                    "reached": chain_set.reached.iter().map(|r| json!({
                        "id": r.id.to_string(),
                        "via_edge": r.via_edge,
                        "depth": r.depth,
                        "direction": r.direction.as_wire(),
                    })).collect::<Vec<_>>(),
                }),
            );
        }
        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()));
        }
        if !result.refused_entities.is_empty() {
            body["refused_entities"] = serde_json::to_value(&result.refused_entities)
                .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,
                ));
            }
        }
        // Never silent: an entity the export declined is one the operator has
        // to repair through the engine, and an export that reported only
        // counts would read as complete over content it did not write.
        if !result.refused_entities.is_empty() {
            block.push_str("\n\n## Refused entities\n");
            for r in &result.refused_entities {
                block.push_str(&format!("\n- `{}` [{}] — {}", r.id, r.reason, r.detail));
            }
        }
        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)?;
    // Deliberately the config-keyed query: a mem-archive export cannot be
    // built without the config it packages, so "no config" is a genuine
    // refusal here rather than a mount to enumerate (04/05, criterion 8 —
    // the criterion is that no consumer SILENTLY skips, and this one refuses
    // by 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,
                })
            }));
        }
        warnings.extend(result.unterminated_fence_entities.iter().map(|id| {
            json!({
                "code": "UNTERMINATED_FENCE_IN_EXPORT",
                "entity": id,
            })
        }));
        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,
            "redactions": result.redactions,
            "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 !result.redactions.is_empty() {
            let listed: Vec<String> = result
                .redactions
                .iter()
                .map(|r| format!("{} {}", r.class, r.count))
                .collect();
            block.push_str(&format!(
                "\n- Redacted in provenance: {} (each span reads `[redacted:<class>]`)",
                listed.join(", ")
            ));
        }
        // `install` will refuse the archive for each of these, so the operator
        // learns it here rather than after sharing.
        if !result.unterminated_fence_entities.is_empty() {
            block.push_str(
                "\n\n## Entities `install` will refuse\n\nEach ends a section inside an \
                 unterminated code fence, which absorbed the sections after it. Repair through \
                 the engine (replace the absorbing section) and re-export.\n",
            );
            for id in &result.unterminated_fence_entities {
                block.push_str(&format!("\n- `{id}` [UNTERMINATED_FENCE_IN_EXPORT]"));
            }
        }
        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. Re-export with `--self-contained` to drop such \
                     rows (each reported; body wiki-link prose survives).",
                    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);
    }
    // Every mount (04/05, criterion 8): a broken mem is still a writable mem
    // for the purpose of "is the target unambiguous", and omitting it turns an
    // ambiguous workspace into a silently-resolved one.
    let writable: Vec<String> = engine
        .mounts_with_optional_config()
        .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::Engine::export_mem_to_bytes`]
/// (the same primitive the mem-repo path and `memstead publish --mem`
/// use) and writes them to `--output` (defaulting to `<name>.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());
    }

    // Export through the ENGINE, which reads whatever layout it
    // booted: the mount roster locates the mem's folder and its
    // `.memstead/config.json` inside it. The legacy assemble path
    // resolved the config against the WORKSPACE root instead — in the
    // legacy single-mem layout the two coincide, but in the current
    // (`workspace.toml` + `state/mounts.json`) layout they do not, so
    // `export --format mem` failed on every workspace `quickstart`
    // produces while the rest of the CLI worked (sealed-gate finding
    // F6). One exporter for every backend also keeps the typed
    // refusals backend-symmetric (MEM_CONFIG_INCOMPLETE on a missing
    // version, F1) without a special-cased mapping.
    let report = engine
        .export_mem_bytes_report(&workspace_mem)
        .map_err(CliError::from_engine_op)?;
    let bytes = report.bytes;

    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,
            "redactions": report.redactions,
            "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 !report.redactions.is_empty() {
            let listed: Vec<String> = report
                .redactions
                .iter()
                .map(|r| format!("{} {}", r.class, r.count))
                .collect();
            block.push_str(&format!(
                "\n- Redacted in provenance: {} (each span reads `[redacted:<class>]`)",
                listed.join(", ")
            ));
        }
        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();
    // A chain's root implies the mem when `--mem` is omitted.
    let implied_mem = args
        .root
        .as_deref()
        .map(|r| memstead_base::EntityId::canonical(r).mem().to_string());
    let mem = resolve_single_mem(engine, args.mem_name.as_deref().or(implied_mem.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 chain = match chain_scope(&args) {
        Some(scope) => Some(
            engine
                .chain_set(&mem, &scope)
                .map_err(CliError::from_engine_op)?,
        ),
        None => None,
    };
    let doc = engine
        .render_llms_txt_scoped(&mem, &ctx_opts, chain.as_ref())
        .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); a chain's root implies its mem;
    // otherwise the sole writable mem.
    let implied_mem = args
        .root
        .as_deref()
        .map(|r| memstead_base::EntityId::canonical(r).mem().to_string());
    let mem = match args.mem_name.as_ref().or(implied_mem.as_ref()) {
        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 chain = match chain_scope(&args) {
        Some(scope) => Some(
            engine
                .chain_set(&mem, &scope)
                .map_err(CliError::from_engine_op)?,
        ),
        None => None,
    };
    let html = engine
        .render_html_export_scoped(&mem, &export_date, chain.as_ref())
        .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"
        );
    }
}