memstead-cli 0.2.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
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
#![cfg(feature = "mem-repo")]
//! Integration tests for `memstead` write subcommands.
//!
//! Covers the core round-trip (create → read → update strict → update
//! auto-hash → delete), plus each write command's distinct failure mode:
//!
//! * `create` — JSON-file input (`--from`) must work end-to-end.
//! * `update` — strict default refuses without `--expected-hash` (exit 5);
//!   wrong hash returns `HashMismatch` (exit 4); `--auto-hash` bypasses both.
//! * `relate` — adds an edge that's visible from `memstead relations`.
//! * `delete` — `--dry-run` leaves the entity in place.
//! * `rename` — changes the ID; the new ID becomes readable via `memstead entity`.
//! * `batch-update` — JSON file with N entries, per-entry status in stdout.
//!
//! Each test's `TempDir` gets a fresh gix-managed repo on first run — `memstead`
//! always initializes VCS since the `--vcs` flag was removed in the gix swap.

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

use assert_cmd::Command;
use memstead_git_branch::test_support::init_real_mem_repo_from_disk;
use predicates::prelude::PredicateBooleanExt;
use predicates::str::contains;
use serde_json::Value;
use tempfile::TempDir;

/// Create a `cli-write/` subdir inside `tmp` and return its absolute
/// path. The subdir basename equals the declared `name: "cli-write"`
/// per the basename-invariant.
///
/// Lays down `<tmp>/mem-repo/.git/` so the CLI's `find_workspace_root`
/// walk finds `<tmp>` and the engine's `mem-repo/.git/` fail-fast
/// accepts the workspace. Tests run the binary with
/// `current_dir(tmp)` so the binary's `.memstead/workspace.toml` walk
/// resolves the workspace from cwd.
fn make_mem(tmp: &Path) -> PathBuf {
    let mem = tmp.join("cli-write");
    fs::create_dir_all(&mem).unwrap();
    let store = mem.join(".memstead");
    fs::create_dir_all(&store).unwrap();
    fs::write(
        store.join("config.json"),
        r#"{ "schema": "default@1.0.0" }"#,
    )
    .unwrap();
    // The CLI write flow routes through the `MemWriter` seam — for
    // mem-repo-backed mems commits land on `refs/heads/cli-write` of
    // `<workspace>/mem-repo/.git/`. Seed a real mem-repo from the disk
    // shell so reads and writes share the same gitdir tip.
    init_real_mem_repo_from_disk(tmp, &[(&mem, "cli-write")]);
    mem
}

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

/// Read an entity and return its current `_hash` from the JSON output.
/// The CLI `entity --json` shape is the typed envelope
/// `{ _hash, id, sections, ... }` (not a `{ markdown: "..." }` flat
/// shape); the helper reads `_hash` directly off the structured field.
fn entity_hash(workspace_root: &Path, id: &str) -> String {
    let out = memstead()
        .current_dir(workspace_root)
        .args(["--json", "entity", id])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let json: Value = serde_json::from_slice(&out).expect("entity --json output is JSON");
    json["_hash"]
        .as_str()
        .unwrap_or_else(|| panic!("entity --json must carry `_hash`: {json}"))
        .to_string()
}

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

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Alpha",
            "--type",
            "spec",
            "--section",
            "identity=The alpha entity.",
            "--section",
            "purpose=Verifies CLI write round-trip.",
        ])
        .assert()
        .success()
        .stdout(contains("Created `cli-write--alpha`"));

    // Mem-db-backed mems persist via `mem-repo/.git/refs/heads/<mem>`
    // — the stdout marker covers the same write-landed contract.
}

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

    let payload = tmp.path().join("payload.json");
    // The `--from` payload uses `entity_type` (matching the response
    // envelopes), not the legacy `type` key.
    fs::write(
        &payload,
        r#"{
            "title": "Gamma",
            "entity_type": "spec",
            "sections": {
                "identity": "Loaded via --from.",
                "purpose": "Covers the JSON-input path."
            }
        }"#,
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["create", "--from"])
        .arg(&payload)
        .assert()
        .success()
        .stdout(contains("cli-write--gamma"));
}

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

    // Step 1 — create.
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Delta",
            "--type",
            "spec",
            "--section",
            "identity=d",
            "--section",
            "purpose=d",
        ])
        .assert()
        .success();

    // Step 2 — read hash.
    let hash1 = entity_hash(tmp.path(), "cli-write--delta");

    // Step 3 — update (strict hash).
    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "cli-write--delta",
            "--expected-hash",
            &hash1,
            "--section",
            "purpose=Updated purpose via strict hash.",
        ])
        .assert()
        .success()
        .stdout(contains("Updated `cli-write--delta`"));

    // Step 4 — update again via --auto-hash (no need to reread).
    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "cli-write--delta",
            "--auto-hash",
            "--append",
            "purpose= Appended via auto-hash.",
        ])
        .assert()
        .success()
        .stdout(contains("Updated `cli-write--delta`"));

    // Step 5 — delete.
    memstead()
        .current_dir(tmp.path())
        .args(["delete", "cli-write--delta"])
        .assert()
        .success()
        .stdout(contains("Deleted `cli-write--delta`"));

    // Disk-existence post-condition is moot for mem-repo-backed mems —
    // the subsequent `memstead entity` lookups in other tests cover the
    // same "the entity is gone" contract.
}

