memstead-cli 0.8.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
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
//! Integration tests for the two happy-path commands: `memstead
//! quickstart` (one-command cold start) and `memstead schema new`
//! (schema scaffold). Both run the real binary via `assert_cmd`, so
//! stdin is a pipe — every test exercises the non-TTY contract (no
//! prompts; defaults and typed refusals instead).

use std::path::Path;

use assert_cmd::Command;
use tempfile::TempDir;

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

fn stdout_of(assert: assert_cmd::assert::Assert) -> String {
    String::from_utf8(assert.get_output().stdout.clone()).expect("stdout is UTF-8")
}

fn stderr_of(assert: assert_cmd::assert::Assert) -> String {
    String::from_utf8(assert.get_output().stderr.clone()).expect("stderr is UTF-8")
}

// ---------------------------------------------------------------------
// quickstart
// ---------------------------------------------------------------------

/// The headline AC: in a fresh empty directory, one command leaves a
/// bootable workspace, a default-schema mem, a seed entity, and MCP
/// wiring; `memstead overview` immediately works. Non-interactive with
/// no `--agent` defaults to Claude Code and says so.
#[test]
fn quickstart_fresh_dir_bootstraps_workspace_seed_and_wiring() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("my-fresh-graph");

    let assert = memstead()
        .args(["quickstart", "--json"])
        .arg(&root)
        .assert()
        .success();
    let payload: serde_json::Value =
        serde_json::from_str(&stdout_of(assert)).expect("quickstart --json emits JSON");

    // Derived name + default schema pin.
    assert_eq!(payload["name"], "my-fresh-graph");
    assert_eq!(payload["schema"], "default@1.3.0");
    // Non-TTY, no --agent: Claude Code default, explicitly flagged.
    assert_eq!(payload["agents_defaulted"], true);
    assert_eq!(payload["agents"][0]["target"], "claude-code");

    // Workspace on disk: marker + config.
    assert!(root.join(".memstead").join("workspace.toml").is_file());
    assert!(root.join(".memstead").join("config.json").is_file());

    // Seed entity exists as a markdown file at the mem root.
    let seed_id = payload["seed_entity"].as_str().expect("seed entity id");
    assert_eq!(seed_id, "my-fresh-graph--welcome-to-memstead");
    assert!(root.join("welcome-to-memstead.md").is_file());

    // `.mcp.json` server entry launches the resolved memstead-mcp.
    let mcp: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.join(".mcp.json")).unwrap()).unwrap();
    let command = mcp["mcpServers"]["memstead"]["command"]
        .as_str()
        .expect("server entry has a command");
    assert!(
        command.contains("memstead-mcp"),
        "command must launch memstead-mcp, got: {command}",
    );

    // Output names the single next action.
    assert!(
        payload["next_action"].as_str().unwrap().contains("Restart"),
        "next action must name the restart, got: {}",
        payload["next_action"],
    );

    // The workspace boots: `memstead overview` works immediately.
    memstead()
        .current_dir(&root)
        .arg("overview")
        .assert()
        .success();
}

/// Tolerance AC: dotfiles and README-grade files don't block, and are
/// never ingested — the graph afterwards contains exactly the seed
/// entity.
#[test]
fn quickstart_tolerates_dotfiles_and_readme_without_ingesting() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    std::fs::write(root.join(".gitignore"), "target/\n").unwrap();
    std::fs::write(root.join("README"), "my project\n").unwrap();
    std::fs::write(root.join("LICENSE"), "MIT\n").unwrap();
    std::fs::create_dir(root.join(".git")).unwrap();

    memstead().arg("quickstart").arg(&root).assert().success();

    // Pre-existing files untouched.
    assert_eq!(
        std::fs::read_to_string(root.join("README")).unwrap(),
        "my project\n"
    );

    // Exactly one entity — the seed. Nothing was ingested.
    let assert = memstead()
        .current_dir(&root)
        .args(["list", "--json"])
        .assert()
        .success();
    let listed: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();
    let hits = listed["hits"]
        .as_array()
        .unwrap_or_else(|| panic!("list --json carries hits[]; got {listed}"));
    assert_eq!(hits.len(), 1, "seed entity only; got {hits:?}");
}

/// A `.md` file — even a README — is a genuine conflict, not a
/// tolerated one: the folder backend would adopt it as an entity, and
/// quickstart never silently ingests user content. The refusal says
/// exactly that.
#[test]
fn quickstart_refuses_markdown_readme_naming_the_ingestion_risk() {
    let tmp = TempDir::new().unwrap();
    std::fs::write(tmp.path().join("README.md"), "# my project\n").unwrap();

    let err = stderr_of(
        memstead()
            .arg("quickstart")
            .arg(tmp.path())
            .assert()
            .failure(),
    );
    assert!(err.contains("README.md"), "names the file; got: {err}");
    assert!(
        err.contains("adopt"),
        "explains the ingestion risk; got: {err}"
    );
    assert!(
        err.contains("memstead quickstart"),
        "carries the alternative; got: {err}"
    );
    assert!(!tmp.path().join(".memstead").exists(), "no half-init");
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("README.md")).unwrap(),
        "# my project\n",
        "the README is untouched",
    );
}

/// Refusal AC: genuinely conflicting content refuses with one typed
/// error naming the conflict and the exact alternative — and the
/// target is left untouched (no half-initialisation).
#[test]
fn quickstart_refuses_conflicting_content_without_half_init() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    std::fs::write(root.join("main.py"), "print()\n").unwrap();

    let assert = memstead().arg("quickstart").arg(&root).assert().failure();
    let err = stderr_of(assert);
    assert!(err.contains("TARGET_NOT_EMPTY"), "typed code; got: {err}");
    assert!(err.contains("main.py"), "names the conflict; got: {err}");
    assert!(
        err.contains("memstead quickstart"),
        "names the exact alternative; got: {err}"
    );

    // Never half-initialises.
    assert!(!root.join(".memstead").exists());
    assert!(!root.join(".mcp.json").exists());
}

