memstead-cli 0.6.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
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
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
#![cfg(feature = "mem-repo")]
//! Integration tests for `memstead` read subcommands.
//!
//! Each test sets up a fresh temp mem with one or two entities and runs the
//! binary as a subprocess. Tests cover: default markdown output, `--json`
//! output, and typed exit codes.

use std::fs;
use std::path::Path;

use assert_cmd::Command;
use memstead_git_branch::test_support::init_real_mem_repo_from_disk;
use predicates::prelude::*;
use predicates::str::contains;
use tempfile::TempDir;

/// Seed a canonical `cli-test/` mem dir under `root`. Returns the
/// mem's absolute path. The dir basename equals the declared
/// `name: "cli-test"` so the engine's basename-invariant holds.
///
/// Also lays down `<root>/mem-repo/.git/` so the engine's
/// `mem-repo/.git/` fail-fast accepts the workspace and so
/// `find_workspace_root` (the CLI's walk-up) resolves `<root>` as the
/// workspace.
fn seed_cli_test_mem(root: &Path) -> std::path::PathBuf {
    let dir = root.join("cli-test");
    fs::create_dir_all(&dir).unwrap();
    make_test_mem(&dir);
    init_real_mem_repo_from_disk(root, &[(&dir, "cli-test")]);
    dir
}

/// Write a minimal single-type mem with one basic entity into `dir`.
fn make_test_mem(dir: &Path) {
    let store = dir.join(".memstead");
    fs::create_dir_all(&store).unwrap();
    fs::write(
        store.join("config.json"),
        r#"{ "schema": "default@1.0.0" }"#,
    )
    .unwrap();

    fs::write(
        dir.join("alpha.md"),
        r#"---
type: spec
created_date: 2026-01-01
last_modified: 2026-01-01
level: M0
---
# Alpha

## Identity

The alpha entity used to exercise CLI read commands.

## Purpose

Verifies memstead CLI integration end-to-end.

## Relationships

- **USES**: [[beta]]
"#,
    )
    .unwrap();

    fs::write(
        dir.join("beta.md"),
        r#"---
type: spec
created_date: 2026-01-02
last_modified: 2026-01-02
level: M0
---
# Beta

## Identity

The beta entity, used by alpha via USES.

## Purpose

Provides a second entity so relations and path commands have something to trace.
"#,
    )
    .unwrap();
}

fn memstead() -> Command {
    Command::cargo_bin("memstead").expect("memstead binary must be built by cargo")
}

#[test]
fn status_markdown() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("status")
        .assert()
        .success()
        .stdout(contains("# Graph status"))
        .stdout(contains("Nodes: 2"));
}

/// Smoke-test Bug 2 closure for `memstead status` on a filesystem-mem
/// workspace. Pre-CLI-parity, this command would error out with the
/// "No mems found. Run `memstead mem-repo init`" message; post the
/// `CliEngine` foundation the command dispatches into the unified
/// `memstead_base::Engine` (lean path) and emits the same shape the
/// mem-repo path produces.
#[test]
fn status_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    // `memstead init --name demo --schema default@1.0.0` lays down
    // `.memstead/config.json` plus the empty cache / memstead-io subdirs.
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", "demo", "--schema", "default@1.0.0"])
        .assert()
        .success();

    // Empty filesystem-mem has zero entities — the command must
    // still produce the canonical markdown layout, not bail.
    memstead()
        .current_dir(tmp.path())
        .arg("status")
        .assert()
        .success()
        .stdout(contains("# Graph status"))
        .stdout(contains("Nodes: 0"));
}

#[test]
fn status_json() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "status"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let parsed: serde_json::Value = serde_json::from_slice(&output).expect("valid JSON");
    assert_eq!(parsed["total_nodes"], 2);
    assert_eq!(parsed["real_nodes"], 2);
}

#[test]
fn entity_markdown() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-test--alpha"])
        .assert()
        .success()
        .stdout(contains("# Alpha"))
        .stdout(contains("## Identity"))
        .stdout(contains("_hash:"));
}