#[test]
fn update_requires_hash_by_default() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Eps",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "cli-write--eps",
            "--section",
            "purpose=no hash given",
        ])
        .assert()
        .code(5)
        .stderr(contains("--expected-hash"));
}

#[test]
fn update_wrong_hash_returns_exit_4() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Zeta",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "cli-write--zeta",
            "--expected-hash",
            "deadbeef",
            "--section",
            "purpose=q",
        ])
        .assert()
        .code(4)
        .stderr(contains("current:"));
}

#[test]
fn update_wrong_hash_json_mode_carries_current() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Omicron",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    memstead()
        .current_dir(tmp.path())
        .args(["--json"])
        .args([
            "update",
            "cli-write--omicron",
            "--expected-hash",
            "deadbeef",
            "--section",
            "purpose=q",
        ])
        .assert()
        .code(4)
        // Under `--json` the error envelope rides stdout.
        .stdout(contains("\"current\""));
}

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

    for (title, slug_sections) in [("Src", "identity=s"), ("Dst", "identity=d")] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                slug_sections,
                "--section",
                "purpose=x",
            ])
            .assert()
            .success();
    }

    memstead()
        .current_dir(tmp.path())
        .args(["relate", "cli-write--src", "USES", "cli-write--dst"])
        .assert()
        .success()
        .stdout(contains("Added"))
        .stdout(contains("USES"));

    memstead()
        .current_dir(tmp.path())
        .args(["relations", "cli-write--src"])
        .assert()
        .success()
        .stdout(contains("cli-write--dst"));
}

#[test]
fn delete_dry_run_does_not_remove_file() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Phi",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    memstead()
        .current_dir(tmp.path())
        .args(["delete", "cli-write--phi", "--dry-run"])
        .assert()
        .success()
        .stdout(contains("Dry-run"));

    // The dry-run contract is observable via the stdout marker plus
    // the entity remaining readable; reading via `memstead entity` would
    // succeed because the dry-run skipped the writer commit.
}

