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
#![cfg(feature = "mem-repo")]
//! The rehearsal contract (agent-trust plan 07), asserted end to end
//! over the CLI write surface: a `--dry-run` call runs the IDENTICAL
//! validation the real call runs (same typed refusals, same details),
//! is observably side-effect-free (every byte under the workspace —
//! git refs, working tree, `.memstead/` — identical before and after),
//! and marks itself with the marker form (empty `commit_sha` plus the
//! prospective fields).
//!
//! Coverage: the pre-existing single-verb dry-run (create, update) is
//! asserted AGAINST the contract for the first time; the plan's new
//! surfaces (relate, batch-create, batch-update, batch-relate) are
//! asserted the same way; complements pin rehearsal against a
//! quarantined mem refusing exactly as the real call would.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};

use assert_cmd::Command;
use memstead_git_branch::test_support::init_real_mem_repo_from_disk;
use serde_json::Value;
use tempfile::TempDir;

/// Same fixture shape as `write_commands.rs`: a `cli-write/` mem with
/// a real gix-managed mem-repo so writes land on
/// `mem-repo/.git/refs/heads/cli-write`.
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();
    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")
}

fn parse_json(stdout_bytes: &[u8]) -> Value {
    let body = std::str::from_utf8(stdout_bytes).expect("stdout must be UTF-8");
    serde_json::from_str(body.trim()).unwrap_or_else(|e| {
        panic!("--json output must parse as JSON: {e}\n--- stdout ---\n{body}\n--- end ---")
    })
}

/// Byte-level fingerprint of EVERYTHING under `root`, recursively:
/// relative path → file bytes. Git refs, loose objects, logs, index,
/// the working tree, and `.memstead/` state are all in scope — a
/// rehearsal that touches any byte anywhere fails the comparison.
fn tree_digest(root: &Path) -> BTreeMap<String, Vec<u8>> {
    fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
        for entry in fs::read_dir(dir).unwrap() {
            let entry = entry.unwrap();
            let path = entry.path();
            if path.is_dir() {
                walk(root, &path, out);
            } else {
                let rel = path
                    .strip_prefix(root)
                    .unwrap()
                    .to_string_lossy()
                    .to_string();
                out.insert(rel, fs::read(&path).unwrap());
            }
        }
    }
    let mut out = BTreeMap::new();
    walk(root, root, &mut out);
    out
}

/// Assert two digests are identical, naming the first divergent path.
fn assert_trees_identical(before: &BTreeMap<String, Vec<u8>>, after: &BTreeMap<String, Vec<u8>>) {
    for (path, bytes) in before {
        match after.get(path) {
            None => panic!("rehearsal DELETED {path}"),
            Some(b) if b != bytes => panic!("rehearsal MODIFIED {path}"),
            Some(_) => {}
        }
    }
    for path in after.keys() {
        assert!(before.contains_key(path), "rehearsal CREATED {path}");
    }
}

/// Boot once so any first-boot writes (state seeding, cursor files)
/// settle before the byte-identity window opens.
fn warm_up(ws: &Path) {
    memstead()
        .current_dir(ws)
        .args(["--json", "health"])
        .assert()
        .success();
}

/// The `{code, details}` pair from a refused `--json` invocation.
/// `message` rides along for the strongest practical parity check.
fn refusal_envelope(ws: &Path, args: &[&str]) -> Value {
    let out = memstead()
        .current_dir(ws)
        .args(args)
        .assert()
        .failure()
        .get_output()
        .stdout
        .clone();
    let v = parse_json(&out);
    serde_json::json!({
        "code": v["code"],
        "message": v["message"],
        "details": v["details"],
    })
}