/// Helper: lay down a filesystem-mem workspace at `tmp` with one
/// entity hand-shaped as `demo--alpha`. Returns the path to the
/// workspace root. Used by the suite of filesystem-mem dispatch
/// tests for read-side subcommands.
fn seed_filesystem_mem(tmp: &TempDir) {
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", "demo", "--schema", "default@1.0.0"])
        .assert()
        .success();
    fs::write(
        tmp.path().join("alpha.md"),
        r#"---
type: spec
created_date: 2026-01-01
last_modified: 2026-01-01
level: M0
---
# Alpha

## Identity

A filesystem-mem entity exercising CLI parity.

## Purpose

Lets the read-side CLI commands round-trip without the mem-repo path.
"#,
    )
    .unwrap();
}

#[test]
fn list_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .arg("list")
        .assert()
        .success()
        .stdout(contains("demo--alpha"));
}

#[test]
fn search_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .args(["search", "Alpha"])
        .assert()
        .success()
        .stdout(contains("Alpha"));
}

#[test]
fn relations_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .args(["relations", "demo--alpha"])
        .assert()
        .success()
        .stdout(contains("demo--alpha"));
}

#[test]
fn overview_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .arg("overview")
        .assert()
        .success();
}

/// `overview --json`
/// promotes `overview_mode`, `total_chunks`, and `hints` to structured
/// envelope siblings so a consumer branches on the mode / fetches the
/// next chunk without parsing the `markdown` string. The `markdown`
/// field stays present (promotion is additive).
#[test]
fn overview_json_promotes_mode_chunks_and_hints_as_siblings() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "overview"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let parsed: serde_json::Value = serde_json::from_slice(&output).expect("valid JSON");

    assert!(
        parsed.get("markdown").and_then(|v| v.as_str()).is_some(),
        "markdown field must remain for the human-rendered view: {parsed}"
    );
    let mode = parsed
        .get("overview_mode")
        .and_then(|v| v.as_str())
        .expect("overview_mode promoted as a sibling");
    assert!(
        matches!(mode, "complete" | "reduced" | "overbudget"),
        "overview_mode must be a known value, got: {mode}"
    );
    assert!(
        parsed
            .get("total_chunks")
            .and_then(|v| v.as_u64())
            .is_some(),
        "total_chunks must be a numeric sibling: {parsed}"
    );
    assert!(
        parsed.get("hints").map(|v| v.is_array()).unwrap_or(false),
        "hints must be an array sibling: {parsed}"
    );
}

#[test]
fn context_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .args(["context", "demo--alpha"])
        .assert()
        .success();
}

#[test]
fn health_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    seed_filesystem_mem(&tmp);

    memstead()
        .current_dir(tmp.path())
        .arg("health")
        .assert()
        .success()
        .stdout(contains("# Graph health"));
}

/// `memstead entity <id>` on a filesystem-mem workspace dispatches via
/// the `CliEngine::Filesystem` arm and reads the entity from the
/// directory walk. Pre-CLI-parity this errored with the
/// "No mems found" bail; post the foundation it round-trips.
#[test]
fn entity_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", "demo", "--schema", "default@1.0.0"])
        .assert()
        .success();

    // Drop a hand-shaped entity .md so the engine's directory walk
    // picks it up on init. Avoids a `memstead create` round-trip until
    // that command also dispatches through `CliEngine`.
    fs::write(
        tmp.path().join("alpha.md"),
        r#"---
type: spec
created_date: 2026-01-01
last_modified: 2026-01-01
level: M0
---
# Alpha

## Identity

A filesystem-mem entity exercising CLI parity.

## Purpose

Lets `memstead entity` round-trip without the mem-repo path.
"#,
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "demo--alpha"])
        .assert()
        .success()
        .stdout(contains("# Alpha"))
        .stdout(contains("## Identity"))
        .stdout(contains("_hash:"));
}