/// Refusal AC: a foreign `.memstead/` (not a workspace) and an ancestor
/// workspace both refuse with typed errors carrying the next command.
#[test]
fn quickstart_refuses_foreign_memstead_dir_and_ancestor_workspace() {
    // Foreign `.memstead/` without workspace.toml.
    let tmp = TempDir::new().unwrap();
    std::fs::create_dir_all(tmp.path().join(".memstead")).unwrap();
    std::fs::write(tmp.path().join(".memstead").join("junk"), "x").unwrap();
    let err = stderr_of(
        memstead()
            .arg("quickstart")
            .arg(tmp.path())
            .assert()
            .failure(),
    );
    assert!(
        err.contains("FOREIGN_MEMSTEAD_DIR"),
        "typed code; got: {err}"
    );
    assert!(
        err.contains("memstead quickstart"),
        "carries next command; got: {err}"
    );

    // Ancestor workspace: refuse to nest.
    let outer = TempDir::new().unwrap();
    memstead()
        .arg("quickstart")
        .arg(outer.path())
        .assert()
        .success();
    let inner = outer.path().join("inner");
    std::fs::create_dir(&inner).unwrap();
    let err = stderr_of(memstead().arg("quickstart").arg(&inner).assert().failure());
    assert!(
        err.contains("WORKSPACE_ALREADY_EXISTS_ABOVE"),
        "typed code; got: {err}"
    );
    // The alternatives must be viable in a quickstart-created
    // (filesystem, no-allowlist) workspace: work there, or start a
    // separate graph — never `memstead mem init`, which refuses there.
    assert!(
        err.contains("memstead overview"),
        "viable next command; got: {err}"
    );
    assert!(
        err.contains("memstead quickstart"),
        "separate-graph alternative; got: {err}"
    );
    assert!(
        !err.contains("mem init"),
        "no dead-end suggestion; got: {err}"
    );
    assert!(
        !inner.join(".memstead").exists(),
        "no half-init in the nested target"
    );

    // Re-run on the finished workspace: refuse, point at overview.
    let err = stderr_of(
        memstead()
            .arg("quickstart")
            .arg(outer.path())
            .assert()
            .failure(),
    );
    assert!(
        err.contains("WORKSPACE_ALREADY_INITIALISED"),
        "typed code; got: {err}"
    );
    assert!(
        err.contains("memstead overview"),
        "carries next command; got: {err}"
    );
}

/// Wiring AC: an existing `.mcp.json` server entry is never
/// overwritten, and foreign entries in the same file survive the merge.
#[test]
fn quickstart_never_overwrites_existing_mcp_server_entry() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    std::fs::write(
        root.join(".mcp.json"),
        serde_json::to_vec_pretty(&serde_json::json!({
            "mcpServers": {
                "memstead": { "command": "/custom/memstead-mcp", "args": ["--flag"] },
                "other": { "command": "/bin/other" },
            }
        }))
        .unwrap(),
    )
    .unwrap();

    let assert = memstead()
        .args(["quickstart", "--json"])
        .arg(&root)
        .assert()
        .success();
    let payload: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();
    assert!(
        payload["agents"][0]["action"]
            .as_str()
            .unwrap()
            .contains("left untouched"),
        "report says the entry was left alone; got {payload}",
    );

    let mcp: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.join(".mcp.json")).unwrap()).unwrap();
    assert_eq!(
        mcp["mcpServers"]["memstead"]["command"],
        "/custom/memstead-mcp"
    );
    assert_eq!(mcp["mcpServers"]["memstead"]["args"][0], "--flag");
    assert_eq!(mcp["mcpServers"]["other"]["command"], "/bin/other");
}

/// `--agent` selects targets without any prompt: Cursor and Gemini get
/// project config files, Codex gets the `codex mcp add` command line.
#[test]
fn quickstart_agent_flags_wire_cursor_gemini_codex() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().to_path_buf();
    let assert = memstead()
        .args([
            "quickstart",
            "--json",
            "--agent",
            "cursor",
            "--agent",
            "gemini",
            "--agent",
            "codex",
        ])
        .arg(&root)
        .assert()
        .success();
    let payload: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();
    assert_eq!(payload["agents_defaulted"], false);

    let cursor: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.join(".cursor/mcp.json")).unwrap()).unwrap();
    assert!(cursor["mcpServers"]["memstead"]["command"].is_string());
    let gemini: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.join(".gemini/settings.json")).unwrap())
            .unwrap();
    assert!(gemini["mcpServers"]["memstead"]["command"].is_string());
    // Codex: command printed, nothing written.
    let codex_action = payload["agents"][2]["action"].as_str().unwrap();
    assert!(
        codex_action.contains("codex mcp add memstead --"),
        "got: {codex_action}"
    );
    assert!(!root.join(".codex").exists());
    // No Claude Code wiring — it was not selected.
    assert!(!root.join(".mcp.json").exists());
}

/// Non-TTY with an underivable directory name refuses with the exact
/// `--name` command instead of prompting; `--name` bypasses derivation.
#[test]
fn quickstart_underivable_name_refuses_with_flag_command_non_tty() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("日本語");
    std::fs::create_dir(&root).unwrap();

    let err = stderr_of(memstead().arg("quickstart").arg(&root).assert().failure());
    assert!(err.contains("--name"), "refusal names the flag; got: {err}");
    assert!(
        err.contains("memstead quickstart --name"),
        "exact command; got: {err}"
    );
    assert!(!root.join(".memstead").exists(), "no half-init");

    memstead()
        .args(["quickstart", "--name", "nihongo"])
        .arg(&root)
        .assert()
        .success();
    assert!(root.join(".memstead").join("workspace.toml").is_file());
}

// ---------------------------------------------------------------------
// schema new
// ---------------------------------------------------------------------

/// Scaffold AC: the generated package passes `schema validate`
/// unmodified, and the output prints the three follow-up commands.
#[test]
fn schema_new_scaffold_validates_unmodified() {
    let tmp = TempDir::new().unwrap();
    let out = stdout_of(
        memstead()
            .current_dir(tmp.path())
            .args(["schema", "new", "acme"])
            .assert()
            .success(),
    );
    assert!(out.contains("memstead schema validate acme"), "got: {out}");
    #[cfg(feature = "mem-repo")]
    assert!(out.contains("memstead schema install acme"), "got: {out}");
    #[cfg(not(feature = "mem-repo"))]
    assert!(
        out.contains("memstead schema install ../acme"),
        "got: {out}"
    );
    assert!(
        out.contains("acme@0.1.0"),
        "pin step names the version; got: {out}",
    );

    assert!(tmp.path().join("acme/schema.yaml").is_file());
    assert!(tmp.path().join("acme/types/note.yaml").is_file());
    memstead()
        .current_dir(tmp.path())
        .args(["schema", "validate", "acme"])
        .assert()
        .success();
}