/// `delete --dry-run` states the would-be
/// verdict — `HAS_INCOMING_REFS` when a Write-mem referrer blocks the
/// delete, `would PROCEED` when nothing does — and that verdict matches
/// the real `memstead delete` outcome in both the refuse and the allow case.
#[test]
fn delete_dry_run_reports_verdict_matching_real_delete() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    for (title, sect) in [("Src", "identity=s"), ("Dst", "identity=d")] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                sect,
                "--section",
                "purpose=x",
            ])
            .assert()
            .success();
    }
    // src --USES--> dst: dst now has a blocking Write-mem referrer.
    memstead()
        .current_dir(tmp.path())
        .args(["relate", "cli-write--src", "USES", "cli-write--dst"])
        .assert()
        .success();

    // Dry-run on the referenced entity surfaces the would-be refusal —
    // an agent can decide not to attempt the delete from the preview alone.
    memstead()
        .current_dir(tmp.path())
        .args(["delete", "cli-write--dst", "--dry-run"])
        .assert()
        .success()
        .stdout(contains("would REFUSE"))
        .stdout(contains("HAS_INCOMING_REFS"));
    // The dry-run was side-effect-free: the entity is still readable.
    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-write--dst"])
        .assert()
        .success();
    // The real delete refuses, matching the verdict.
    memstead()
        .current_dir(tmp.path())
        .args(["delete", "cli-write--dst"])
        .assert()
        .failure();

    // Dry-run on the unreferenced source previews a clean removal, and
    // the real delete then succeeds — verdict matches in the allow case.
    memstead()
        .current_dir(tmp.path())
        .args(["delete", "cli-write--src", "--dry-run"])
        .assert()
        .success()
        .stdout(contains("would PROCEED"));
    memstead()
        .current_dir(tmp.path())
        .args(["delete", "cli-write--src"])
        .assert()
        .success()
        .stdout(contains("Deleted"));
}

#[test]
fn rename_changes_id() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Old Name",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    memstead()
        .current_dir(tmp.path())
        .args(["rename", "cli-write--old-name", "New Name", "--auto-hash"])
        .assert()
        .success()
        .stdout(contains("cli-write--new-name"));

    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-write--new-name"])
        .assert()
        .success()
        .stdout(contains("# New Name"));
}

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

    for title in ["Bat1", "Bat2"] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                "identity=x",
                "--section",
                "purpose=x",
            ])
            .assert()
            .success();
    }

    let h1 = entity_hash(tmp.path(), "cli-write--bat1");
    let h2 = entity_hash(tmp.path(), "cli-write--bat2");

    let payload = tmp.path().join("batch.json");
    fs::write(
        &payload,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--bat1", "expected_hash": h1,
                  "sections": { "purpose": "Batched #1" } },
                { "id": "cli-write--bat2", "expected_hash": h2,
                  "sections": { "purpose": "Batched #2" } }
            ]
        })
        .to_string(),
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["batch-update", "--from"])
        .arg(&payload)
        .assert()
        .success()
        .stdout(contains("applied — 2 item(s) in one commit"));
}

/// Atomic refusal: a 2-entry batch where the second entry targets a
/// missing id refuses the WHOLE batch — nothing is committed, and the
/// valid first entry's section change does NOT land. The output names
/// the refusal and marks the valid entry `not_applied`.
#[test]
fn batch_update_refuses_whole_batch_on_one_bad_entry() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Atomic",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=orig",
        ])
        .assert()
        .success();

    let h = entity_hash(tmp.path(), "cli-write--atomic");

    let payload = tmp.path().join("batch.json");
    fs::write(
        &payload,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--atomic", "expected_hash": h,
                  "sections": { "purpose": "should NOT land" } },
                { "id": "cli-write--ghost", "force": true,
                  "sections": { "purpose": "missing entity" } }
            ]
        })
        .to_string(),
    )
    .unwrap();

    // CLI F12: a refused batch exits non-zero (was exit 0), matching the
    // exit-code table for the dominant failure — here `ENTITY_NOT_FOUND`
    // → 3, the same code single `memstead update`/`entity` use for a missing
    // id. The human breakdown still prints on stdout.
    memstead()
        .current_dir(tmp.path())
        .args(["batch-update", "--from"])
        .arg(&payload)
        .assert()
        .failure()
        .code(3)
        .stdout(contains("REFUSED"))
        .stdout(contains("not_applied"))
        .stdout(contains("ENTITY_NOT_FOUND"));

    // The valid entry's change must not have landed — the batch was
    // refused as a unit.
    memstead()
        .current_dir(tmp.path())
        .args(["entity", "cli-write--atomic"])
        .assert()
        .success()
        .stdout(contains("orig"))
        .stdout(contains("should NOT land").not());
}