// ---------------------------------------------------------------------------
// Criterion 3 — the PRE-EXISTING dry-run surfaces, asserted against
// the contract: paired refusals, byte-identical workspace.
// ---------------------------------------------------------------------------

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

    // Paired refusal: an unknown section refuses with the same typed
    // envelope, rehearsed or real.
    let illegal = |dry: bool| {
        let mut args = vec!["--json", "create", "--title", "Alpha", "--type", "spec"];
        args.extend(["--section", "bogus-section=nope"]);
        if dry {
            args.push("--dry-run");
        }
        args.into_iter().map(String::from).collect::<Vec<_>>()
    };
    let rehearsed = refusal_envelope(
        tmp.path(),
        &illegal(true).iter().map(String::as_str).collect::<Vec<_>>(),
    );
    let real = refusal_envelope(
        tmp.path(),
        &illegal(false)
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    assert_eq!(
        rehearsed, real,
        "identical typed refusal, rehearsed vs real"
    );

    // Byte-identity: a LEGAL rehearsed create touches nothing.
    let before = tree_digest(tmp.path());
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "create",
            "--title",
            "Alpha",
            "--type",
            "spec",
            "--section",
            "identity=The alpha entity.",
            "--section",
            "purpose=Rehearsal contract test.",
            "--dry-run",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = parse_json(&out);
    assert_eq!(body["commit_sha"], "", "marker form: empty commit_sha");
    assert_eq!(body["id"], "cli-write--alpha", "prospective id reported");
    let after = tree_digest(tmp.path());
    assert_trees_identical(&before, &after);

    // Identical validation: the real call on the unchanged mem lands.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "create",
            "--title",
            "Alpha",
            "--type",
            "spec",
            "--section",
            "identity=The alpha entity.",
            "--section",
            "purpose=Rehearsal contract test.",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let real_body = parse_json(&out);
    assert_ne!(real_body["commit_sha"], "", "the real create commits");
    // No cross-call hash-equality assertion: the auto-stamped
    // `created_date` (second-resolution wall clock) enters `_hash`,
    // so the rehearsed and real hashes diverge whenever a second
    // ticks between the two invocations — a legitimate timestamp
    // shift, not drift. The engine-level test pins the mutation
    // clock and asserts equality there.
    assert_eq!(real_body["id"], body["id"], "same prospective identity");
}

#[test]
fn update_rehearsal_refuses_identically_and_leaves_workspace_byte_identical() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Target",
            "--type",
            "spec",
            "--section",
            "identity=Before.",
            "--section",
            "purpose=Rehearsal target.",
        ])
        .assert()
        .success();
    warm_up(tmp.path());
    let hash = {
        let out = memstead()
            .current_dir(tmp.path())
            .args(["--json", "entity", "cli-write--target"])
            .assert()
            .success()
            .get_output()
            .stdout
            .clone();
        parse_json(&out)["_hash"].as_str().unwrap().to_string()
    };

    // Paired refusal: unknown section, rehearsed vs real.
    let illegal = |dry: bool| {
        let mut v = vec![
            "--json".to_string(),
            "update".to_string(),
            "cli-write--target".to_string(),
            "--expected-hash".to_string(),
            hash.clone(),
            "--section".to_string(),
            "bogus-section=nope".to_string(),
        ];
        if dry {
            v.push("--dry-run".to_string());
        }
        v
    };
    let rehearsed = refusal_envelope(
        tmp.path(),
        &illegal(true).iter().map(String::as_str).collect::<Vec<_>>(),
    );
    let real = refusal_envelope(
        tmp.path(),
        &illegal(false)
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    assert_eq!(
        rehearsed, real,
        "identical typed refusal, rehearsed vs real"
    );

    // Byte-identity for the legal rehearsal.
    let before = tree_digest(tmp.path());
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "update",
            "cli-write--target",
            "--expected-hash",
            &hash,
            "--section",
            "identity=After.",
            "--dry-run",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = parse_json(&out);
    assert_eq!(body["commit_sha"], "", "marker form: empty commit_sha");
    assert_eq!(
        body["_hash"].as_str().unwrap(),
        hash,
        "dry-run `_hash` is the CURRENT hash (the next expected_hash)"
    );
    let prospective = body["prospective_hash"].as_str().unwrap().to_string();
    assert_ne!(prospective, hash);
    let after = tree_digest(tmp.path());
    assert_trees_identical(&before, &after);

    // The real call with the SAME hash lands — a persisted rehearsal
    // would have moved the on-disk hash and refused here. This is the
    // load-bearing identical-validation proof; hash equality with the
    // rehearsed `prospective_hash` is NOT asserted, because the
    // auto-stamped `last_modified` (second-resolution wall clock)
    // enters the hash and legitimately diverges across a second tick.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "update",
            "cli-write--target",
            "--expected-hash",
            &hash,
            "--section",
            "identity=After.",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let real_body = parse_json(&out);
    assert_ne!(real_body["commit_sha"], "");
    assert_ne!(
        real_body["_hash"].as_str().unwrap(),
        hash,
        "the real update moved the hash"
    );
}