/// Follow-up AC: the printed three-command sequence, executed verbatim
/// from a workspace, ends with the mem pinned to `acme@0.1.0` and
/// accepting a `memstead create --type note`. (`mem set-schema` lives
/// in the mem-repo-featured binary; the lean flavour covers the
/// scaffold/validate/install prefix in the test above and below.)
#[cfg(feature = "mem-repo")]
#[test]
fn schema_new_follow_up_commands_end_in_pinned_mem_accepting_create() {
    let tmp = TempDir::new().unwrap();
    // The mem name is path-derived — the directory basename is the
    // authoritative identity, so it must match `--name`.
    let ws = tmp.path().join("myws");
    memstead()
        .args(["init", "--name", "myws", "--schema", "default@1.0.0"])
        .arg(&ws)
        .assert()
        .success();

    // Step 0: scaffold inside the workspace (where the printed steps
    // resolve the real mem name).
    let out = stdout_of(
        memstead()
            .current_dir(&ws)
            .args(["schema", "new", "acme"])
            .assert()
            .success(),
    );
    assert!(
        out.contains("memstead mem set-schema myws acme@0.1.0"),
        "pin step names the workspace's mem; got: {out}",
    );
    assert!(
        !out.contains("memstead delete"),
        "no seed in an init workspace, so no delete step; got: {out}",
    );

    // Steps 1-3 verbatim.
    memstead()
        .current_dir(&ws)
        .args(["schema", "validate", "acme"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args(["schema", "install", "acme"])
        .assert()
        .success();
    let pin_out = stdout_of(
        memstead()
            .current_dir(&ws)
            .args(["mem", "set-schema", "myws", "acme@0.1.0"])
            .assert()
            .success(),
    );
    assert!(
        pin_out.contains("Switched"),
        "empty mem switches atomically; got: {pin_out}"
    );

    // The pinned mem accepts the scaffolded example type.
    memstead()
        .current_dir(&ws)
        .args([
            "create",
            "--type",
            "note",
            "--title",
            "First note",
            "--section",
            "summary=It works.",
        ])
        .assert()
        .success();
}

/// The newcomer path end-to-end: from a *quickstart* workspace (which
/// carries the seed entity), the printed follow-up includes a delete
/// step for the seed, and the printed commands executed verbatim end
/// with the mem atomically pinned (`Switched`, not a dual-pin
/// migration) and accepting the scaffolded type.
#[cfg(feature = "mem-repo")]
#[test]
fn schema_new_follow_up_from_quickstart_workspace_ends_pinned() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("my-graph");
    memstead().arg("quickstart").arg(&ws).assert().success();

    let out = stdout_of(
        memstead()
            .current_dir(&ws)
            .args(["schema", "new", "acme"])
            .assert()
            .success(),
    );
    let seed_id = "my-graph--welcome-to-memstead";
    assert!(
        out.contains(&format!("memstead delete {seed_id}")),
        "follow-up includes the seed delete step; got: {out}",
    );
    assert!(
        out.contains("memstead mem set-schema my-graph acme@0.1.0"),
        "pin step names the quickstart mem; got: {out}",
    );

    // The printed commands, verbatim.
    memstead()
        .current_dir(&ws)
        .args(["schema", "validate", "acme"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args(["schema", "install", "acme"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args(["delete", seed_id])
        .assert()
        .success();
    let pin_out = stdout_of(
        memstead()
            .current_dir(&ws)
            .args(["mem", "set-schema", "my-graph", "acme@0.1.0"])
            .assert()
            .success(),
    );
    assert!(
        pin_out.contains("Switched"),
        "seedless mem switches atomically, no migration; got: {pin_out}",
    );
    memstead()
        .current_dir(&ws)
        .args([
            "create",
            "--type",
            "note",
            "--title",
            "First note",
            "--section",
            "summary=It works.",
        ])
        .assert()
        .success();
}

/// `schema install <builtin>@<version>` resolves every RETAINED
/// built-in version: the registry registers all generations, and the
/// collect path scans the suffixed retention directories
/// (`planning-0.3`, …) instead of refusing everything but the
/// name-exact directory's version. An unregistered version still
/// refuses.
#[cfg(feature = "mem-repo")]
#[test]
fn schema_install_resolves_retained_builtin_versions() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("retained");
    memstead().arg("quickstart").arg(&ws).assert().success();

    // planning@0.3.0 lives in the retained `planning-0.3` directory
    // (name-exact `planning/` holds 0.1.0) — resolve + collect must
    // both succeed through the real command.
    memstead()
        .current_dir(&ws)
        .args(["schema", "install", "planning@0.3.0"])
        .assert()
        .success();

    let err = stderr_of(
        memstead()
            .current_dir(&ws)
            .args(["schema", "install", "planning@9.9.9"])
            .assert()
            .failure(),
    );
    assert!(
        err.contains("planning@9.9.9"),
        "unregistered version refuses, naming the pin; got: {err}"
    );
}

/// Preflight AC: a malformed agent config file refuses BEFORE anything
/// is created — the printed "re-run memstead quickstart" must still be
/// able to succeed, so no workspace may exist after the refusal.
#[test]
fn quickstart_malformed_agent_config_refuses_before_any_write() {
    // Invalid JSON.
    let tmp = TempDir::new().unwrap();
    std::fs::write(tmp.path().join(".mcp.json"), "{not json").unwrap();
    let err = stderr_of(
        memstead()
            .arg("quickstart")
            .arg(tmp.path())
            .assert()
            .failure(),
    );
    assert!(
        err.contains("not valid JSON"),
        "names the defect; got: {err}"
    );
    assert!(
        err.contains("re-run: memstead quickstart"),
        "carries the retry; got: {err}"
    );
    assert!(
        !tmp.path().join(".memstead").exists(),
        "nothing was created"
    );
    // The printed retry actually works once the file is fixed.
    std::fs::remove_file(tmp.path().join(".mcp.json")).unwrap();
    memstead()
        .arg("quickstart")
        .arg(tmp.path())
        .assert()
        .success();

    // `mcpServers` present but not an object.
    let tmp = TempDir::new().unwrap();
    std::fs::write(tmp.path().join(".mcp.json"), r#"{"mcpServers": []}"#).unwrap();
    let err = stderr_of(
        memstead()
            .arg("quickstart")
            .arg(tmp.path())
            .assert()
            .failure(),
    );
    assert!(err.contains("mcpServers"), "names the defect; got: {err}");
    assert!(
        err.contains("re-run: memstead quickstart"),
        "carries the retry; got: {err}"
    );
    assert!(
        !tmp.path().join(".memstead").exists(),
        "nothing was created"
    );
}

/// Lean-flavour follow-up end-to-end: without `mem set-schema`, the
/// printed sequence routes through a fresh mem — init pins the custom
/// schema, then `schema install ../<name>` from inside the new folder
/// makes the workspace boot. Executed as printed, it ends with a
/// working workspace accepting a `create --type note` (regression: an
/// earlier sequence pinned without installing, leaving a workspace
/// where every engine-booting command died with INTERNAL).
#[cfg(not(feature = "mem-repo"))]
#[test]
fn schema_new_lean_follow_up_ends_in_working_fresh_mem() {
    let tmp = TempDir::new().unwrap();
    let out = stdout_of(
        memstead()
            .current_dir(tmp.path())
            .args(["schema", "new", "acme"])
            .assert()
            .success(),
    );
    assert!(
        out.contains("memstead init --name acme-mem --schema acme@0.1.0"),
        "lean follow-up routes through a fresh init; got: {out}",
    );
    assert!(
        out.contains("memstead schema install ../acme"),
        "install step targets the new workspace; got: {out}",
    );
    assert!(
        !out.contains("mem set-schema"),
        "lean never prints the full-only subcommand; got: {out}",
    );

    // The printed sequence, step by step (`mkdir && cd` become the
    // test's directory handling).
    memstead()
        .current_dir(tmp.path())
        .args(["schema", "validate", "acme"])
        .assert()
        .success();
    let fresh = tmp.path().join("acme-mem");
    std::fs::create_dir(&fresh).unwrap();
    memstead()
        .current_dir(&fresh)
        .args(["init", "--name", "acme-mem", "--schema", "acme@0.1.0"])
        .assert()
        .success();
    memstead()
        .current_dir(&fresh)
        .args(["schema", "install", "../acme"])
        .assert()
        .success();

    // The workspace boots and the scaffolded type is writable.
    memstead()
        .current_dir(&fresh)
        .arg("overview")
        .assert()
        .success();
    memstead()
        .current_dir(&fresh)
        .args([
            "create",
            "--type",
            "note",
            "--title",
            "First note",
            "--section",
            "summary=It works.",
        ])
        .assert()
        .success();
}

/// Lean follow-up scaffolded from INSIDE an existing workspace: the
/// printed fresh-mem path must land outside it (workspaces don't nest,
/// and the lean binary has no `memstead mem init` to fall back on).
/// The test executes the paths exactly as printed and ends in a
/// working mem.
#[cfg(not(feature = "mem-repo"))]
#[test]
fn schema_new_lean_follow_up_from_inside_workspace_lands_outside() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("my-graph");
    memstead().arg("quickstart").arg(&ws).assert().success();

    let out = stdout_of(
        memstead()
            .current_dir(&ws)
            .args(["schema", "new", "acme"])
            .assert()
            .success(),
    );

    // Pull the two printed paths: the fresh-mem dir from the init step,
    // the package path from the install step. Both are quoted absolute
    // paths in the in-workspace variant.
    let quoted = |line_marker: &str| -> std::path::PathBuf {
        let line = out
            .lines()
            .find(|l| l.contains(line_marker))
            .unwrap_or_else(|| panic!("no step containing `{line_marker}`; got: {out}"));
        let start = line
            .find('"')
            .unwrap_or_else(|| panic!("no quoted path in: {line}"));
        let rest = &line[start + 1..];
        let end = rest
            .find('"')
            .unwrap_or_else(|| panic!("unterminated quote in: {line}"));
        std::path::PathBuf::from(&rest[..end])
    };
    let fresh = quoted("memstead init --name acme-mem");
    let pkg = quoted("memstead schema install");

    // The fresh mem lands outside the workspace.
    let ws_canon = std::fs::canonicalize(&ws).unwrap();
    assert!(
        !fresh.starts_with(&ws_canon) && !fresh.starts_with(&ws),
        "fresh-mem dir {} must not nest inside the workspace {}",
        fresh.display(),
        ws.display(),
    );

    // Execute as printed: mkdir + init in the fresh dir, install the
    // package by its printed path, and the workspace works.
    std::fs::create_dir_all(&fresh).unwrap();
    memstead()
        .current_dir(&fresh)
        .args(["init", "--name", "acme-mem", "--schema", "acme@0.1.0"])
        .assert()
        .success();
    memstead()
        .current_dir(&fresh)
        .args(["schema", "install"])
        .arg(&pkg)
        .assert()
        .success();
    memstead()
        .current_dir(&fresh)
        .arg("overview")
        .assert()
        .success();
    memstead()
        .current_dir(&fresh)
        .args([
            "create",
            "--type",
            "note",
            "--title",
            "First note",
            "--section",
            "summary=It works.",
        ])
        .assert()
        .success();
}

/// `schema install` accepts the scaffolded package on the folder
/// backend regardless of binary flavour (the lean prefix of the
/// follow-up flow).
#[test]
fn schema_new_package_installs_into_folder_workspace() {
    let tmp = TempDir::new().unwrap();
    let ws = tmp.path().join("ws");
    memstead()
        .args(["init", "--name", "myws", "--schema", "default@1.0.0"])
        .arg(&ws)
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args(["schema", "new", "acme"])
        .assert()
        .success();
    memstead()
        .current_dir(&ws)
        .args(["schema", "install", "acme"])
        .assert()
        .success();
    assert!(
        ws.join(".memstead/schemas/acme@0.1.0/schema.yaml")
            .is_file()
    );
    assert!(
        ws.join(".memstead/schemas/acme@0.1.0/types/note.yaml")
            .is_file()
    );
}

/// Refusal ACs: an existing package refuses rather than overwriting; an
/// invalid name refuses with the slug rule and a suggested correction.
/// Both messages carry the exact next command.
#[test]
fn schema_new_refusals_carry_next_commands() {
    let tmp = TempDir::new().unwrap();
    memstead()
        .current_dir(tmp.path())
        .args(["schema", "new", "acme"])
        .assert()
        .success();
    let before = std::fs::read_to_string(tmp.path().join("acme/schema.yaml")).unwrap();

    // Existing package: refuse, don't overwrite.
    let err = stderr_of(
        memstead()
            .current_dir(tmp.path())
            .args(["schema", "new", "acme"])
            .assert()
            .failure(),
    );
    assert!(
        err.contains("SCHEMA_PACKAGE_EXISTS"),
        "typed code; got: {err}"
    );
    assert!(
        err.contains("memstead schema validate acme"),
        "next command; got: {err}"
    );
    assert_eq!(
        std::fs::read_to_string(tmp.path().join("acme/schema.yaml")).unwrap(),
        before,
        "the existing package is untouched",
    );

    // Invalid (non-slug) name: rule + suggestion + exact retry command.
    let err = stderr_of(
        memstead()
            .current_dir(tmp.path())
            .args(["schema", "new", "Acme Corp!"])
            .assert()
            .failure(),
    );
    assert!(err.contains("lowercase"), "states the rule; got: {err}");
    assert!(
        err.contains("memstead schema new acme-corp"),
        "suggested correction as a runnable command; got: {err}",
    );

    // Non-empty non-package directory: refuse, name the finding.
    std::fs::create_dir(tmp.path().join("busy")).unwrap();
    std::fs::write(tmp.path().join("busy/x.txt"), "x").unwrap();
    let err = stderr_of(
        memstead()
            .current_dir(tmp.path())
            .args(["schema", "new", "busy"])
            .assert()
            .failure(),
    );
    assert!(err.contains("TARGET_NOT_EMPTY"), "typed code; got: {err}");
    assert!(err.contains("x.txt"), "names the finding; got: {err}");
}

/// Vocabulary AC helper: the artifacts the two commands generate carry
/// no retired unit noun — checked on the scaffold and the quickstart
/// report (source-level grep is part of the review gate).
#[test]
fn generated_artifacts_speak_mem_vocabulary_only() {
    // The retired unit noun stays retired even in this test's source —
    // assemble it at runtime so a source-level grep stays at zero hits.
    let retired_noun = ["va", "ult"].concat();

    let tmp = TempDir::new().unwrap();
    memstead()
        .current_dir(tmp.path())
        .args(["schema", "new", "acme"])
        .assert()
        .success();
    let scaffold = format!(
        "{}{}",
        std::fs::read_to_string(tmp.path().join("acme/schema.yaml")).unwrap(),
        std::fs::read_to_string(tmp.path().join("acme/types/note.yaml")).unwrap(),
    );
    assert!(
        !scaffold.to_lowercase().contains(&retired_noun),
        "scaffold speaks mem only"
    );

    let root = tmp.path().join("qs");
    let out = stdout_of(memstead().arg("quickstart").arg(&root).assert().success());
    assert!(
        !out.to_lowercase().contains(&retired_noun),
        "quickstart report speaks mem only"
    );
}

/// Errors-as-tutorial sweep: every refusal reachable on the two paths
/// prints an exact next command (a `memstead …` or `codex …`
/// invocation), not just a reason.
#[test]
fn every_refusal_on_these_paths_names_a_next_command() {
    let tmp = TempDir::new().unwrap();

    // quickstart refusals.
    let dirty = tmp.path().join("dirty");
    std::fs::create_dir(&dirty).unwrap();
    std::fs::write(dirty.join("code.rs"), "x").unwrap();
    let cases: Vec<String> = vec![
        // Conflicting content.
        stderr_of(memstead().arg("quickstart").arg(&dirty).assert().failure()),
        // Underivable name (non-TTY).
        {
            let weird = tmp.path().join("统一");
            std::fs::create_dir(&weird).unwrap();
            stderr_of(memstead().arg("quickstart").arg(&weird).assert().failure())
        },
        // schema new: existing package.
        {
            memstead()
                .current_dir(tmp.path())
                .args(["schema", "new", "acme"])
                .assert()
                .success();
            stderr_of(
                memstead()
                    .current_dir(tmp.path())
                    .args(["schema", "new", "acme"])
                    .assert()
                    .failure(),
            )
        },
        // schema new: invalid name.
        stderr_of(
            memstead()
                .current_dir(tmp.path())
                .args(["schema", "new", "BAD NAME"])
                .assert()
                .failure(),
        ),
    ];
    for (i, err) in cases.iter().enumerate() {
        assert!(
            err.contains("memstead "),
            "refusal #{i} must include an exact next command; got: {err}",
        );
    }
}

// ---------------------------------------------------------------------
// workspace-shape disclosure
// ---------------------------------------------------------------------

/// Every assertion the shape disclosure has to satisfy, in one place:
/// which shape, one concrete thing it cannot do, and the way to the
/// other shape. Applied to `quickstart` and `init` alike.
///
/// The "cannot" half is flavour-specific on purpose. The full build
/// names `memstead install` and the typed code it refuses with, because
/// that command exists there. The lean build has no `install`
/// subcommand at all, so it states the limit without borrowing a verb
/// the reader could not run — see the FILESYSTEM_CANNOT gate in
/// `setup.rs`. Both must still name `memstead mem-repo init`, which is
/// a pointer at the other shape, not an invitation to run it here.
fn assert_filesystem_shape_disclosure(out: &str, ctx: &str) {
    let mut needles = vec![
        "filesystem-mem",
        "cannot install mems from the registry",
        "memstead mem-repo init",
    ];
    if cfg!(feature = "mem-repo") {
        needles.push("memstead install");
        needles.push("UNSUPPORTED_WORKSPACE_SHAPE");
    } else {
        needles.push("this lean build does not carry them");
    }
    for needle in needles {
        assert!(
            out.contains(needle),
            "{ctx}: shape disclosure must name `{needle}`; got:\n{out}",
        );
    }
}

/// The fork `quickstart` decides silently is stated in the receipt the
/// newcomer is already reading — not discovered later by being refused.
#[test]
fn quickstart_receipt_discloses_the_shape_it_picked() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("disclosed-graph");
    let out = stdout_of(
        memstead()
            .args(["quickstart", "--agent", "claude-code"])
            .arg(&root)
            .assert()
            .success(),
    );
    assert_filesystem_shape_disclosure(&out, "quickstart receipt");
}

/// `memstead init` picks the same fork and discloses it the same way.
#[test]
fn init_receipt_discloses_the_shape_it_picked() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("strict-graph");
    let out = stdout_of(
        memstead()
            .args([
                "init",
                "--name",
                "strict-graph",
                "--schema",
                "default@1.3.0",
            ])
            .arg(&root)
            .assert()
            .success(),
    );
    assert_filesystem_shape_disclosure(&out, "init receipt");
}

/// Symmetry: the mem-repo verb reports its shape too, so the
/// disclosure reads as a fork rather than as a warning bolted onto one
/// branch. It names what mem-repo costs and the command for the other
/// shape.
#[cfg(feature = "mem-repo")]
#[test]
fn mem_repo_init_discloses_its_shape_symmetrically() {
    let tmp = TempDir::new().unwrap();
    let out = stdout_of(
        memstead()
            .args(["mem-repo", "init"])
            .arg(tmp.path())
            .assert()
            .success(),
    );
    for needle in ["mem-repo", "git", "memstead quickstart"] {
        assert!(
            out.contains(needle),
            "mem-repo init receipt must name `{needle}`; got:\n{out}",
        );
    }
}

/// The `--json` receipt carries the whole disclosure, not just the
/// label. The agent surface is the primary consumer here; a bare
/// `"workspace_shape": "filesystem-mem"` names the fork without
/// disclosing it, which is the failure this block exists to end.
#[test]
fn json_receipts_carry_the_whole_disclosure_not_just_the_label() {
    fn assert_disclosure(payload: &serde_json::Value, want_shape: &str, ctx: &str) {
        let d = &payload["workspace_shape_disclosure"];
        assert_eq!(d["shape"], want_shape, "{ctx}: shape; got {payload}");
        for key in ["summary", "cannot", "other_shape", "other_shape_command"] {
            let v = d[key].as_str().unwrap_or_default();
            assert!(
                !v.is_empty(),
                "{ctx}: `{key}` must be present and non-empty; got {d}",
            );
        }
        assert_ne!(
            d["other_shape"], want_shape,
            "{ctx}: the other shape must differ from this one; got {d}",
        );
    }

    let tmp = TempDir::new().unwrap();

    let assert = memstead()
        .args(["quickstart", "--json", "--agent", "claude-code"])
        .arg(tmp.path().join("json-qs"))
        .assert()
        .success();
    let payload: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();
    assert_disclosure(&payload, "filesystem-mem", "quickstart --json");

    let assert = memstead()
        .args([
            "init",
            "--json",
            "--name",
            "json-init",
            "--schema",
            "default@1.3.0",
        ])
        .arg(tmp.path().join("json-init"))
        .assert()
        .success();
    let payload: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();
    assert_disclosure(&payload, "filesystem-mem", "init --json");
}

/// Symmetric machine surface: `mem-repo init --json` carries the same
/// disclosure shape, pointing the other way.
#[cfg(feature = "mem-repo")]
#[test]
fn mem_repo_init_json_carries_the_whole_disclosure() {
    let tmp = TempDir::new().unwrap();
    let assert = memstead()
        .args(["mem-repo", "init", "--json"])
        .arg(tmp.path())
        .assert()
        .success();
    let payload: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();
    let d = &payload["workspace_shape_disclosure"];
    assert_eq!(d["shape"], "mem-repo", "got {payload}");
    assert_eq!(d["other_shape"], "filesystem-mem", "got {d}");
    assert!(
        d["other_shape_command"]
            .as_str()
            .unwrap_or_default()
            .contains("memstead quickstart"),
        "must name the other shape's command; got {d}",
    );
}

/// A verb the receipt names must either exist in the binary that
/// printed it, or be named together with the statement that this build
/// does not carry it. Anything else sends the reader to
/// `unrecognized subcommand`.
///
/// Both halves are live. The lean build's "cannot" clause no longer
/// borrows `memstead install` (it has none), while its pointer at the
/// other shape still names `memstead mem-repo init` — legitimately,
/// because the same sentence says a different build is needed first.
#[test]
fn every_verb_the_receipt_names_is_runnable_or_flagged_as_absent() {
    let tmp = TempDir::new().unwrap();
    let out = stdout_of(
        memstead()
            .args(["quickstart", "--agent", "claude-code"])
            .arg(tmp.path().join("named-cmds"))
            .assert()
            .success(),
    );

    let help = stdout_of(memstead().arg("--help").assert().success());
    let disowned =
        out.contains("this lean build has no") || out.contains("this lean build does not carry");
    for verb in ["install", "mem-repo", "quickstart", "overview", "delete"] {
        if !out.contains(&format!("memstead {verb}")) {
            continue;
        }
        // `--help` lists subcommands one per line, name first.
        let listed = help.lines().any(|l| l.trim_start().starts_with(verb));
        assert!(
            listed || disowned,
            "the receipt names `memstead {verb}`, this build's help does not list it, and the \
             receipt never says the build lacks it \u{2014} the reader would hit `unrecognized \
             subcommand`.\n--- receipt ---\n{out}\n--- help ---\n{help}",
        );
    }
}

/// Disclosure is not permission: a mem-repo-only subcommand on the
/// shape `quickstart` produces still refuses with the same typed code,
/// and the message still names the recovering command.
#[cfg(feature = "mem-repo")]
#[test]
fn mem_repo_only_subcommand_still_refuses_after_disclosure() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("refusing-graph");
    memstead()
        .args(["quickstart", "--agent", "claude-code"])
        .arg(&root)
        .assert()
        .success();

    let assert = memstead()
        .current_dir(&root)
        .args(["install", "acme/notes", "--json"])
        .assert()
        .failure();
    let body = stdout_of(assert);
    let envelope: serde_json::Value =
        serde_json::from_str(body.trim()).expect("--json refusal is JSON");
    assert_eq!(
        envelope["code"], "UNSUPPORTED_WORKSPACE_SHAPE",
        "install must still refuse by shape; got: {envelope}",
    );
    let message = envelope["message"].as_str().unwrap_or_default();
    assert!(
        message.contains("mem-repo"),
        "refusal must still name the recovering shape; got: {message}",
    );
}

/// F5: an agent session that has just run onboarding cannot restart
/// itself, so the receipt names a check that works from inside that
/// session — and still names the restart for what the restart does.
#[test]
fn quickstart_receipt_names_in_session_verification_and_the_restart() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("verifiable-graph");
    let assert = memstead()
        .args(["quickstart", "--json", "--agent", "claude-code"])
        .arg(&root)
        .assert()
        .success();
    let payload: serde_json::Value =
        serde_json::from_str(&stdout_of(assert)).expect("quickstart --json emits JSON");

    let next = payload["next_action"].as_str().unwrap_or_default();
    assert!(
        next.contains("Restart") && next.contains("registers"),
        "the restart must still be named for what it does; got: {next}",
    );

    let verify = payload["verify_now"]
        .as_array()
        .expect("receipt carries in-session verification steps");
    let rendered = verify
        .iter()
        .map(|v| v["command"].as_str().unwrap_or_default())
        .collect::<Vec<_>>()
        .join("\n");
    assert!(
        rendered.contains("--version"),
        "verification must exercise the binary the wiring points at; got:\n{rendered}",
    );
    assert!(
        rendered.contains("memstead overview"),
        "verification must name a read of the graph itself; got:\n{rendered}",
    );

    // The named check is real: the wired binary answers right now.
    let wired = payload["mcp_command"].as_str().expect("mcp_command");
    let status = std::process::Command::new(wired)
        .arg("--version")
        .status()
        .expect("the wired memstead-mcp binary must be runnable");
    assert!(status.success(), "`{wired} --version` must succeed");

    // …and the markdown receipt says the same thing.
    let root2 = tmp.path().join("verifiable-graph-md");
    let out = stdout_of(
        memstead()
            .args(["quickstart", "--agent", "claude-code"])
            .arg(&root2)
            .assert()
            .success(),
    );
    assert!(
        out.contains("--version") && out.contains("Restart"),
        "markdown receipt must carry both the in-session check and the restart; got:\n{out}",
    );
}

