mx 0.1.231

A Swiss army knife for Claude Code and multi-agent toolkits
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
//! CLI-level integration test for the one-guess wake ritual.
//!
//! This drives the real binary (`CARGO_BIN_EXE_mx`) against an isolated,
//! embedded, tempdir-backed SurrealDB via `common::isolate`, so it never
//! touches a real store. What it pins that the unit layer cannot:
//!
//!   - a `--respond` call does not change any entry's activation count
//!     (the cascade used to be re-run, and re-counted, on every guess);
//!   - guess rows never appear in any `memory export` format;
//!   - `--wake`, `--model` and `--include-excluded` are wired end to end;
//!   - `--skip` is gone from the parser.
//!
//! Everything runs inside ONE `#[serial]` test against ONE seeded store:
//! spinning up an embedded SurrealDB applies the full schema, and doing that
//! from several test processes at once races SurrealDB's optimistic
//! concurrency. All fixture content here is invented.

use serial_test::serial;
use std::process::{Command, Stdio};
use tempfile::TempDir;

mod common;

const MX: &str = env!("CARGO_BIN_EXE_mx");
const AGENT: &str = "agent-a";

fn mx(dir: &TempDir, args: &[&str]) -> std::process::Output {
    let mut cmd = Command::new(MX);
    common::isolate(&mut cmd, dir.path());
    cmd.args(args)
        .env("MX_CURRENT_AGENT", AGENT)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    let mut child = cmd.spawn().expect("failed to spawn mx");
    drop(child.stdin.take());
    child.wait_with_output().expect("failed to wait on mx")
}