#[test]
fn entity_not_found_exit_code_3() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-test--does-not-exist"])
        .assert()
        .failure()
        .code(3)
        .stderr(contains("Entity not found"));
}

/// A missing/unmatched `--mem` is a not-found condition — exit 3 on
/// every command, the same bucket as the `entity <missing>` precedent
/// above. Locks the uniform `UNKNOWN_MEM` → `NotFound` mapping across
/// the read-scoped read path (`search`/`list`), `changes`, and the
/// engine-error path (`reload`). Measured standalone, not through a
/// pipe — a pipe would mask the exit through the last process.
#[test]
fn unknown_mem_exit_code_3() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    for args in [
        vec!["search", "x", "--mem", "nope"],
        vec!["list", "--mem", "nope"],
        vec!["reload", "--mem", "nope"],
        vec!["changes", "--since", "HEAD", "--mem", "nope"],
    ] {
        memstead()
            .current_dir(tmp.path())
            .args(&args)
            .assert()
            .failure()
            .code(3);
    }
}

#[test]
fn entity_not_found_json_envelope() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    let assert = memstead()
        .current_dir(tmp.path())
        .args(["--json", "entity", "cli-test--does-not-exist"])
        .assert()
        .failure()
        .code(3);
    // Under `--json` the error envelope rides stdout
    // so `… --json | jq -r .code` works on the error path.
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    let envelope: serde_json::Value = serde_json::from_str(stdout.trim()).expect("JSON envelope");
    // Wire shape: `{code, message, details}` matching MCP. Process exit
    // stays at the NotFound exit-kind (numeric 3) but it rides on the
    // process-status channel rather than inside the JSON body.
    assert_eq!(envelope["code"], "ENTITY_NOT_FOUND");
    assert!(
        envelope["message"]
            .as_str()
            .unwrap()
            .contains("Entity not found")
    );
}

#[test]
fn relations_markdown() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["relations", "cli-test--alpha"])
        .assert()
        .success()
        .stdout(contains("## Outgoing"))
        .stdout(contains("USES"));
}

#[test]
fn search_finds_entity() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["search", "alpha"])
        .assert()
        .success()
        .stdout(contains("Alpha"));
}

#[test]
fn list_all() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("list")
        .assert()
        .success()
        .stdout(contains("Alpha"))
        .stdout(contains("Beta"));
}

#[test]
fn overview_runs() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("overview")
        .assert()
        .success();
}

/// Full CLI's overview command renders the rich content (community
/// bridges, mem distribution, dangling links) via the shared
/// `memstead-engine::overview::compose_overview` composer. The full CLI
/// renders the content directly: when `--include` is passed the
/// `OVERVIEW_RICH_CONTENT_FULL_ONLY` (formerly `mcp_only_notice`)
/// warning string must not appear in the response.
#[test]
fn overview_with_include_renders_rich_content_without_full_only_warning() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args([
            "overview",
            "--include",
            "mem_distribution,community_bridges,dangling_links",
        ])
        .assert()
        .success()
        .stdout(contains("## Schemas"))
        .stdout(contains("## Mems"))
        // The lean CLI's pre-lift output would have included this
        // warning code; the full CLI's shared-composer path does NOT.
        .stdout(predicates::str::contains("OVERVIEW_RICH_CONTENT_FULL_ONLY").not())
        // Full CLI uses `memstead type <name>` for the schema-lookup hint,
        // not the MCP-flavour `memstead_schema(name=...)`.
        .stdout(contains("`memstead type <name>`"));
}

#[test]
fn type_named() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["type", "spec"])
        .assert()
        .success()
        .stdout(contains("# Type: spec"))
        .stdout(contains("## Sections"));
}

#[test]
fn health_summary() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .arg("health")
        .assert()
        .success()
        .stdout(contains("# Graph health"))
        .stdout(contains("Entities: 2"));
}