/// Every command the receipt prints must run verbatim, from the
/// directory the reader is standing in — across the awkward cases, on
/// both output surfaces, for every agent target.
///
/// Three earlier versions of this guard passed while printed commands
/// were unrunnable, each time because the test sampled a subset: it
/// checked `verify_now` but not the markdown lines, one agent target
/// but not Codex, a space in the path but not a leading dash, and a
/// `PATH` that always happened to contain `memstead`. So this one
/// *extracts* every backticked command from the markdown receipt and
/// every command-bearing JSON field, and runs the lot.
#[test]
fn the_receipts_printed_commands_run_verbatim_from_the_callers_cwd() {
    // Pull every `backticked` span out of the markdown receipt, keeping
    // the ones that look like commands (they name a binary we ship, or
    // start with `cd `). Extraction rather than enumeration is the
    // point: a new printed command is covered the day it is added.
    fn commands_in_markdown(out: &str) -> Vec<String> {
        out.split('`')
            .skip(1)
            .step_by(2)
            .map(str::trim)
            .filter(|s| {
                // A printed command always carries at least a
                // subcommand or flag. Requiring a space is what keeps
                // prose mentions (the backticked `memstead` in "the
                // `memstead` MCP server") and the seed entity id
                // (`<mem>--welcome-to-memstead`) out — and, unlike a
                // first-word match, it still recognises a command whose
                // program is quoted because its path holds a space.
                s.contains(' ')
                    && (s.starts_with("cd ") || s.starts_with("codex ") || s.contains("memstead"))
            })
            // `memstead quickstart` in recovery hints is a real command
            // but would create a second workspace; the disclosure block's
            // `memstead install <scope>/<name>` is a placeholder, not a
            // literal. Both are covered by their own tests.
            .filter(|s| !s.contains("quickstart") && !s.contains('<'))
            .map(str::to_string)
            .collect()
    }

    // The `PATH` a case runs under. It is applied to BOTH the
    // `quickstart` invocation and the commands its receipt prints —
    // a reader runs both in the same shell, so generating the receipt
    // under one environment and testing it under another would prove
    // nothing about what they see.
    fn path_for(has_memstead: bool) -> String {
        if has_memstead {
            format!(
                "{}:{}",
                Path::new(env!("CARGO_BIN_EXE_memstead"))
                    .parent()
                    .unwrap()
                    .display(),
                std::env::var("PATH").unwrap_or_default(),
            )
        } else {
            "/usr/bin:/bin".to_string()
        }
    }

    fn run(command: &str, cwd: &Path, path_has_memstead: bool) {
        let path = path_for(path_has_memstead);
        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(command)
            .current_dir(cwd)
            .env("PATH", path)
            .output()
            .expect("spawn sh");
        assert!(
            out.status.success(),
            "the receipt printed `{command}`, which fails when run as printed \
             (PATH carries memstead: {path_has_memstead}):\n--- stdout ---\n{}\n\
             --- stderr ---\n{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr),
        );
    }

    // Each case is (directory name, whether `memstead` is on PATH,
    // whether the binary itself sits under a path with a space).
    // The dash-prefixed name is why the `cd` carries `--`; the
    // PATH-less case is why the receipt names the binary it was
    // actually invoked as; the awkward-binary-path case is why that
    // name is quoted wherever it is printed — including in the shape
    // disclosure, which lives in a different module and was the last
    // printed command still interpolating it raw.
    let cases = [
        ("My Graph", true, false),
        ("-dashed-graph", true, false),
        ("bob's graph", true, false),
        ("offpath-graph", false, false),
        ("awkward-binary-graph", false, true),
    ];

    for (dir, on_path, awkward_binary) in cases {
        let tmp = TempDir::new().unwrap();
        let outer = tmp.path().join("outer");
        std::fs::create_dir_all(&outer).unwrap();

        // Copy the pair into a directory whose name would break any
        // unquoted interpolation, and invoke through that copy.
        let bin = if awkward_binary {
            let dir = tmp.path().join("bob's bin dir");
            std::fs::create_dir_all(&dir).unwrap();
            for name in ["memstead", "memstead-mcp"] {
                let src = Path::new(env!("CARGO_BIN_EXE_memstead"))
                    .parent()
                    .unwrap()
                    .join(name);
                if src.is_file() {
                    std::fs::copy(&src, dir.join(name)).unwrap();
                }
            }
            dir.join("memstead")
        } else {
            Path::new(env!("CARGO_BIN_EXE_memstead")).to_path_buf()
        };

        // `--` so clap does not read `-dashed-graph` as a flag.
        let assert = Command::new(&bin)
            .current_dir(&outer)
            .env("PATH", path_for(on_path))
            .args(["quickstart", "--agent", "claude-code", "--"])
            .arg(dir)
            .assert()
            .success();
        let out = stdout_of(assert);
        // The lean receipt names `mem-repo init` while stating that this
        // build does not carry it — a pointer at another build, not an
        // instruction for here. `every_verb_the_receipt_names_is_runnable_
        // or_flagged_as_absent` is what holds that case honest.
        let disowned = out.contains("this lean build has no")
            || out.contains("this lean build does not carry");
        for command in commands_in_markdown(&out) {
            if disowned && command.contains("mem-repo") {
                continue;
            }
            run(&command, &outer, on_path);
        }
    }

    // The JSON surface, including the Codex target — whose wiring IS a
    // command the reader runs, so it has to survive the same paths.
    let tmp = TempDir::new().unwrap();
    let outer = tmp.path().join("outer");
    std::fs::create_dir_all(&outer).unwrap();
    let assert = memstead()
        .current_dir(&outer)
        .args([
            "quickstart",
            "--json",
            "--agent",
            "claude-code",
            "--agent",
            "codex",
            "--",
            "My Graph",
        ])
        .assert()
        .success();
    let payload: serde_json::Value = serde_json::from_str(&stdout_of(assert)).unwrap();

    let steps = payload["verify_now"]
        .as_array()
        .expect("verify_now is an array of steps");
    assert!(!steps.is_empty(), "got {payload}");
    for s in steps {
        let c = s["command"].as_str().unwrap_or_default();
        assert!(
            !c.contains('`') && !c.starts_with("- "),
            "machine surface must carry a bare command, got: {c}",
        );
        run(c, &outer, true);
    }
    run(
        payload["seed_entity_delete_command"]
            .as_str()
            .expect("seed delete command"),
        &outer,
        true,
    );

    // `next_action`'s trailing command must be runnable too — it is the
    // most prominent line in the receipt.
    let next = payload["next_action"].as_str().unwrap_or_default();
    let (_, tail) = next
        .rsplit_once("then try: ")
        .unwrap_or_else(|| panic!("next_action names a follow-up command; got: {next}"));
    run(tail, &outer, true);

    // Codex's wiring line is a command too. It is not run (that would
    // need Codex installed), but it must parse into the argv we intend
    // — the bug this catches is an unquoted path splitting into extra
    // words, which `set --` reproduces exactly.
    let codex_action = payload["agents"]
        .as_array()
        .and_then(|a| a.iter().find(|w| w["target"] == "codex"))
        .map(|w| w["action"].as_str().unwrap_or_default().to_string())
        .expect("codex wiring action");
    let codex_cmd = codex_action.split('`').nth(1).unwrap_or_else(|| {
        panic!("codex action carries a backticked command; got: {codex_action}")
    });
    let out = std::process::Command::new("sh")
        .arg("-c")
        .arg(format!("set -- {codex_cmd}; echo $#"))
        .output()
        .expect("spawn sh");
    let argc: usize = String::from_utf8_lossy(&out.stdout).trim().parse().unwrap();
    assert_eq!(
        argc, 6,
        "`{codex_cmd}` must parse as exactly `codex mcp add memstead -- <path>` (6 words); \
         an unquoted path with a space would split into more",
    );

    // Absolute paths, so a relative argument does not leak into a field
    // an agent will resolve against its own cwd.
    for key in ["workspace_root", "config_path"] {
        let v = payload[key].as_str().unwrap_or_default();
        assert!(
            Path::new(v).is_absolute(),
            "`{key}` must be absolute for a machine consumer, got: {v}",
        );
    }
}