// ---------------------------------------------------------------------------
// Criterion 1 — relate gains the same contract.
// ---------------------------------------------------------------------------

#[test]
fn relate_rehearsal_reports_would_be_stub_and_leaves_workspace_byte_identical() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    memstead()
        .current_dir(tmp.path())
        .args([
            "create",
            "--title",
            "Source",
            "--type",
            "spec",
            "--section",
            "identity=Src.",
            "--section",
            "purpose=Rehearsal source.",
        ])
        .assert()
        .success();
    warm_up(tmp.path());

    // Paired refusal: malformed target id, rehearsed vs real.
    let rehearsed = refusal_envelope(
        tmp.path(),
        &[
            "--json",
            "relate",
            "cli-write--source",
            "USES",
            "not a valid id",
            "--dry-run",
        ],
    );
    let real = refusal_envelope(
        tmp.path(),
        &[
            "--json",
            "relate",
            "cli-write--source",
            "USES",
            "not a valid id",
        ],
    );
    assert_eq!(
        rehearsed, real,
        "identical typed refusal, rehearsed vs real"
    );

    // Legal rehearsal to an ABSENT target: would-be stub reported,
    // nothing written anywhere.
    let before = tree_digest(tmp.path());
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "relate",
            "cli-write--source",
            "USES",
            "cli-write--ghost",
            "--dry-run",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = parse_json(&out);
    assert_eq!(body["commit_sha"], "", "marker form: empty commit_sha");
    let warnings = serde_json::to_string(&body["warnings"]).unwrap();
    assert!(
        warnings.contains("AUTO_STUB_CREATED"),
        "would-be stub must be reported: {warnings}"
    );
    let after = tree_digest(tmp.path());
    assert_trees_identical(&before, &after);
    // The stub was never created.
    memstead()
        .current_dir(tmp.path())
        .args(["--json", "entity", "cli-write--ghost"])
        .assert()
        .failure();

    // The real call on the unchanged mem lands.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "relate",
            "cli-write--source",
            "USES",
            "cli-write--ghost",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let real_body = parse_json(&out);
    assert_ne!(real_body["commit_sha"], "", "the real relate commits");
    // No cross-call hash equality: the relate re-stamps
    // `last_modified` into the hash, so rehearsed vs real diverge
    // across a second tick (the clock-pinned engine test asserts
    // equality deterministically).
}

// ---------------------------------------------------------------------------
// Criterion 2 — the batch family's reversed contract.
// ---------------------------------------------------------------------------

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

    // Two entries; the first references the second — intra-batch
    // resolution is part of the rehearsed validation.
    let batch_file = tmp.path().join("batch.json");
    fs::write(
        &batch_file,
        serde_json::json!({
            "creates": [
                { "title": "Alpha", "entity_type": "spec",
                  "sections": { "identity": "A.", "purpose": "P." },
                  "relations": [ { "to": "cli-write--beta", "type": "USES" } ] },
                { "title": "Beta", "entity_type": "spec",
                  "sections": { "identity": "B.", "purpose": "P." } }
            ]
        })
        .to_string(),
    )
    .unwrap();

    let before = tree_digest(tmp.path());
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "batch-create",
            "--from",
            batch_file.to_str().unwrap(),
            "--dry-run",
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = parse_json(&out);
    assert_eq!(body["applied"], true, "{body}");
    assert_eq!(body["commit_sha"], "", "marker form: empty commit_sha");
    assert_eq!(body["succeeded"], 2);
    assert_eq!(body["results"][0]["action"], "created");
    assert_eq!(body["results"][0]["id"], "cli-write--alpha");
    let after = tree_digest(tmp.path());
    assert_trees_identical(&before, &after);

    // Real run lands.
    let out = memstead()
        .current_dir(tmp.path())
        .args([
            "--json",
            "batch-create",
            "--from",
            batch_file.to_str().unwrap(),
        ])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let real_body = parse_json(&out);
    assert_eq!(real_body["applied"], true);
    assert_ne!(real_body["commit_sha"], "", "the real batch commits");
}

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

    // One illegal entry (bad title) refuses the whole batch — the
    // per-entry report must be identical, rehearsed vs real (both
    // refusals are side-effect-free, so they run back to back).
    let batch_file = tmp.path().join("batch.json");
    fs::write(
        &batch_file,
        serde_json::json!({
            "creates": [
                { "title": "Fine", "entity_type": "spec",
                  "sections": { "identity": "A.", "purpose": "P." } },
                { "title": "Bad\tTitle", "entity_type": "spec",
                  "sections": { "identity": "B.", "purpose": "P." } }
            ]
        })
        .to_string(),
    )
    .unwrap();
    let path = batch_file.to_str().unwrap();
    let rehearsed = refusal_envelope(
        tmp.path(),
        &["--json", "batch-create", "--from", path, "--dry-run"],
    );
    let real = refusal_envelope(tmp.path(), &["--json", "batch-create", "--from", path]);
    assert_eq!(rehearsed, real, "identical per-entry refusals");
    // Nothing landed either way.
    memstead()
        .current_dir(tmp.path())
        .args(["--json", "entity", "cli-write--fine"])
        .assert()
        .failure();
}