/// Seed a workspace whose mem uses a custom schema with one
/// `required_outgoing` block (decision needs CHOSEN). When
/// `with_violation` is true, a single decision entity is authored
/// without any CHOSEN edge so `memstead_health
/// include=missing_required_outgoing` reports one violator;
/// otherwise the mem has no entities and the report is empty.
fn seed_strict_health_workspace(root: &Path, with_violation: bool) {
    // Authored schema at the fixed folder-backend location
    // (`<workspace>/.memstead/schemas/`); the `schemas_dir` key is retired.
    let schema_dir = root
        .join(".memstead")
        .join("schemas")
        .join("strictdecision");
    fs::create_dir_all(schema_dir.join("types")).unwrap();
    fs::write(
        schema_dir.join("schema.yaml"),
        r#"name: strictdecision
version: 0.1.0
description: Minimal schema pinning required_outgoing for the CLI --strict test.
when_to_use: Used only by memstead-cli health-strict integration tests.
types:
  - decision
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hierarchy
      default_weight: 3.0
      acyclic: true
    - name: REFERENCES
      description: inline link
      default_weight: 0.5
    - name: CHOSEN
      description: decision picked option
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
    )
    .unwrap();
    fs::write(
        schema_dir.join("types").join("decision.yaml"),
        r#"name: decision
description: A choice with required CHOSEN edge.
when_to_use: tests
sections:
  - key: body
    heading: Body
    required: true
    search_weight: 10.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - body
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - body
health_required_fields:
  - body
staleness_threshold_days: 90
write_rules: []
required_outgoing:
  - relationships: [CHOSEN]
    cardinality: at_least_one
"#,
    )
    .unwrap();

    let mem_dir = root.join("strictmem");
    fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
    fs::write(
        mem_dir.join(".memstead").join("config.json"),
        r#"{ "schema": "strictdecision@0.1.0" }"#,
    )
    .unwrap();

    if with_violation {
        fs::write(
            mem_dir.join("violator.md"),
            r#"---
type: decision
created_date: 2026-01-01
last_modified: 2026-01-01
---
# Violator

## Body

A decision entity authored without any CHOSEN edge — exercises the
`MISSING_REQUIRED_OUTGOING` health surface.
"#,
        )
        .unwrap();
    }

    init_real_mem_repo_from_disk(root, &[(&mem_dir, "strictmem")]);
}

/// Seed a workspace pinned to a heading-round-trip-violating schema
/// (sealed posture: it loads; new installs would be refused) with one
/// entity whose content sits under the non-deriving heading and one
/// whose required section is genuinely absent — the two conditions the
/// `missing_fields` issue codes distinguish.
fn seed_violator_workspace(root: &Path) {
    let schema_dir = root.join(".memstead").join("schemas").join("debate");
    fs::create_dir_all(schema_dir.join("types")).unwrap();
    fs::write(
        schema_dir.join("schema.yaml"),
        r#"name: debate
version: 0.1.0
description: sealed-violator fixture for the CLI health projection tests.
when_to_use: Used only by memstead-cli integration tests.
types:
  - question
relationships:
  mode: strict
  definitions:
    - name: PART_OF
      description: hier
      default_weight: 3.0
    - name: _default
      description: fallback
      default_weight: 1.0
community:
  resolution: 1.0
  seed: 42
"#,
    )
    .unwrap();
    fs::write(
        schema_dir.join("types").join("question.yaml"),
        r#"name: question
description: t
when_to_use: tests
sections:
  - key: answers
    heading: Answers argued
    required: true
    search_weight: 10.0
    write_rules: []
  - key: notes
    heading: Notes
    required: false
    search_weight: 3.0
    catch_all: true
    write_rules: []
metadata_fields: []
title_weight: 100.0
text_fields:
  - answers
  - notes
hierarchy_relationship: PART_OF
no_self_loop_relationships: []
updatable_fields:
  - title
  - answers
health_required_fields:
  - answers
staleness_threshold_days: 90
write_rules: []
"#,
    )
    .unwrap();

    let mem_dir = root.join("debatemem");
    fs::create_dir_all(mem_dir.join(".memstead")).unwrap();
    fs::write(
        mem_dir.join(".memstead").join("config.json"),
        r#"{ "schema": "debate@0.1.0" }"#,
    )
    .unwrap();
    fs::write(
        mem_dir.join("mismatch.md"),
        "---\ntype: question\n---\n# Mismatch\n\n## Answers argued\n\nPresent.\n",
    )
    .unwrap();
    fs::write(
        mem_dir.join("absent.md"),
        "---\ntype: question\n---\n# Absent\n",
    )
    .unwrap();

    init_real_mem_repo_from_disk(root, &[(&mem_dir, "debatemem")]);
}