/// F8: `--relation` is no longer refused on a filesystem-mem
/// workspace — the MCP surface has always performed this operation on
/// this shape, and the CLI-local guard made the limit look like the
/// engine's. The edge is readable afterwards.
#[test]
fn create_relation_lands_edges_on_a_filesystem_mem_workspace() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path().join("edge-graph");
    memstead()
        .args(["quickstart", "--agent", "claude-code"])
        .arg(&root)
        .assert()
        .success();

    memstead()
        .current_dir(&root)
        .args([
            "create",
            "--title",
            "Edge Source",
            "--type",
            "concept",
            "--section",
            "definition=A concept that points at the seed entity.",
            "--section",
            "explanation=Its only job is to carry one inline relation, so the edge is \
             observable after creation.",
            "--relation",
            "CONTRASTS_WITH:edge-graph--welcome-to-memstead",
        ])
        .assert()
        .success();

    let out = stdout_of(
        memstead()
            .current_dir(&root)
            .args(["entity", "edge-graph--edge-source", "--include-relations"])
            .assert()
            .success(),
    );
    assert!(
        out.contains("welcome-to-memstead"),
        "the inline relation must be readable after creation; got:\n{out}",
    );
}

/// The `--help` text no longer claims a restriction that is gone.
#[test]
fn create_help_no_longer_claims_a_mem_repo_only_relation_limit() {
    let out = stdout_of(memstead().args(["create", "--help"]).assert().success());
    assert!(
        !out.contains("Mem-repo workspaces only"),
        "create --help must not claim a lifted restriction; got:\n{out}",
    );
}