/// CLI F12 (`--json`): a refused batch exits non-zero and emits exactly
/// one JSON document — the standard `{code, message, details}` error
/// envelope. `code` is the stable `BATCH_REFUSED` token (so a script can
/// branch on `--json | jq -r .code`), and `details` carries the full
/// `BatchResult` (`applied:false`, per-entry `results`) so nothing is
/// lost. A stale hash → exit 4, matching single `update`.
#[test]
fn batch_update_json_refusal_exits_nonzero_with_envelope() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "JsonAtomic",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=orig",
        ])
        .assert()
        .success();

    // A deliberately stale hash → HASH_MISMATCH → exit 4 (mirrors single
    // `update`), and the whole batch refuses atomically.
    let payload = tmp.path().join("batch.json");
    fs::write(
        &payload,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--jsonatomic", "expected_hash": "0000000000000000",
                  "sections": { "purpose": "should NOT land" } }
            ]
        })
        .to_string(),
    )
    .unwrap();

    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "batch-update", "--from"])
        .arg(&payload)
        .assert()
        .failure()
        .code(4)
        .get_output()
        .clone();

    // Exactly one JSON document on stdout.
    let stdout = String::from_utf8(output.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| {
        panic!("refused-batch --json stdout must be one JSON document: {e}; stdout:\n{stdout}")
    });
    assert_eq!(
        parsed["code"], "BATCH_REFUSED",
        "top-level code must signal the refusal: {parsed}",
    );
    // Full result preserved under details.
    assert_eq!(
        parsed["details"]["applied"], false,
        "details carries the BatchResult: {parsed}"
    );
    assert_eq!(
        parsed["details"]["results"][0]["error"]["code"], "HASH_MISMATCH",
        "per-entry failure code stays available: {parsed}",
    );
}

/// CLI F12 complement: a successful `--json` batch is unchanged — exit 0,
/// the bare `BatchResult` on stdout with `applied:true` and the commit
/// sha (no error-envelope wrapping on the success path).
#[test]
fn batch_update_json_success_unchanged_exits_zero() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "JsonOk",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();
    let h = entity_hash(tmp.path(), "cli-write--jsonok");

    let payload = tmp.path().join("batch.json");
    fs::write(
        &payload,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--jsonok", "expected_hash": h,
                  "sections": { "purpose": "Batched" } }
            ]
        })
        .to_string(),
    )
    .unwrap();

    let output = memstead()
        .current_dir(tmp.path())
        .args(["--json", "batch-update", "--from"])
        .arg(&payload)
        .assert()
        .success()
        .get_output()
        .clone();
    let stdout = String::from_utf8(output.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(
        parsed["applied"], true,
        "success path keeps the bare BatchResult shape: {parsed}"
    );
    assert_eq!(parsed["succeeded"], 1);
    assert!(parsed["commit_sha"].as_str().is_some_and(|s| !s.is_empty()));
}

/// CLI F13: a `--include-notes` read of a batch-update commit names every
/// entity the batch touched via an additive `entity_ids` array — the
/// subject still collapses to `(N entities)` (so `subject`/`entity_id`
/// keep their backward shape), but the note alone is now self-describing.
#[test]
fn batch_update_commit_note_names_entities_via_include_notes() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());

    for title in ["Note1", "Note2"] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                "identity=x",
                "--section",
                "purpose=x",
            ])
            .assert()
            .success();
    }
    let h1 = entity_hash(tmp.path(), "cli-write--note1");
    let h2 = entity_hash(tmp.path(), "cli-write--note2");

    let payload = tmp.path().join("batch.json");
    fs::write(
        &payload,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--note1", "expected_hash": h1,
                  "sections": { "purpose": "Batched #1" } },
                { "id": "cli-write--note2", "expected_hash": h2,
                  "sections": { "purpose": "Batched #2" } }
            ]
        })
        .to_string(),
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["batch-update", "--from"])
        .arg(&payload)
        .assert()
        .success();

    // Walk every commit (empty-tree sentinel as `since`) with notes folded in.
    let output = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "changes",
            "--since",
            "4b825dc642cb6eb9a060e54bf8d69288fbee4904",
            "--include-notes",
        ])
        .assert()
        .success()
        .get_output()
        .clone();
    let stdout = String::from_utf8(output.stdout).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();

    let notes = parsed["notes"]
        .as_array()
        .expect("notes[] present with --include-notes");
    let batch_note = notes
        .iter()
        .find(|n| {
            n["subject"]
                .as_str()
                .is_some_and(|s| s.contains("batch-update"))
        })
        .unwrap_or_else(|| panic!("batch-update commit note must be present; notes:\n{parsed}"));

    // Subject keeps its count-string shape (backward compatibility).
    assert!(
        batch_note["subject"]
            .as_str()
            .unwrap()
            .contains("(2 entities)"),
        "subject keeps the count-string: {batch_note}",
    );
    // The additive entity_ids array names both touched entities.
    let ids: Vec<&str> = batch_note["entity_ids"]
        .as_array()
        .expect("batch note carries entity_ids")
        .iter()
        .map(|v| v.as_str().unwrap())
        .collect();
    assert!(
        ids.contains(&"cli-write--note1") && ids.contains(&"cli-write--note2"),
        "entity_ids must name every entity the batch touched; got: {ids:?}",
    );
}