/// The CLI `missing_fields` projection carries per-issue codes beside
/// the legacy `missing` array: a genuinely absent section reports
/// `MISSING`, content under a non-deriving heading reports
/// `SECTION_HEADING_MISMATCH` — never "missing"-only. The legacy array
/// stays bare field names for both.
#[test]
fn health_missing_fields_carries_issue_codes() {
    let tmp = TempDir::new().unwrap();
    seed_violator_workspace(tmp.path());

    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "health", "--include", "missing_fields"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).expect("health --json is JSON");
    let entries = json["missing_fields"].as_array().expect("include renders");
    let entry_for = |id: &str| {
        entries
            .iter()
            .find(|e| e["id"] == format!("debatemem--{id}"))
            .unwrap_or_else(|| panic!("entry for {id}: {entries:?}"))
    };

    let mismatch = entry_for("mismatch");
    assert_eq!(mismatch["missing"], serde_json::json!(["answers"]));
    assert_eq!(mismatch["issues"][0]["code"], "SECTION_HEADING_MISMATCH");
    assert!(
        mismatch["issues"][0]["message"]
            .as_str()
            .unwrap()
            .contains("is not missing"),
        "message rides beside the code: {mismatch}"
    );

    let absent = entry_for("absent");
    assert_eq!(absent["missing"], serde_json::json!(["answers"]));
    assert_eq!(absent["issues"][0]["code"], "MISSING");
    assert!(
        absent["issues"][0]["message"]
            .as_str()
            .unwrap()
            .contains("is empty"),
        "message rides beside the code: {absent}"
    );
}

/// `memstead health --include config` renders the same projection MCP's
/// `include_config: true` serves (`mems` / `mutations` / `plugin`);
/// without the token the response carries no config block.
#[test]
fn health_include_config_renders_workspace_config_projection() {
    let tmp = TempDir::new().unwrap();
    seed_strict_health_workspace(tmp.path(), false);

    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "health", "--include", "config"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).expect("health --json is JSON");
    for key in ["mems", "mutations", "plugin"] {
        assert!(
            json.get(key).is_some(),
            "--include config must render `{key}`: {json}"
        );
    }
    let mems = json["mems"].as_array().expect("mems detail array");
    assert!(
        mems.iter().any(|m| m["name"] == "strictmem"),
        "per-mem detail names the writable mem: {mems:?}"
    );
    assert!(
        json["mutations"].get("require_notes").is_some(),
        "mutations posture rides the projection: {json}"
    );

    // Refusal complement: no config block without the token.
    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "health"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).expect("health --json is JSON");
    for key in ["mems", "mutations", "plugin"] {
        assert!(
            json.get(key).is_none(),
            "no config block without the opt-in: {json}"
        );
    }
}

#[test]
fn health_strict_exits_zero_when_no_violations() {
    let tmp = TempDir::new().unwrap();
    seed_strict_health_workspace(tmp.path(), false);

    memstead()
        .current_dir(tmp.path())
        .args([
            "health",
            "--include",
            "missing_required_outgoing",
            "--strict",
        ])
        .assert()
        .success();
}