#[test]
fn batch_update_rehearsal_reports_receipt_and_leaves_workspace_byte_identical() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    for title in ["One", "Two"] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                "identity=Before.",
                "--section",
                "purpose=P.",
            ])
            .assert()
            .success();
    }
    warm_up(tmp.path());

    let batch_file = tmp.path().join("batch.json");
    fs::write(
        &batch_file,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--one", "auto_hash": true,
                  "sections": { "identity": "After one." } },
                { "id": "cli-write--two", "auto_hash": true,
                  "sections": { "identity": "After two." } }
            ]
        })
        .to_string(),
    )
    .unwrap();
    let path = batch_file.to_str().unwrap();

    let before = tree_digest(tmp.path());
    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "batch-update", "--from", path, "--dry-run"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = parse_json(&out);
    assert_eq!(body["applied"], true, "{body}");
    assert_eq!(body["commit_sha"], "", "marker form: empty commit_sha");
    assert!(
        body["results"]
            .as_array()
            .unwrap()
            .iter()
            .all(|r| r["action"] == "updated"),
        "{body}"
    );
    let after = tree_digest(tmp.path());
    assert_trees_identical(&before, &after);

    // Real run applies (auto_hash re-reads, so the pre-rehearsal
    // hashes being untouched is what lets this succeed).
    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "batch-update", "--from", path])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let real_body = parse_json(&out);
    assert_eq!(real_body["applied"], true);
    assert_ne!(real_body["commit_sha"], "");
}

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

    let batch_file = tmp.path().join("batch.json");
    fs::write(
        &batch_file,
        serde_json::json!({
            "updates": [
                { "id": "cli-write--one", "expected_hash": "wrong-hash",
                  "sections": { "identity": "Y." } },
                { "id": "cli-write--missing", "force": true,
                  "sections": { "identity": "Z." } }
            ]
        })
        .to_string(),
    )
    .unwrap();
    let path = batch_file.to_str().unwrap();
    let rehearsed = refusal_envelope(
        tmp.path(),
        &["--json", "batch-update", "--from", path, "--dry-run"],
    );
    let real = refusal_envelope(tmp.path(), &["--json", "batch-update", "--from", path]);
    assert_eq!(rehearsed, real, "identical per-entry refusals");
}