// -----------------------------------------------------------------------------
// Filesystem-mem write-side dispatch — proves Bug 2 closure for `create`,
// `update`, `delete`, `relate`, `rename` on the filesystem flavour. Each test
// initialises a fresh filesystem-mem workspace via `memstead init`, then
// exercises the relevant subcommand via the CLI subprocess (no engine
// shortcuts, no hand-shaped .md seeds).
// -----------------------------------------------------------------------------

fn entity_hash_filesystem(workspace_root: &Path, id: &str) -> String {
    entity_hash(workspace_root, id)
}

fn init_filesystem(tmp: &TempDir, name: &str) {
    memstead()
        .current_dir(tmp.path())
        .args(["init", "--name", name, "--schema", "default@1.0.0"])
        .assert()
        .success();
}

#[test]
fn create_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Alpha",
            "--type",
            "spec",
            "--section",
            "identity=The alpha entity for filesystem CLI tests.",
            "--section",
            "purpose=Exercise the create-on-filesystem path end to end.",
        ])
        .assert()
        .success()
        .stdout(contains("Created `demo--alpha`"));

    // `memstead entity` should now read the entity back through the
    // filesystem-engine path — proves the round-trip across two
    // separate CLI invocations against the same workspace.
    memstead()
        .current_dir(tmp.path())
        .args(["entity", "demo--alpha"])
        .assert()
        .success()
        .stdout(contains("# Alpha"));
}

#[test]
fn update_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Updatable",
            "--type",
            "spec",
            "--section",
            "identity=before",
            "--section",
            "purpose=before",
        ])
        .assert()
        .success();

    let hash = entity_hash_filesystem(tmp.path(), "demo--updatable");
    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "demo--updatable",
            "--expected-hash",
            &hash,
            "--section",
            "identity=after",
        ])
        .assert()
        .success()
        .stdout(contains("Updated `demo--updatable`"));
}

#[test]
fn delete_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Doomed",
            "--type",
            "spec",
            "--section",
            "identity=now you see me",
            "--section",
            "purpose=now you don't",
        ])
        .assert()
        .success();

    memstead()
        .current_dir(tmp.path())
        .args(["delete", "demo--doomed"])
        .assert()
        .success()
        .stdout(contains("Deleted `demo--doomed`"));

    // Re-read should now fail with NOT_FOUND.
    memstead()
        .current_dir(tmp.path())
        .args(["entity", "demo--doomed"])
        .assert()
        .failure()
        .code(3);
}

#[test]
fn relate_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    for title in ["Source", "Target"] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                "identity=x",
                "--section",
                "purpose=x",
            ])
            .assert()
            .success();
    }

    memstead()
        .current_dir(tmp.path())
        .args(["relate", "demo--source", "USES", "demo--target"])
        .assert()
        .success()
        .stdout(contains("Added"));
}