/// The two commands exist on the declared CLI surface (the doc
/// generator and `--help` read the same clap tree).
#[test]
fn help_lists_quickstart_and_schema_new() {
    let out = stdout_of(memstead().arg("--help").assert().success());
    assert!(
        out.contains("quickstart"),
        "top-level help lists quickstart; got: {out}"
    );
    let out = stdout_of(memstead().args(["schema", "--help"]).assert().success());
    assert!(out.contains("new"), "schema help lists new; got: {out}");
}

/// Path sanity for the wiring test helper: `Path::is_file` on the
/// scaffold README-less package (regression guard for the two-file
/// package shape the docs promise).
#[test]
fn scaffold_package_is_exactly_two_files() {
    let tmp = TempDir::new().unwrap();
    memstead()
        .current_dir(tmp.path())
        .args(["schema", "new", "acme"])
        .assert()
        .success();
    let mut files: Vec<String> = walk(tmp.path().join("acme").as_path());
    files.sort();
    assert_eq!(
        files,
        vec!["schema.yaml".to_string(), "types/note.yaml".to_string()]
    );
}

fn walk(dir: &Path) -> Vec<String> {
    let mut out = Vec::new();
    for entry in std::fs::read_dir(dir).unwrap() {
        let entry = entry.unwrap();
        let name = entry.file_name().to_string_lossy().to_string();
        if entry.path().is_dir() {
            for sub in walk(&entry.path()) {
                out.push(format!("{name}/{sub}"));
            }
        } else {
            out.push(name);
        }
    }
    out
}