#[test]
fn batch_relate_rehearsal_reports_receipt_and_leaves_workspace_byte_identical() {
    let tmp = TempDir::new().unwrap();
    let _mem = make_mem(tmp.path());
    for title in ["One", "Two"] {
        memstead()
            .current_dir(tmp.path())
            .args([
                "create",
                "--title",
                title,
                "--type",
                "spec",
                "--section",
                "identity=X.",
                "--section",
                "purpose=P.",
            ])
            .assert()
            .success();
    }
    warm_up(tmp.path());

    let batch_file = tmp.path().join("batch.json");
    fs::write(
        &batch_file,
        serde_json::json!({
            "relates": [
                { "from": "cli-write--one", "type": "USES", "to": "cli-write--two" },
                { "from": "cli-write--one", "type": "USES", "to": "cli-write--ghost" }
            ]
        })
        .to_string(),
    )
    .unwrap();
    let path = batch_file.to_str().unwrap();

    let before = tree_digest(tmp.path());
    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "batch-relate", "--from", path, "--dry-run"])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let body = parse_json(&out);
    assert_eq!(body["applied"], true, "{body}");
    assert_eq!(body["commit_sha"], "", "marker form: empty commit_sha");
    assert!(
        body["results"]
            .as_array()
            .unwrap()
            .iter()
            .all(|r| r["action"] == "added"),
        "{body}"
    );
    let after = tree_digest(tmp.path());
    assert_trees_identical(&before, &after);
    // No stub landed.
    memstead()
        .current_dir(tmp.path())
        .args(["--json", "entity", "cli-write--ghost"])
        .assert()
        .failure();

    // Real run lands both edges.
    let out = memstead()
        .current_dir(tmp.path())
        .args(["--json", "batch-relate", "--from", path])
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let real_body = parse_json(&out);
    assert_eq!(real_body["applied"], true);
    assert_ne!(real_body["commit_sha"], "");
}

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

    let batch_file = tmp.path().join("batch.json");
    fs::write(
        &batch_file,
        serde_json::json!({
            "relates": [
                { "from": "cli-write--one", "type": "USES", "to": "not a valid id" }
            ]
        })
        .to_string(),
    )
    .unwrap();
    let path = batch_file.to_str().unwrap();
    let rehearsed = refusal_envelope(
        tmp.path(),
        &["--json", "batch-relate", "--from", path, "--dry-run"],
    );
    let real = refusal_envelope(tmp.path(), &["--json", "batch-relate", "--from", path]);
    assert_eq!(rehearsed, real, "identical refusals");
}

// ---------------------------------------------------------------------------
// Criterion 5 complement — rehearsal against a quarantined mem refuses
// exactly as the real call would.
// ---------------------------------------------------------------------------

/// A workspace whose `plenum` mem quarantines on an unresolvable
/// schema pin (same fixture shape as `repair_below_boot.rs`).
fn quarantined_workspace(tmp: &TempDir) -> PathBuf {
    let ws = tmp.path().join("ws");
    memstead()
        .args(["mem-repo", "init", ws.to_str().unwrap(), "--no-gitignore"])
        .assert()
        .success();
    fs::create_dir_all(ws.join("plenum")).unwrap();
    let mounts = ws.join(".memstead").join("state").join("mounts.json");
    fs::create_dir_all(mounts.parent().unwrap()).unwrap();
    fs::write(
        &mounts,
        r#"{
  "format": "memstead-mounts-3",
  "mounts": [
    { "mem": "plenum", "schema": "ghost@1.0.0", "storage": { "type": "folder", "path": "plenum" }, "capability": "write", "lifecycle": "eager", "cross_linkable": true }
  ]
}"#,
    )
    .unwrap();
    ws
}

#[test]
fn rehearsal_against_quarantined_mem_refuses_identically_to_real() {
    let tmp = TempDir::new().unwrap();
    let ws = quarantined_workspace(&tmp);

    let illegal = |dry: bool| {
        let mut v = vec![
            "--json".to_string(),
            "create".to_string(),
            "--title".to_string(),
            "Doc".to_string(),
            "--type".to_string(),
            "note".to_string(),
            "--mem".to_string(),
            "plenum".to_string(),
        ];
        if dry {
            v.push("--dry-run".to_string());
        }
        v
    };
    let rehearsed = refusal_envelope(
        &ws,
        &illegal(true).iter().map(String::as_str).collect::<Vec<_>>(),
    );
    let real = refusal_envelope(
        &ws,
        &illegal(false)
            .iter()
            .map(String::as_str)
            .collect::<Vec<_>>(),
    );
    assert_eq!(rehearsed, real, "identical quarantine refusal");
    assert_eq!(rehearsed["code"], "MEM_QUARANTINED", "{rehearsed}");
}