#[test]
fn rename_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Old Name",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    let hash = entity_hash_filesystem(tmp.path(), "demo--old-name");
    memstead()
        .current_dir(tmp.path())
        .args([
            "rename",
            "demo--old-name",
            "New Name",
            "--expected-hash",
            &hash,
        ])
        .assert()
        .success()
        .stdout(contains("Renamed"))
        .stdout(contains("demo--new-name"));
}

/// `memstead changes --since ""` on a filesystem-mem workspace reads
/// `.memstead/changes.jsonl` and surfaces every entry whose `ts` exceeds
/// the cursor. After a single `create`, the log holds one row tagged
/// with the new entity's id — exercises the filesystem dispatch arm
/// added on top of the mem-repo path.
#[test]
fn changes_works_on_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Logged",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

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

/// `memstead export --format mem` on a filesystem-mem workspace
/// invokes the `assemble_archive` path. Without a `version` field in
/// `.memstead/config.json`, the archive shape projection refuses with a
/// `MissingVersion` error — locks in that the CLI surfaces that
/// failure cleanly instead of silently producing an unstamped `.mem`.
/// F1: `memstead init` now seeds `version = 0.1.0` so the failure path
/// only fires when the field is removed (simulating a pre-gate or
/// externally-imported config). The CLI must surface this via the
/// typed `MEM_CONFIG_INCOMPLETE` envelope.
#[test]
fn export_mem_on_filesystem_requires_version() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    // Strip `version` from the engine-default config to force the
    // residual missing-version path.
    let config_path = tmp.path().join(".memstead").join("config.json");
    let body = fs::read_to_string(&config_path).unwrap();
    let mut parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
    parsed.as_object_mut().unwrap().remove("version");
    fs::write(&config_path, serde_json::to_string_pretty(&parsed).unwrap()).unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["export", "--format", "mem", "-o", "out.mem"])
        .assert()
        .failure();
}

/// `memstead export --format mem` on a filesystem-mem workspace with
/// a complete config (`name`, `schema`, `version`) packs the workspace
/// into a portable `.mem` zip and writes it to `--output`.
#[test]
fn export_mem_on_filesystem_writes_archive() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    let config_path = tmp.path().join(".memstead").join("config.json");
    fs::write(
        &config_path,
        r#"{ "format": 1, "name": "demo", "schema": "default@1.0.0", "version": "0.1.0" }"#,
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Packed",
            "--type",
            "spec",
            "--section",
            "identity=x",
            "--section",
            "purpose=x",
        ])
        .assert()
        .success();

    let archive_path = tmp.path().join("out.mem");
    memstead()
        .current_dir(tmp.path())
        .args([
            "export",
            "--format",
            "mem",
            "-o",
            archive_path.to_str().unwrap(),
        ])
        .assert()
        .success();

    assert!(
        archive_path.is_file(),
        "expected {} to exist after export --format mem",
        archive_path.display()
    );
    assert!(
        fs::metadata(&archive_path).unwrap().len() > 0,
        "archive should be non-empty"
    );
}

/// F1: `memstead mem set-version` updates the workspace config's
/// `version` field on disk. The change persists across CLI
/// invocations — a follow-up `memstead export --format mem` uses the
/// bumped version in the default archive filename.
#[test]
fn mem_set_version_persists_through_filesystem_backend() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    // Engine-default seed is `0.1.0` per F1; bump to 0.2.0.
    memstead()
        .current_dir(tmp.path())
        .args(["mem", "set-version", "demo", "0.2.0"])
        .assert()
        .success();

    // Verify the on-disk config reflects the bump.
    let config_path = tmp.path().join(".memstead").join("config.json");
    let body = fs::read_to_string(&config_path).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
    assert_eq!(
        parsed["version"].as_str(),
        Some("0.2.0"),
        "version must be bumped on disk: {body}"
    );

    // Malformed semver refuses with INVALID_INPUT exit + envelope.
    memstead()
        .current_dir(tmp.path())
        .args(["mem", "set-version", "demo", "not-a-semver"])
        .assert()
        .failure();

    // Unknown mem refuses with UNKNOWN_MEM.
    memstead()
        .current_dir(tmp.path())
        .args(["mem", "set-version", "no-such-mem", "1.0.0"])
        .assert()
        .failure();
}