#[test]
fn health_strict_exits_one_when_violations_present() {
    let tmp = TempDir::new().unwrap();
    seed_strict_health_workspace(tmp.path(), true);

    let assert = memstead()
        .current_dir(tmp.path())
        .args([
            "health",
            "--include",
            "missing_required_outgoing",
            "--strict",
        ])
        .assert()
        .failure()
        .code(1)
        .stderr(contains("strict mode"))
        .stderr(contains("missing_required_outgoing: 1"));
    let stdout = String::from_utf8(assert.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.contains("Missing required outgoing"),
        "violation report still rendered to stdout before non-zero exit; got:\n{stdout}"
    );
}

// ---------------------------------------------------------------------------
// Range filters (`--range-filter`) — MCP key grammar, same outcome codes
// ---------------------------------------------------------------------------

/// A range-filterable field narrows results from the CLI with the MCP
/// key grammar, and each of the four typed outcome codes is reachable
/// with the same meaning as over MCP (same engine path — the CLI only
/// splits KEY=VALUE).
#[test]
fn search_range_filter_narrows_and_surfaces_the_typed_codes() {
    let tmp = TempDir::new().unwrap();
    // Two mems: the default-schema `cli-test` (base-metadata dates are
    // range-filterable on every type) and a planning-schema `cli-plan`
    // (whose `decision.decided_on` is a type-SPECIFIC range field —
    // needed to reach RANGE_FILTER_TYPE_SCOPED).
    let dir = tmp.path().join("cli-test");
    fs::create_dir_all(&dir).unwrap();
    make_test_mem(&dir);
    let plan = tmp.path().join("cli-plan");
    fs::create_dir_all(plan.join(".memstead")).unwrap();
    fs::write(
        plan.join(".memstead").join("config.json"),
        r#"{ "schema": "planning@0.1.0" }"#,
    )
    .unwrap();
    init_real_mem_repo_from_disk(tmp.path(), &[(&dir, "cli-test"), (&plan, "cli-plan")]);

    // Supported key form narrows: alpha's created_date is 2026-01-01.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--type",
            "spec",
            "--range-filter",
            "created_date_after=2025-01-01",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert!(
        json["hits"].as_array().is_some_and(|r| !r.is_empty()),
        "in-range date filter keeps the hit: {json}"
    );

    // …and excludes when out of range.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--type",
            "spec",
            "--range-filter",
            "created_date_before=2020-01-01",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert!(
        json["hits"].as_array().is_some_and(|r| r.is_empty()),
        "out-of-range date filter drops the hit: {json}"
    );

    // Composable with --filter (equality) and the named shortcuts.
    memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--type",
            "spec",
            "--filter",
            "level=M0",
            "--range-filter",
            "created_date_after=2025-01-01",
        ])
        .assert()
        .success()
        .stdout(contains("alpha"));

    // The four typed outcome codes, same meaning as over MCP:
    // 1. malformed key → RANGE_FILTER_KEY_MALFORMED (not ignored).
    memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--type",
            "spec",
            "--range-filter",
            "bogus=1",
        ])
        .assert()
        .success()
        .stdout(contains("RANGE_FILTER_KEY_MALFORMED"));

    // 2. field declared on OTHER types in scope but not the queried
    //    one → RANGE_FILTER_TYPE_SCOPED (applied with type-narrowing):
    //    `decided_on` is range-filterable on planning's `decision`,
    //    not on `step`.
    memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--mem",
            "cli-plan",
            "--type",
            "step",
            "--range-filter",
            "decided_on_after=2020-01-01",
        ])
        .assert()
        .success()
        .stdout(contains("RANGE_FILTER_TYPE_SCOPED"));

    // 3. unknown field → UNKNOWN_RANGE_FILTER_FIELD, results UNFILTERED
    //    (not empty) — the filter is dropped with a warning.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--type",
            "spec",
            "--range-filter",
            "min_nonexistent=1",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert!(
        out.windows(b"UNKNOWN_RANGE_FILTER_FIELD".len())
            .any(|w| w == b"UNKNOWN_RANGE_FILTER_FIELD"),
        "unknown field surfaces its code: {json}"
    );
    assert!(
        json["hits"].as_array().is_some_and(|r| !r.is_empty()),
        "unknown range field leaves results unfiltered, not empty: {json}"
    );

    // 4. declared-but-not-range-filterable field → FIELD_NOT_RANGE_FILTERABLE.
    memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "--type",
            "spec",
            "--range-filter",
            "min_level=1",
        ])
        .assert()
        .success()
        .stdout(contains("FIELD_NOT_RANGE_FILTERABLE"));
}