fn stdout_of(out: &std::process::Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}
fn stderr_of(out: &std::process::Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

fn json_of(out: &std::process::Output) -> serde_json::Value {
    let text = stdout_of(out);
    serde_json::from_str(text.trim())
        .unwrap_or_else(|e| panic!("expected JSON on stdout, got {text:?} ({e})"))
}

/// Add a public bloom with one authored phrase. `--no-embed` keeps the ONNX
/// embedding model (a network- and cache-dependent side effect) out of a
/// hermetic test.
fn add_bloom(dir: &TempDir, title: &str, body: &str, phrase: &str, tags: Option<&str>) {
    let mut args = vec![
        "memory",
        "add",
        "--category",
        "bloom",
        "--title",
        title,
        "--content",
        body,
        "--resonance",
        "9",
        "--resonance-type",
        "foundational",
        "--wake-phrase",
        phrase,
        "--no-embed",
        "--no-auto-anchor",
    ];
    if let Some(tags) = tags {
        args.push("--tags");
        args.push(tags);
    }
    let out = mx(dir, &args);
    assert!(
        out.status.success(),
        "add {title:?} must succeed; stderr: {}",
        stderr_of(&out)
    );
}

/// Every exported entry's `(title, activation_count)`, read out of the JSONL
/// export because that format carries the whole entry.
fn activation_counts(dir: &TempDir) -> Vec<(String, i64)> {
    let path = dir.path().join("export.jsonl");
    let path_str = path.to_str().unwrap();
    let out = mx(
        dir,
        &[
            "memory", "export", "--format", "jsonl", "--output", path_str,
        ],
    );
    assert!(
        out.status.success(),
        "jsonl export must succeed; stderr: {}",
        stderr_of(&out)
    );
    let text = std::fs::read_to_string(&path).expect("export file");
    let mut counts: Vec<(String, i64)> = text
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(|line| {
            let v: serde_json::Value = serde_json::from_str(line).expect("jsonl line");
            (
                v["title"].as_str().unwrap_or_default().to_string(),
                v["activation_count"].as_i64().unwrap_or_default(),
            )
        })
        .collect();
    counts.sort();
    counts
}

#[test]
#[serial]
fn one_guess_ritual_end_to_end() {
    let dir = TempDir::new().unwrap();

    // Two live blooms and one tagged for exclusion.
    add_bloom(&dir, "Alpha Note", "Alpha body text.", "alpha cue", None);
    add_bloom(&dir, "Beta Note", "Beta body text.", "beta cue", None);
    add_bloom(
        &dir,
        "Shelved Note",
        "Shelved body text.",
        "shelved cue",
        Some("archive"),
    );

    // ---- --skip is gone from the parser (#452) --------------------------
    let out = mx(&dir, &["memory", "wake", "--skip"]);
    assert!(!out.status.success(), "--skip must no longer parse");
    let err = stderr_of(&out);
    assert!(
        err.contains("unexpected argument") || err.contains("--skip"),
        "clap should reject --skip as unknown; stderr: {err}"
    );

    // ---- the excluded bloom is out of the plain wake set -----------------
    let out = mx(&dir, &["memory", "wake", "--min-resonance", "9"]);
    assert!(
        out.status.success(),
        "plain wake must succeed; stderr: {}",
        stderr_of(&out)
    );
    let listing = stdout_of(&out);
    assert!(listing.contains("Alpha Note"), "{listing}");
    assert!(
        !listing.contains("Shelved Note"),
        "an archive-tagged entry is out of the wake set by default: {listing}"
    );

    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--min-resonance",
            "9",
            "--include-excluded",
        ],
    );
    assert!(
        stdout_of(&out).contains("Shelved Note"),
        "--include-excluded brings it back: {}",
        stdout_of(&out)
    );

    // ---- begin the ritual ------------------------------------------------
    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--min-resonance",
            "9",
            "--begin",
            "--wake",
            "7",
            "--model",
            "test-model",
        ],
    );
    assert!(
        out.status.success(),
        "--begin must succeed; stderr: {}",
        stderr_of(&out)
    );
    let begin = json_of(&out);
    assert_eq!(begin["status"], "ritual_started");
    assert_eq!(begin["excluded"]["archive"], 1);
    assert_eq!(begin["progress"]["bloom_total"], 2);
    let prompt_title = begin["prompt"]["title"].as_str().unwrap().to_string();
    assert!(
        !prompt_title.contains("Shelved"),
        "the excluded bloom must not open the ritual: {prompt_title}"
    );

    // The begin call is the one that counts as surfacing the entries.
    let after_begin = activation_counts(&dir);
    assert!(
        after_begin.iter().any(|(_, c)| *c > 0),
        "begin should have activated the cascade: {after_begin:?}"
    );

    // ---- one guess per bloom --------------------------------------------
    let mut token = begin["session"].as_str().unwrap().to_string();
    let mut bloom_id = begin["prompt"]["id"].as_str().unwrap().to_string();

    // First bloom: a guess that misses.
    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &bloom_id,
            "--respond",
            "nothing like the cue",
            "--session",
            &token,
        ],
    );
    assert!(
        out.status.success(),
        "--respond must succeed; stderr: {}",
        stderr_of(&out)
    );
    let first = json_of(&out);
    assert_eq!(first["status"], "shown");
    assert_eq!(first["bucket"], "revealed");
    assert_eq!(first["match"]["kind"], "none");
    assert!(
        first["bloom"]["content"].as_str().unwrap().contains("body"),
        "the bloom is shown after the one guess: {first}"
    );

    // A respond must not re-count activations (#451).
    let after_respond = activation_counts(&dir);
    assert_eq!(
        after_begin, after_respond,
        "a --respond call must not change any activation count"
    );

    // Second bloom: the cue, matched.
    token = first["session"].as_str().unwrap().to_string();
    bloom_id = first["next"]["id"].as_str().unwrap().to_string();
    let cue = if first["next"]["title"] == "Alpha Note" {
        "alpha cue"
    } else {
        "beta cue"
    };
    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &bloom_id,
            "--respond",
            cue,
            "--session",
            &token,
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let second = json_of(&out);
    assert_eq!(second["bucket"], "unhinted");
    assert_eq!(second["match"]["kind"], "exact");
    let summary = &second["summary"];
    assert_eq!(summary["chunks"], 2);
    assert_eq!(summary["blooms"], 2);
    assert_eq!(summary["buckets"]["unhinted"]["authored"], 1);
    assert_eq!(summary["buckets"]["revealed"]["authored"], 1);

    assert_eq!(
        after_begin,
        activation_counts(&dir),
        "the second --respond must not change any activation count either"
    );

    // ---- guess rows stay out of every export format ----------------------
    // `memory export` reads the knowledge table only. Pin that: a guess this
    // ritual just logged must not surface in any format.
    let guess_text = "nothing like the cue";

    let jsonl = dir.path().join("check.jsonl");
    let out = mx(
        &dir,
        &[
            "memory",
            "export",
            "--format",
            "jsonl",
            "--output",
            jsonl.to_str().unwrap(),
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let jsonl_text = std::fs::read_to_string(&jsonl).unwrap();
    assert!(
        jsonl_text.contains("Alpha Note"),
        "precondition: the export must contain entries at all"
    );
    assert!(
        !jsonl_text.contains(guess_text) && !jsonl_text.contains("wake_guess"),
        "jsonl export leaked the guess log"
    );

    let csv = dir.path().join("check.csv");
    let out = mx(
        &dir,
        &[
            "memory",
            "export",
            "--format",
            "csv",
            "--output",
            csv.to_str().unwrap(),
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let csv_text = std::fs::read_to_string(&csv).unwrap();
    assert!(
        !csv_text.contains(guess_text) && !csv_text.contains("wake_guess"),
        "csv export leaked the guess log"
    );

    let md_dir = dir.path().join("md-export");
    let out = mx(
        &dir,
        &[
            "memory",
            "export",
            "--format",
            "md",
            "--output",
            md_dir.to_str().unwrap(),
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let mut md_text = String::new();
    for entry in walk_files(&md_dir) {
        md_text.push_str(&std::fs::read_to_string(entry).unwrap_or_default());
    }
    assert!(
        md_text.contains("Alpha"),
        "precondition: the md export must contain entries at all"
    );
    assert!(
        !md_text.contains(guess_text) && !md_text.contains("wake_guess"),
        "md export leaked the guess log"
    );
}

// =========================================================================
// Coverage gaps 2 and 3 from review: the DEFAULT three-layer cascade and
// `--include-excluded` driven through the real binary rather than the
// min-resonance path and the query layer.
// =========================================================================

/// The default cascade (no `--min-resonance`) is the path every real wake
/// takes, and until now only the min-resonance path was driven end to end.
#[test]
#[serial]
fn the_default_cascade_opens_a_ritual_and_honours_the_exclusion() {
    let dir = TempDir::new().unwrap();
    add_bloom(&dir, "Cascade Alpha", "Alpha body text.", "alpha cue", None);
    add_bloom(&dir, "Cascade Beta", "Beta body text.", "beta cue", None);
    add_bloom(
        &dir,
        "Cascade Shelved",
        "Shelved body text.",
        "shelved cue",
        Some("wake-exclude"),
    );

    let out = mx(
        &dir,
        &["memory", "wake", "--begin", "--model", "test-model"],
    );
    assert!(
        out.status.success(),
        "the default cascade must open a ritual; stderr: {}",
        stderr_of(&out)
    );
    let begin = json_of(&out);
    assert_eq!(begin["status"], "ritual_started");
    assert_eq!(
        begin["progress"]["bloom_total"], 2,
        "the excluded entry must not be in the default cascade: {begin}"
    );
    assert_eq!(begin["excluded"]["wake-exclude"], 1);

    // And the override brings it back through --begin, not just through the
    // listing and the query layer.
    let out = mx(&dir, &["memory", "wake", "--begin", "--include-excluded"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    assert_eq!(
        begin["progress"]["bloom_total"], 3,
        "--include-excluded must restore the entry through --begin: {begin}"
    );
    // The key is always present, so this reads as an empty object rather than
    // an absent key — one shape for the consumer either way.
    assert_eq!(
        begin["excluded"],
        serde_json::json!({}),
        "nothing is excluded when the override is on: {begin}"
    );
}

/// Two `--begin` calls over unchanged data must produce the same sequence.
#[test]
#[serial]
fn two_begins_over_the_same_data_produce_the_same_sequence() {
    let dir = TempDir::new().unwrap();
    for (title, cue) in [
        ("Order One", "one cue"),
        ("Order Two", "two cue"),
        ("Order Three", "three cue"),
    ] {
        add_bloom(&dir, title, "Body text.", cue, None);
    }

    let sequence = |dir: &TempDir| -> Vec<String> {
        let mut titles = Vec::new();
        let out = mx(dir, &["memory", "wake", "--begin"]);
        assert!(out.status.success(), "stderr: {}", stderr_of(&out));
        let mut node = json_of(&out);
        let mut token = node["session"].as_str().unwrap().to_string();
        let mut id = node["prompt"]["id"].as_str().unwrap().to_string();
        titles.push(node["prompt"]["title"].as_str().unwrap().to_string());
        loop {
            let out = mx(
                dir,
                &[
                    "memory",
                    "wake",
                    "--bloom-id",
                    &id,
                    "--respond",
                    "no match at all",
                    "--session",
                    &token,
                ],
            );
            assert!(out.status.success(), "stderr: {}", stderr_of(&out));
            node = json_of(&out);
            let Some(next) = node.get("next").filter(|n| !n.is_null()) else {
                break;
            };
            titles.push(next["title"].as_str().unwrap().to_string());
            id = next["id"].as_str().unwrap().to_string();
            token = node["session"].as_str().unwrap().to_string();
        }
        titles
    };

    let first = sequence(&dir);
    let second = sequence(&dir);
    assert_eq!(first.len(), 3, "precondition: all three blooms walked");
    assert_eq!(
        first, second,
        "the wake sequence is not stable across begins"
    );
}

/// Gap 4: `chunk_truncated` was only ever driven against the mock store. This
/// walks it through the real binary and a real store: a chunked bloom is
/// shrunk under the session's cursor mid-ritual, and the ritual must report
/// the truncation and keep going.
#[test]
#[serial]
fn a_bloom_shrunk_mid_ritual_reports_chunk_truncated_end_to_end() {
    /// `mx` with a small chunk threshold, so a modest fixture chunks.
    fn mx_chunked(dir: &TempDir, args: &[&str]) -> std::process::Output {
        let mut cmd = Command::new(MX);
        common::isolate(&mut cmd, dir.path());
        cmd.args(args)
            .env("MX_CURRENT_AGENT", AGENT)
            .env("MX_WAKE_CHUNK_BYTES", "300")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        let mut child = cmd.spawn().expect("failed to spawn mx");
        drop(child.stdin.take());
        child.wait_with_output().expect("failed to wait on mx")
    }

    let dir = TempDir::new().unwrap();
    let mut body = String::new();
    for section in 1..=6 {
        body.push_str(&format!(
            "\n## Section {section}\n\nThis is section {section} of the fixture, \
             long enough that the sections cross the chunking threshold.\n\n"
        ));
    }
    add_bloom(&dir, "Chunky Note", &body, "chunky cue", None);
    add_bloom(&dir, "Tail Note", "Tail body text.", "tail cue", None);

    let out = mx_chunked(&dir, &["memory", "wake", "--begin"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    let total = begin["progress"]["total"].as_u64().unwrap();
    assert!(
        total > 2,
        "precondition: the fixture must chunk, got {total}"
    );

    // The sequence is ordered by the cascade, not by insertion, so walk
    // forward until the chunked bloom is the one on the table, then take one
    // more chunk of it so the cursor sits past chunk 0.
    let mut id = begin["prompt"]["id"].as_str().unwrap().to_string();
    let mut title = begin["prompt"]["title"].as_str().unwrap().to_string();
    let mut token = begin["session"].as_str().unwrap().to_string();
    let mut chunky_id = String::new();

    for _ in 0..total + 1 {
        let out = mx_chunked(
            &dir,
            &[
                "memory",
                "wake",
                "--bloom-id",
                &id,
                "--respond",
                "no match",
                "--session",
                &token,
            ],
        );
        assert!(out.status.success(), "stderr: {}", stderr_of(&out));
        let node = json_of(&out);
        token = node["session"].as_str().unwrap().to_string();
        if title.starts_with("Chunky") {
            chunky_id = id.clone();
            break;
        }
        let next = node.get("next").expect("more blooms to walk");
        id = next["id"].as_str().unwrap().to_string();
        title = next["title"].as_str().unwrap().to_string();
    }
    assert!(
        !chunky_id.is_empty(),
        "precondition: the chunked bloom must be reachable"
    );

    let out = mx_chunked(
        &dir,
        &["memory", "update", &chunky_id, "--content", "tiny now."],
    );
    assert!(out.status.success(), "update; stderr: {}", stderr_of(&out));

    let out = mx_chunked(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &chunky_id,
            "--respond",
            "ignored",
            "--session",
            &token,
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let trunc = json_of(&out);
    assert_eq!(
        trunc["status"], "chunk_truncated",
        "a bloom shrunk under the cursor must report the truncation: {trunc}"
    );
    assert!(
        trunc.get("bucket").is_none() && trunc.get("guess").is_none(),
        "no guess was judged, so neither is reported: {trunc}"
    );
    assert!(
        trunc.get("next").is_some() || trunc.get("summary").is_some(),
        "a truncation must still hand back a next prompt or a summary: {trunc}"
    );
}

// =========================================================================
// Adversarial: flags and error surfaces.
// =========================================================================

/// `--wake` and `--model` are declared `requires = "begin"`, but
/// `--include-excluded` is not, so a respond call accepts a wake-set flag it
/// cannot act on and silently ignores it. The same is true of `--limit`,
/// `--min-resonance`, `--days` and `--no-activate`: the respond branch never
/// reads any of them.
#[test]
#[serial]
fn wake_set_flags_are_rejected_on_a_respond_call() {
    let dir = TempDir::new().unwrap();
    add_bloom(&dir, "Flag Alpha", "Alpha body text.", "alpha cue", None);

    let out = mx(&dir, &["memory", "wake", "--begin"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    let token = begin["session"].as_str().unwrap().to_string();
    let id = begin["prompt"]["id"].as_str().unwrap().to_string();

    for flag in [
        vec!["--include-excluded"],
        vec!["--min-resonance", "9"],
        vec!["--limit", "5"],
    ] {
        let mut args = vec![
            "memory",
            "wake",
            "--bloom-id",
            &id,
            "--respond",
            "alpha cue",
            "--session",
            &token,
        ];
        args.extend(flag.iter().copied());
        let out = mx(&dir, &args);
        assert!(
            !out.status.success(),
            "{flag:?} was accepted and silently ignored on a respond call; stdout: {}",
            stdout_of(&out)
        );
    }
}

/// With the exclusion on by default, tagging the wrong thing empties the wake
/// set. The failure a user meets then is a bare "No blooms to wake", which
/// names neither the exclusion nor the flag that turns it off — and the
/// entries are sitting right there in the graph.
#[test]
#[serial]
fn an_all_excluded_wake_set_says_why_it_is_empty() {
    let dir = TempDir::new().unwrap();
    add_bloom(
        &dir,
        "Shelved One",
        "Body text.",
        "one cue",
        Some("archive"),
    );
    add_bloom(
        &dir,
        "Shelved Two",
        "Body text.",
        "two cue",
        Some("wake-exclude"),
    );

    let out = mx(&dir, &["memory", "wake", "--begin"]);
    assert!(!out.status.success(), "an empty wake set must fail");

    // Precondition: the entries are there, and the override finds them.
    let check = mx(&dir, &["memory", "wake", "--begin", "--include-excluded"]);
    assert!(
        check.status.success(),
        "precondition: the entries exist; stderr: {}",
        stderr_of(&check)
    );

    let err = stderr_of(&out);
    assert!(
        err.contains("exclude") || err.contains("archive"),
        "the error must name the exclusion that emptied the set, got: {err}"
    );
}

/// Section 3 retires this vocabulary from tool output, help text and error
/// messages alike.
#[test]
#[serial]
fn no_retired_vocabulary_survives_in_the_wake_help_text() {
    let dir = TempDir::new().unwrap();
    let mut seen = String::new();
    for args in [
        vec!["memory", "wake", "--help"],
        vec!["memory", "add", "--help"],
        vec!["memory", "update", "--help"],
        vec!["memory", "--help"],
    ] {
        seen.push_str(&stdout_of(&mx(&dir, &args)));
    }
    for retired in [
        "remembered",
        "needed_help",
        "needed help",
        "incorrect",
        "prove",
        "verification",
    ] {
        assert!(
            !seen.to_lowercase().contains(retired),
            "help text still carries the retired word {retired:?}"
        );
    }
}

// =========================================================================
// Failure paths from the Wake 464 review, through the real binary: a guess
// starting with `-`, a refused id exits non-zero, `--wake` is echoed and
// checked against the log, and a retried token is answered from the log.
// =========================================================================

fn respond_args<'a>(bloom_id: &'a str, guess: &'a str, token: &'a str) -> Vec<&'a str> {
    vec![
        "memory",
        "wake",
        "--bloom-id",
        bloom_id,
        "--respond",
        guess,
        "--session",
        token,
    ]
}

#[test]
#[serial]
fn failure_paths_end_to_end() {
    let dir = TempDir::new().unwrap();
    add_bloom(&dir, "Alpha Note", "Alpha body text.", "alpha cue", None);
    add_bloom(&dir, "Beta Note", "Beta body text.", "beta cue", None);

    // ---- --wake must be positive; a refused begin surfaces nothing --------
    let before = activation_counts(&dir);
    let out = mx(&dir, &["memory", "wake", "--begin", "--wake", "0"]);
    assert!(!out.status.success(), "--wake 0 must be refused");
    assert!(stderr_of(&out).contains("positive"), "{}", stderr_of(&out));
    assert_eq!(
        before,
        activation_counts(&dir),
        "a refused --begin must not count as surfacing the entries"
    );

    // ---- begin echoes wake and model ---------------------------------------
    let out = mx(
        &dir,
        &["memory", "wake", "--begin", "--wake", "7", "--model", "m-1"],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    assert_eq!(begin["wake"], 7);
    assert_eq!(begin["model"], "m-1");
    let token = begin["session"].as_str().unwrap().to_string();
    let first_id = begin["prompt"]["id"].as_str().unwrap().to_string();

    // ---- a wrong id is an error: JSON on stderr, non-zero exit -------------
    let out = mx(&dir, &respond_args("kn-not-this-one", "alpha cue", &token));
    assert!(!out.status.success(), "a refused id must exit non-zero");
    assert!(stdout_of(&out).trim().is_empty(), "nothing on stdout");
    let refusal: serde_json::Value = serde_json::from_str(stderr_of(&out).trim())
        .unwrap_or_else(|e| panic!("expected JSON on stderr ({e}): {}", stderr_of(&out)));
    assert_eq!(refusal["status"], "error");
    assert_eq!(refusal["error"], "invalid_bloom_id");
    assert_eq!(refusal["expected_id"], first_id.as_str());

    // ---- a guess that starts with a hyphen parses --------------------------
    let hyphen_guess = "-ish, something about the cue";
    let out = mx(&dir, &respond_args(&first_id, hyphen_guess, &token));
    assert!(
        out.status.success(),
        "a guess starting with '-' must parse; stderr: {}",
        stderr_of(&out)
    );
    let first = json_of(&out);
    assert_eq!(first["guess"], hyphen_guess);
    assert_eq!(first["wake"], 7, "every respond echoes the wake");
    assert_eq!(first["model"], "m-1");

    // ---- the response is lost; the retry is answered from the log ----------
    let out = mx(&dir, &respond_args(&first_id, "alpha cue", &token));
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let resumed = json_of(&out);
    assert_eq!(resumed["replayed"], true);
    assert_eq!(resumed["guess"], hyphen_guess, "the first guess counts");
    assert_eq!(resumed["session"], first["session"]);
    assert_eq!(resumed["next"], first["next"]);

    // ---- finish the ritual --------------------------------------------------
    let next_token = first["session"].as_str().unwrap();
    let next_id = first["next"]["id"].as_str().unwrap();
    let out = mx(&dir, &respond_args(next_id, "beta cue", next_token));
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let last = json_of(&out);
    assert!(last["summary"].is_object());

    // A stale token two steps back names the recovery.
    let out = mx(&dir, &respond_args(&first_id, "alpha cue", &token));
    assert!(!out.status.success());
    assert!(
        stderr_of(&out).contains("token from your last successful response"),
        "{}",
        stderr_of(&out)
    );

    // ---- the same wake number again is refused, unless forced --------------
    let out = mx(&dir, &["memory", "wake", "--begin", "--wake", "7"]);
    assert!(
        !out.status.success(),
        "a logged wake number must be refused"
    );
    assert!(
        stderr_of(&out).contains("--force-wake"),
        "{}",
        stderr_of(&out)
    );

    let out = mx(
        &dir,
        &["memory", "wake", "--begin", "--wake", "7", "--force-wake"],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let forced = json_of(&out);
    assert_eq!(forced["wake"], 7);
    assert!(
        forced["warnings"][0]
            .as_str()
            .unwrap()
            .contains("--force-wake"),
        "{forced}"
    );

    // --force-wake means nothing without --wake.
    let out = mx(&dir, &["memory", "wake", "--begin", "--force-wake"]);
    assert!(!out.status.success(), "--force-wake requires --wake");
}

// =========================================================================
// The deleted-entry path, driven through the real binary and a real store.
// It was covered only against the mock, whose `get` ignores the caller's
// context and never round-trips a session.
// =========================================================================

/// Begin a ritual, walk it to the end missing every guess, and return the
/// entry ids in sequence order. The order is stable across begins, so a later
/// ritual over the same data walks the same sequence.
fn walk_order(dir: &TempDir) -> Vec<String> {
    let out = mx(dir, &["memory", "wake", "--begin"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let mut node = json_of(&out);
    let mut token = node["session"].as_str().unwrap().to_string();
    let mut id = node["prompt"]["id"].as_str().unwrap().to_string();
    let mut ids = vec![id.clone()];
    loop {
        let out = mx(
            dir,
            &[
                "memory",
                "wake",
                "--bloom-id",
                &id,
                "--respond",
                "no match at all",
                "--session",
                &token,
            ],
        );
        assert!(out.status.success(), "stderr: {}", stderr_of(&out));
        node = json_of(&out);
        let Some(next) = node.get("next").filter(|n| !n.is_null()) else {
            break;
        };
        id = next["id"].as_str().unwrap().to_string();
        ids.push(id.clone());
        token = node["session"].as_str().unwrap().to_string();
    }
    ids
}

fn seed_three(dir: &TempDir) {
    add_bloom(dir, "Vanish One", "One body text.", "one cue", None);
    add_bloom(dir, "Vanish Two", "Two body text.", "two cue", None);
    add_bloom(dir, "Vanish Three", "Three body text.", "three cue", None);
}

/// An entry deleted while it is the one on the table comes back as
/// `bloom_missing` — no body, nothing judged — and the ritual carries on.
#[test]
#[serial]
fn an_entry_deleted_under_the_cursor_reports_bloom_missing_end_to_end() {
    let dir = TempDir::new().unwrap();
    seed_three(&dir);
    let order = walk_order(&dir);
    assert_eq!(order.len(), 3, "precondition: three entries");

    let out = mx(&dir, &["memory", "wake", "--begin"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    let mut token = begin["session"].as_str().unwrap().to_string();

    // Answer the first, so the second becomes the entry on the table.
    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &order[0],
            "--respond",
            "one cue",
            "--session",
            &token,
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let node = json_of(&out);
    assert_eq!(node["next"]["id"], order[1].as_str());
    token = node["session"].as_str().unwrap().to_string();

    // Delete it out from under the open session.
    let out = mx(&dir, &["memory", "delete", &order[1]]);
    assert!(out.status.success(), "delete; stderr: {}", stderr_of(&out));

    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &order[1],
            "--respond",
            "two cue",
            "--session",
            &token,
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let gone = json_of(&out);
    assert_eq!(gone["status"], "bloom_missing", "{gone}");
    assert!(
        gone.get("bloom").is_none(),
        "there is no entry left to show: {gone}"
    );
    assert!(gone.get("bucket").is_none(), "nothing was judged: {gone}");
    assert_eq!(gone["next"]["id"], order[2].as_str());

    // The ritual finishes normally on the entry after it.
    let token = gone["session"].as_str().unwrap().to_string();
    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &order[2],
            "--respond",
            "three cue",
            "--session",
            &token,
        ],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    // The sequence is ordered by the cascade, not by insertion, so whether
    // this guess happens to be the right cue is incidental. What matters is
    // that the ritual finishes normally on the entry after the deleted one.
    let last = json_of(&out);
    assert_eq!(last["status"], "shown");
    assert!(last.get("bloom").is_some(), "{last}");
    assert!(last.get("summary").is_some(), "{last}");
    assert_eq!(
        last["summary"]["blooms"], 3,
        "the deleted entry still counts toward the sequence length: {last}"
    );
}

/// An entry deleted while the ritual is on the one BEFORE it is stepped over
/// when the next prompt is chosen, so the responder is never handed an id
/// that no longer resolves. This is the path that used to hard-fail with
/// "Next bloom not found", and it is on the ordinary `shown` branch rather
/// than the unjudged one.
#[test]
#[serial]
fn an_entry_deleted_before_its_turn_is_stepped_over_end_to_end() {
    let dir = TempDir::new().unwrap();
    seed_three(&dir);
    let order = walk_order(&dir);

    let out = mx(&dir, &["memory", "wake", "--begin"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    assert_eq!(begin["progress"]["bloom_total"], 3);
    let token = begin["session"].as_str().unwrap().to_string();

    // Delete the SECOND entry while the ritual sits on the first.
    let out = mx(&dir, &["memory", "delete", &order[1]]);
    assert!(out.status.success(), "delete; stderr: {}", stderr_of(&out));

    let out = mx(
        &dir,
        &[
            "memory",
            "wake",
            "--bloom-id",
            &order[0],
            "--respond",
            "one cue",
            "--session",
            &token,
        ],
    );
    assert!(
        out.status.success(),
        "a deleted later entry must not fail the respond; stderr: {}",
        stderr_of(&out)
    );
    let node = json_of(&out);
    assert_eq!(node["status"], "shown");
    assert_eq!(
        node["next"]["id"],
        order[2].as_str(),
        "the deleted entry must be stepped over when choosing the next \
         prompt: {node}"
    );
}

// =========================================================================
// The conflation of "deleted" with "not visible to you".
// =========================================================================

/// `mx` as a named agent other than the harness default.
fn mx_as(dir: &TempDir, agent: &str, args: &[&str]) -> std::process::Output {
    let mut cmd = Command::new(MX);
    common::isolate(&mut cmd, dir.path());
    cmd.args(args)
        .env("MX_CURRENT_AGENT", agent)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());
    let mut child = cmd.spawn().expect("failed to spawn mx");
    drop(child.stdin.take());
    child.wait_with_output().expect("failed to wait on mx")
}

/// Add a public bloom as `agent` and return its id.
fn add_bloom_as(dir: &TempDir, agent: &str, title: &str, phrase: &str) -> String {
    let out = mx_as(
        dir,
        agent,
        &[
            "memory",
            "add",
            "--category",
            "bloom",
            "--title",
            title,
            "--content",
            "Body text.",
            "--resonance",
            "9",
            "--resonance-type",
            "foundational",
            "--wake-phrase",
            phrase,
            "--no-embed",
            "--no-auto-anchor",
        ],
    );
    assert!(
        out.status.success(),
        "add {title:?} as {agent}; stderr: {}",
        stderr_of(&out)
    );
    stdout_of(&out)
        .lines()
        .find_map(|l| {
            l.strip_prefix("Added entry: ")
                .map(|s| s.trim().to_string())
        })
        .unwrap_or_else(|| panic!("no id in add output: {}", stdout_of(&out)))
}

/// `respond_ritual` builds its entry map with the CALLER's context, so an
/// entry that context cannot read is indistinguishable from one that was
/// deleted. The ownership guard's comment claims requiring the owner keeps
/// that conflation out of reach — "a caller with less visibility than the
/// session's owner cannot get here".
///
/// The owner's OWN visibility is not fixed for the life of the ritual. A
/// public entry belonging to another agent is in the owner's cascade at
/// `--begin`; if that agent makes it private mid-ritual, the owner's context
/// can no longer read it, and the ritual steps over it as vanished. The entry
/// is still in the database the whole time.
///
/// This is the gate b332e54 set for itself: no public sentence may assert a
/// property the code does not have.
#[test]
#[serial]
#[ignore = "telling a deleted entry apart from one this caller can no longer \
            read is follow-up work, not part of this change"]
fn an_entry_made_private_mid_ritual_is_not_reported_as_deleted() {
    let dir = TempDir::new().unwrap();
    add_bloom_as(&dir, AGENT, "Owned By A", "a cue");
    let b_id = add_bloom_as(&dir, "agent-b", "Owned By B", "b cue");

    // The owner begins while both entries are public and visible.
    let out = mx(&dir, &["memory", "wake", "--begin"]);
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    let begin = json_of(&out);
    assert_eq!(
        begin["progress"]["bloom_total"], 2,
        "precondition: both entries are in the wake set: {begin}"
    );

    // The other agent makes its entry private. Nothing is deleted.
    let out = mx_as(
        &dir,
        "agent-b",
        &[
            "memory",
            "update",
            &b_id,
            "--visibility",
            "private",
            "--owner",
            "agent-b",
        ],
    );
    assert!(
        out.status.success(),
        "making the entry private; stderr: {}",
        stderr_of(&out)
    );

    // Walk the open ritual to the end.
    let mut token = begin["session"].as_str().unwrap().to_string();
    let mut id = begin["prompt"]["id"].as_str().unwrap().to_string();
    let summary = loop {
        let out = mx(
            &dir,
            &[
                "memory",
                "wake",
                "--bloom-id",
                &id,
                "--respond",
                "a guess",
                "--session",
                &token,
            ],
        );
        assert!(out.status.success(), "stderr: {}", stderr_of(&out));
        let node = json_of(&out);
        token = node["session"].as_str().unwrap().to_string();
        if let Some(summary) = node.get("summary").filter(|s| !s.is_null()) {
            break summary.clone();
        }
        id = node["next"]["id"].as_str().unwrap().to_string();
    };

    // The entry was never deleted: its owner can still list it.
    let out = mx_as(
        &dir,
        "agent-b",
        &["memory", "list", "--category", "bloom", "--include-private"],
    );
    assert!(out.status.success(), "stderr: {}", stderr_of(&out));
    assert!(
        stdout_of(&out).contains("Owned By B"),
        "precondition: the entry still exists for its owner: {}",
        stdout_of(&out)
    );

    assert_eq!(
        summary["unjudged"], 0,
        "an entry that still exists was counted as vanished because the \
         caller could no longer read it: {summary}"
    );
}

/// Every file under `dir`, recursively. Returns nothing if `dir` is missing.
fn walk_files(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return out;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            out.extend(walk_files(&path));
        } else {
            out.push(path);
        }
    }
    out
}