/// `memstead export --format markdown` on a filesystem-mem workspace
/// rejects with a validation error because entities are already on
/// disk in canonical form. Locks in the explicit "not yet supported"
/// path instead of a silent no-op.
#[test]
fn export_markdown_on_filesystem_rejects() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args(["export", "--format", "markdown"])
        .assert()
        .failure()
        .stderr(contains("not yet supported"));
}

/// `memstead batch-update` is mem-repo-only because every entry needs an
/// optimistic-locking `expected_hash` over a mem-repo commit graph.
/// On a filesystem-mem workspace the CLI surfaces the
/// "mem-repo-only" message so the operator knows to either move
/// flavours or replay the updates one by one through `memstead update`.
///
/// Only meaningful in the full build — under `--no-default-features`
/// the `batch-update` subcommand is gated out at the clap layer, so
/// the bail-on-filesystem behaviour can't be exercised.
#[test]
fn batch_update_on_filesystem_surfaces_mem_repo_only() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    let payload = tmp.path().join("updates.json");
    fs::write(
        &payload,
        r#"{ "updates": [{ "id": "demo--anything", "expected_hash": "deadbeef" }] }"#,
    )
    .unwrap();

    memstead()
        .current_dir(tmp.path())
        .args(["batch-update", "--from"])
        .arg(&payload)
        .assert()
        .failure()
        .stderr(contains("mem-repo-only"));
}

/// `memstead workspace dump` is mem-repo-only because the snapshot token
/// is the mem's branch HEAD oid in `mem-repo/.git/`. Filesystem
/// mems have no git history, so the command surfaces the same
/// "mem-repo-only" message that the legacy `engine()` fallback
/// produces.
///
/// Only meaningful in the full build — see the `batch_update_on_filesystem_*`
/// twin for the rationale.
#[test]
fn workspace_dump_on_filesystem_surfaces_mem_repo_only() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args(["workspace", "dump"])
        .assert()
        .failure()
        .stderr(contains("mem-repo-only"));
}

/// `memstead update --declare-relations REL:TARGET` lands the
/// declared relation in one CLI call and the response surfaces the
/// `relations_declared` echo. Locks the CLI flag plumbing for the
/// atomic-batched-declaration feature.
#[test]
fn update_declare_relations_lands_in_one_cli_call() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Source",
            "--type",
            "spec",
            "--section",
            "identity=Source entity",
            "--section",
            "purpose=Source purpose",
        ])
        .assert()
        .success();
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Target",
            "--type",
            "spec",
            "--section",
            "identity=Target entity",
            "--section",
            "purpose=Target purpose",
        ])
        .assert()
        .success();

    let hash = entity_hash_filesystem(tmp.path(), "demo--source");
    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "demo--source",
            "--expected-hash",
            &hash,
            "--declare-relations",
            "USES:demo--target",
        ])
        .assert()
        .success()
        .stdout(contains("Relations declared:"))
        .stdout(contains("USES → demo--target"));

    // The relation is queryable via `memstead relations`. USES (not
    // REFERENCES) — explicit author of REFERENCES is refused under
    // the default schema's `alias_target_rel_type` pointer.
    memstead()
        .current_dir(tmp.path())
        .args(["relations", "demo--source"])
        .assert()
        .success()
        .stdout(contains("USES"))
        .stdout(contains("demo--target"));
}

/// `memstead update --declare-relations` with a missing `:` separator
/// surfaces a validation error before the engine call.
#[test]
fn update_declare_relations_rejects_malformed_value() {
    let tmp = TempDir::new().unwrap();
    init_filesystem(&tmp, "demo");

    memstead()
        .current_dir(tmp.path())
        .args([
            "update",
            "demo--missing",
            "--expected-hash",
            "0000000000000000",
            "--declare-relations",
            "no-separator-here",
        ])
        .assert()
        .failure()
        .stderr(contains("expected REL_TYPE:TARGET_ID"));
}