// ---------------------------------------------------------------------------
// Workspace override (global --workspace / MEMSTEAD_WORKSPACE)
// ---------------------------------------------------------------------------

/// The global override lets the CLI operate on a named workspace from
/// any working directory: flag alone, env alone, flag over env. An
/// override without the marker refuses naming the tried path and never
/// falls back to the walk — even when the walk WOULD succeed from cwd.
#[test]
fn workspace_override_flag_env_precedence_and_refusal() {
    let ws = TempDir::new().unwrap();
    seed_cli_test_mem(ws.path());
    let elsewhere = TempDir::new().unwrap();

    // Flag alone, from an unrelated cwd.
    memstead()
        .current_dir(elsewhere.path())
        .env_remove("MEMSTEAD_WORKSPACE")
        .args([
            "--workspace",
            ws.path().to_str().unwrap(),
            "entity",
            "cli-test--alpha",
        ])
        .assert()
        .success()
        .stdout(contains("Alpha"));

    // Env alone.
    memstead()
        .current_dir(elsewhere.path())
        .env("MEMSTEAD_WORKSPACE", ws.path())
        .args(["entity", "cli-test--alpha"])
        .assert()
        .success()
        .stdout(contains("Alpha"));

    // Both: the flag wins (env points at a non-workspace; the flag's
    // valid path must be used, or this would refuse).
    memstead()
        .current_dir(elsewhere.path())
        .env("MEMSTEAD_WORKSPACE", elsewhere.path())
        .args([
            "--workspace",
            ws.path().to_str().unwrap(),
            "entity",
            "cli-test--alpha",
        ])
        .assert()
        .success()
        .stdout(contains("Alpha"));

    // Refusal: a marker-less override refuses, names the tried path,
    // and does NOT fall back to the walk — run from INSIDE the valid
    // workspace so a fallback would have succeeded.
    memstead()
        .current_dir(ws.path())
        .env_remove("MEMSTEAD_WORKSPACE")
        .args([
            "--workspace",
            elsewhere.path().to_str().unwrap(),
            "entity",
            "cli-test--alpha",
        ])
        .assert()
        .failure()
        .stderr(
            contains("WORKSPACE_NOT_INITIALISED").and(contains(elsewhere.path().to_str().unwrap())),
        );

    // Without either, the walk behaves exactly as today.
    memstead()
        .current_dir(ws.path())
        .env_remove("MEMSTEAD_WORKSPACE")
        .args(["entity", "cli-test--alpha"])
        .assert()
        .success()
        .stdout(contains("Alpha"));
}

// ---------------------------------------------------------------------------
// Directional traversal (--direction) + CLI expansion parity
// ---------------------------------------------------------------------------

/// The CLI gains the expansion pair and the direction selector: an
/// `out` expansion from alpha reaches beta (alpha --USES--> beta) and
/// reports the traversal direction beside the edge label; `in` from
/// alpha reaches nothing; an unrecognised selector refuses naming the
/// accepted values instead of silently falling back to `both`.
#[test]
fn search_direction_and_expand_via_flags() {
    let tmp = TempDir::new().unwrap();
    seed_cli_test_mem(tmp.path());

    // out: beta is reached and the direction rides beside the label.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "exercise",
            "--expand-via",
            "USES",
            "--direction",
            "out",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
    let beta = json["hits"]
        .as_array()
        .unwrap()
        .iter()
        .find(|h| h["id"] == "cli-test--beta")
        .unwrap_or_else(|| panic!("out-expansion reaches beta: {json}"));
    assert_eq!(beta["expansion"]["via_edge"], "USES");
    assert_eq!(
        beta["expansion"]["via_direction"], "out",
        "the reached entity reports its traversal direction: {beta}"
    );

    // in: alpha has no incoming USES — no expanded hit.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "search",
            "exercise",
            "--expand-via",
            "USES",
            "--direction",
            "in",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: serde_json::Value = serde_json::from_slice(&out).unwrap();
    assert!(
        !json["hits"]
            .as_array()
            .unwrap()
            .iter()
            .any(|h| h["id"] == "cli-test--beta"),
        "in-expansion must not reach a descendant: {json}"
    );

    // Unrecognised selector: refuses naming the accepted values.
    memstead()
        .current_dir(tmp.path())
        .args(["search", "alpha", "--direction", "sideways"])
        .assert()
        .failure()
        .stderr(
            contains("sideways")
                .and(contains("out"))
                .and(contains("in"))
                .and(contains("both")),
        );
}

/// Plan 08 duplicate check (CLI leg): an identifier-shaped metadata
/// value is findable by plain free-text search — the silent-zero
/// failure that produced duplicate entities is gone.
#[test]
fn search_finds_identifier_shaped_metadata_value() {
    let tmp = TempDir::new().unwrap();
    let dir = tmp.path().join("cli-test");
    fs::create_dir_all(&dir).unwrap();
    make_test_mem(&dir);
    // A file carrying the identifier in a metadata field the schema
    // never declared — tolerated on load, and now findable.
    fs::write(
        dir.join("akte.md"),
        r#"---
type: spec
aktenzeichen: 20/54/033
---
# Akte

## Identity

Die Akte selbst.

## Purpose

Nachweis für Suche in Metadaten.
"#,
    )
    .unwrap();
    init_real_mem_repo_from_disk(tmp.path(), &[(&dir, "cli-test")]);

    memstead()
        .current_dir(tmp.path())
        .args(["--json", "search", "20/54/033"])
        .assert()
        .success()
        .stdout(contains("cli-test--akte").and(contains("\"metadata\"")));
}

/// `memstead due` (first-author-path plan 08): the CLI wiring — a
/// workspace whose schema declares no due axis renders the honest
/// empty brief; a bad window refuses typed naming the accepted forms;
/// the default window is stated in `--help`; `--today` makes the
/// brief deterministic.
#[test]
fn due_brief_cli_wiring() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["due", "--today", "2026-08-10"])
        .assert()
        .success()
        .stdout(contains("# Due brief — 2026-08-10, window 90d"))
        .stdout(contains("No mounted mem's schema declares a due axis"));

    memstead()
        .current_dir(tmp.path())
        .args(["due", "--within", "90w"])
        .assert()
        .failure()
        .stderr(contains("INVALID_INPUT"))
        .stderr(contains("<N>d"));

    memstead()
        .current_dir(tmp.path())
        .args(["due", "--help"])
        .assert()
        .success()
        .stdout(contains("90d"));
}

/// `memstead export --format html` (first-author-path plan 11): the
/// CLI wiring — the format appears in help, a fixture workspace
/// exports one self-contained file, and an unknown mem refuses with
/// the same typed code the other formats use.
#[test]
fn html_export_cli_wiring() {
    let tmp = TempDir::new().unwrap();
    let _mem = seed_cli_test_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args(["export", "--help"])
        .assert()
        .success()
        .stdout(contains("html"));

    memstead()
        .current_dir(tmp.path())
        .args(["--json", "export", "--format", "html", "-o", "out.html"])
        .assert()
        .success()
        .stdout(contains("\"format\": \"html\""));
    let html = std::fs::read_to_string(tmp.path().join("out.html")).unwrap();
    assert!(html.starts_with("<!DOCTYPE html>"));
    assert!(!html.contains("<img"), "self-contained");

    memstead()
        .current_dir(tmp.path())
        .args(["export", "--format", "html", "--mem", "nope"])
        .assert()
        .failure()
        .stderr(contains("UNKNOWN_MEM"));
}