reliary-agent 0.8.11

Grammar-free symbol intelligence — CLI and MCP server.
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
//! End-to-end tests for the CLI surface.
//!
//! Each test spawns the real `reliary` binary and asserts on stdout / stderr /
//! exit code, with `HOME` pointed at a temp dir so no user state is touched.
//!
//! Run: `cargo test -p reliary-agent --test e2e_cli`
mod common;

use common::{binary_path, run_cli, run_cli_stdin, Fixture};
use std::path::{Path, PathBuf};

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

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

/// Strip ANSI escapes so assertions do not depend on colour support.
fn plain(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // skip to 'm'
            for c2 in chars.by_ref() {
                if c2 == 'm' {
                    break;
                }
            }
        } else {
            out.push(c);
        }
    }
    out
}

// ── trust / index ─────────────────────────────────────────────────────────

#[test]
fn e2e_cli_trust_builds_index() {
    let fx = Fixture::new();
    fx.trust();
    assert!(fx.path().join(".reliary/index.sqlite").exists());

    // The index must be a usable SQLite database with content.
    let conn = rusqlite::Connection::open(fx.path().join(".reliary/index.sqlite")).unwrap();
    let files: i64 = conn
        .query_row("SELECT COUNT(*) FROM file_map", [], |r| r.get(0))
        .unwrap();
    assert!(files >= 2, "expected both fixture files indexed, got {}", files);
}

#[test]
fn e2e_cli_trust_is_idempotent() {
    let fx = Fixture::new();

    // Row counts across the whole index must not change on re-trust.
    // (V73 fixed a bug where every reindex duplicated phrase blobs.)
    let counts = |root: &Path| -> Vec<(String, i64)> {
        let conn = rusqlite::Connection::open(root.join(".reliary/index.sqlite")).unwrap();
        ["file_map", "phrases", "phrase_occ", "file_phrases", "file_stats"]
            .iter()
            .map(|t| {
                let n: i64 = conn
                    .query_row(&format!("SELECT COUNT(*) FROM {}", t), [], |r| r.get(0))
                    .unwrap_or(-1);
                (t.to_string(), n)
            })
            .collect()
    };

    fx.trust();
    let first = counts(fx.path());
    assert!(
        first.iter().all(|(_, n)| *n > 0),
        "first trust must populate every table: {:?}",
        first
    );

    fx.trust();
    let second = counts(fx.path());
    assert_eq!(
        first, second,
        "re-trust must not duplicate rows — index size drifted: {:?} -> {:?}",
        first, second
    );
}

// ── search ────────────────────────────────────────────────────────────────

#[test]
fn e2e_cli_search_finds_symbol_file() {
    let fx = Fixture::new();
    fx.trust();

    let out = run_cli(&["search", "alpha"], fx.path(), &[]);
    assert!(out.status.success(), "search failed: {}", stderr_of(&out));
    let text = plain(&stdout_of(&out));
    assert!(
        text.contains("lib.rs"),
        "search for alpha must name src/lib.rs: {}",
        text
    );
}

#[test]
fn e2e_cli_search_without_index_explains_itself() {
    // No trust: the CLI must offer to build the index (or explain), never
    // panic and never silently return nothing. Feed "n" so it exits without
    // indexing, then assert the prompt named the problem.
    let dir = tempfile::tempdir().unwrap();
    let out = run_cli_stdin(&["search", "anything"], dir.path(), &[], "n\n");
    let combined = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(
        !combined.contains("panicked"),
        "search without index must not panic: {}",
        combined
    );
    let lower = combined.to_ascii_lowercase();
    assert!(
        lower.contains("no project index")
            || lower.contains("no index")
            || lower.contains("index")
            || lower.contains("trust"),
        "search without index must explain how to fix it: {}",
        combined
    );
    // Declining the prompt must not create an index.
    assert!(
        !dir.path().join(".reliary/index.sqlite").exists(),
        "declining the build prompt must leave the directory unindexed"
    );
}

// ── verify ────────────────────────────────────────────────────────────────

#[test]
fn e2e_cli_verify_true_claim() {
    let fx = Fixture::new();
    fx.trust();

    let out = run_cli(&["verify", "alpha at src/lib.rs:3"], fx.path(), &[]);
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(
        text.contains("VERIFIED"),
        "a true claim must verify: {}",
        text
    );
}

#[test]
fn e2e_cli_verify_false_claim_exits_nonzero() {
    let fx = Fixture::new();
    fx.trust();

    let out = run_cli(&["verify", "zeta_missing at src/lib.rs:99000"], fx.path(), &[]);
    assert!(
        !out.status.success(),
        "a falsified claim must exit non-zero: {}",
        plain(&stdout_of(&out))
    );
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(
        text.contains("FALSE") || text.contains("false"),
        "falsified claim should be reported: {}",
        text
    );
}

#[test]
fn e2e_cli_verify_json_is_valid_and_stable() {
    let fx = Fixture::new();
    fx.trust();

    let out = run_cli(&["verify", "--json", "alpha at src/lib.rs:3"], fx.path(), &[]);
    let text = stdout_of(&out);
    let parsed: serde_json::Value =
        serde_json::from_str(text.trim()).unwrap_or_else(|e| panic!("verify --json invalid: {} ({})", e, text));
    assert!(parsed["verified"].is_number(), "json needs a verified count: {}", parsed);
    assert!(parsed["falsified"].is_number(), "json needs a falsified count: {}", parsed);
    assert!(parsed["claims"].is_array(), "json needs a claims array: {}", parsed);

    // Deterministic: same input, same index, identical bytes.
    let out2 = run_cli(&["verify", "--json", "alpha at src/lib.rs:3"], fx.path(), &[]);
    assert_eq!(
        text, stdout_of(&out2),
        "verify --json must be deterministic"
    );
}

// ── status / doctor ───────────────────────────────────────────────────────

#[test]
fn e2e_cli_status_reports_index() {
    let fx = Fixture::new();
    fx.trust();

    let out = run_cli(&["status"], fx.path(), &[]);
    assert!(out.status.success(), "status failed: {}", stderr_of(&out));
    let text = plain(&stdout_of(&out));
    assert!(
        text.contains("Index"),
        "status must report the index: {}",
        text
    );
    assert!(
        text.contains('2'),
        "status should report the 2 indexed files: {}",
        text
    );
}

#[test]
fn e2e_cli_doctor_runs_clean() {
    let fx = Fixture::new();
    fx.trust();

    let out = run_cli(&["doctor"], fx.path(), &[]);
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(!text.contains("panicked"), "doctor must not panic: {}", text);
    assert!(
        text.contains("binary") || text.contains("index"),
        "doctor should report checks: {}",
        text
    );
}

#[test]
fn e2e_cli_doctor_without_index_still_runs() {
    let dir = tempfile::tempdir().unwrap();
    let out = run_cli(&["doctor"], dir.path(), &[]);
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(!text.contains("panicked"), "doctor must not panic: {}", text);
}

// ── wrap (bash compression) ───────────────────────────────────────────────

#[test]
fn e2e_cli_wrap_compresses_repetitive_output() {
    let dir = tempfile::tempdir().unwrap();
    let script = "for i in $(seq 1 40); do echo \"Compiling crate_$i v0.1.0\"; done; echo 'error: boom'";
    let out = run_cli(&["wrap", "bash", "-c", script], dir.path(), &[]);
    let text = plain(&stdout_of(&out));

    assert!(
        text.contains("error: boom"),
        "compression must preserve errors: {}",
        text
    );
    // 40 repetitive lines must have collapsed.
    let compiling_lines = text.lines().filter(|l| l.contains("Compiling")).count();
    assert!(
        compiling_lines < 40,
        "expected the 40 Compiling lines to collapse, got {}: {}",
        compiling_lines,
        text
    );
}

#[test]
fn e2e_cli_wrap_passes_through_source_reads() {
    // `cat <source file>` must NOT be compressed — read tools need the real bytes.
    let fx = Fixture::new();
    let src = fx.path().join("src/lib.rs");
    let out = run_cli(
        &["wrap", "cat", src.to_str().unwrap()],
        fx.path(),
        &[],
    );
    let text = stdout_of(&out);
    assert!(
        text.contains("pub fn alpha"),
        "cat of a source file must pass through unchanged: {}",
        text
    );
    assert!(
        text.contains("pub fn beta") || text.contains("beta()"),
        "full file body must be present: {}",
        text
    );
}

#[test]
fn e2e_cli_wrap_is_deterministic() {
    let dir = tempfile::tempdir().unwrap();
    let script = "for i in $(seq 1 25); do echo \"step $i\"; done";
    let a = run_cli(&["wrap", "bash", "-c", script], dir.path(), &[]);
    let b = run_cli(&["wrap", "bash", "-c", script], dir.path(), &[]);
    assert_eq!(
        stdout_of(&a),
        stdout_of(&b),
        "wrap output must be byte-identical across runs (KV-cache safety)"
    );
}

// ── init / uninstall (fake HOME) ──────────────────────────────────────────

/// Build a fake HOME with Claude Code and OpenCode configs present.
fn fake_home() -> tempfile::TempDir {
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join(".claude.json"), r#"{"mcpServers":{}}"#).unwrap();
    std::fs::create_dir_all(home.path().join(".claude")).unwrap();
    let oc = home.path().join(".config/opencode");
    std::fs::create_dir_all(&oc).unwrap();
    // OpenCode uses the "mcp" key (not Claude's "mcpServers").
    std::fs::write(oc.join("opencode.json"), r#"{"mcp":{}}"#).unwrap();
    home
}

fn init_with(home: &Path, answers: &str) -> std::process::Output {
    init_args(home, &["init"], answers)
}

/// Run `init` (or `init --dry-run`) against a fake HOME with scripted answers.
fn init_args(home: &Path, args: &[&str], answers: &str) -> std::process::Output {
    use std::io::Write;
    use std::process::{Command, Stdio};

    let mut child = Command::new(binary_path())
        .args(args)
        .current_dir(home)
        .env("HOME", home)
        .env("NO_RELIARY_WATCHER", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn init");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(answers.as_bytes())
        .unwrap();
    child.wait_with_output().expect("init wait")
}

#[test]
fn e2e_cli_init_wires_mcp_entries() {
    let home = fake_home();
    let out = init_with(home.path(), "Y\nN\nY\nN\n");
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));

    let claude: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(home.path().join(".claude.json")).unwrap())
            .expect("claude config must stay valid JSON");
    assert!(
        claude["mcpServers"]["reliary"].is_object(),
        "init must add the reliary MCP server to Claude config: {}",
        claude
    );
    assert_eq!(
        claude["mcpServers"]["reliary"]["args"][0], "mcp",
        "MCP command must be the `mcp` subcommand: {}",
        claude
    );

    let oc: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(home.path().join(".config/opencode/opencode.json")).unwrap(),
    )
    .expect("opencode config must stay valid JSON");
    // OpenCode uses the "mcp" key (not "mcpServers").
    assert!(
        oc["mcp"]["reliary"].is_object() || oc["mcpServers"]["reliary"].is_object(),
        "init must add the reliary MCP server to OpenCode config: {}",
        oc
    );
    assert!(!text.contains("panicked"), "init must not panic: {}", text);
}

#[test]
fn e2e_cli_init_is_idempotent() {
    let home = fake_home();
    init_with(home.path(), "Y\nN\nY\nN\n");
    init_with(home.path(), "Y\nN\nY\nN\n");

    let claude: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(home.path().join(".claude.json")).unwrap())
            .unwrap();
    // Exactly one entry — a second init must not duplicate servers or args.
    let servers = claude["mcpServers"].as_object().expect("mcpServers object");
    assert_eq!(
        servers.keys().filter(|k| *k == "reliary").count(),
        1,
        "second init duplicated the server: {}",
        claude
    );
    let args = claude["mcpServers"]["reliary"]["args"].as_array().unwrap();
    assert_eq!(args.len(), 1, "args must not accumulate: {:?}", args);
}

#[test]
fn e2e_cli_uninstall_removes_mcp_entries() {
    let home = fake_home();
    init_with(home.path(), "Y\nN\nY\nN\n");

    // Confirm it was wired first.
    let before: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(home.path().join(".claude.json")).unwrap())
            .unwrap();
    assert!(
        before["mcpServers"]["reliary"].is_object(),
        "precondition: reliary must be wired"
    );

    let out = run_cli(&["uninstall"], home.path(), &[("HOME", home.path().to_str().unwrap())]);
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));

    let after: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(home.path().join(".claude.json")).unwrap())
            .expect("claude config must remain valid JSON after uninstall");
    assert!(
        after["mcpServers"].get("reliary").is_none(),
        "uninstall must remove the reliary MCP server: {}",
        after
    );
    assert!(!text.contains("panicked"), "uninstall must not panic: {}", text);
}

// ── the advertised short alias is real ─────────────────────────────────────
//
// `--help` used to print "Shorter: 'rel' also works for all commands", but
// nothing ever created a `rel` command — the hint was aspirational. These
// tests pin the two halves: init creates the shim, uninstall removes it, and
// the help text does not name a binary that is not the one being run.

/// The `rel` shim path under a fake HOME.
fn rel_shim(home: &Path) -> PathBuf {
    home.join(".local/bin").join(if cfg!(windows) { "rel.cmd" } else { "rel" })
}

#[test]
fn e2e_cli_init_installs_rel_alias() {
    let home = fake_home();
    // Answers: claude mcp, claude hooks, opencode mcp, opencode plugin, rel alias.
    let out = init_with(home.path(), "Y\nY\nY\nY\nY\n");
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));

    let shim = rel_shim(home.path());
    assert!(
        shim.symlink_metadata().is_ok(),
        "init must create the 'rel' shim it advertises: {}",
        text
    );

    // The shim must dispatch: running it reports the crate version.
    let rel_out = std::process::Command::new(&shim)
        .arg("--version")
        .current_dir(home.path())
        .env("HOME", home.path())
        .output()
        .expect("run rel shim");
    let rel_text = format!(
        "{}{}",
        String::from_utf8_lossy(&rel_out.stdout),
        String::from_utf8_lossy(&rel_out.stderr)
    );
    assert!(
        rel_text.contains("reliary") && rel_text.contains(env!("CARGO_PKG_VERSION")),
        "'rel' shim must dispatch to reliary and report its version: {}",
        rel_text
    );
}

#[test]
fn e2e_cli_uninstall_removes_rel_alias() {
    let home = fake_home();
    init_with(home.path(), "Y\nY\nY\nY\nY\n");
    assert!(
        rel_shim(home.path()).symlink_metadata().is_ok(),
        "precondition: init must have installed the shim"
    );

    let out = run_cli(
        &["uninstall"],
        home.path(),
        &[("HOME", home.path().to_str().unwrap())],
    );
    assert!(
        rel_shim(home.path()).symlink_metadata().is_err(),
        "uninstall must remove the 'rel' shim: {}",
        plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)))
    );
}

#[test]
fn e2e_cli_dry_run_does_not_install_rel_alias() {
    let home = fake_home();
    init_args(home.path(), &["init", "--dry-run"], "\n\n\n\n\n\n");
    assert!(
        rel_shim(home.path()).symlink_metadata().is_err(),
        "dry-run must not create the 'rel' shim"
    );
}

#[test]
fn e2e_cli_help_examples_use_the_real_binary_name() {
    let dir = tempfile::tempdir().unwrap();
    let out = run_cli(&["--help"], dir.path(), &[]);
    let text = plain(&stdout_of(&out));

    // The examples used to say `reliary-agent index .`, naming a binary the
    // user does not have. Every example line must start with `reliary `.
    let examples: Vec<&str> = text
        .lines()
        .skip_while(|l| !l.starts_with("EXAMPLES"))
        .skip(1)
        .take_while(|l| !l.trim().is_empty())
        .collect();
    assert!(!examples.is_empty(), "help must list examples: {}", text);
    for line in &examples {
        let cmd = line.trim();
        assert!(
            cmd.starts_with("reliary "),
            "example must invoke the real binary 'reliary': {:?}",
            cmd
        );
        assert!(
            !cmd.contains("reliary-agent"),
            "example must not reference the crate name 'reliary-agent': {:?}",
            cmd
        );
    }

    // Usage line must match the shipped binary name too.
    assert!(
        text.contains("Usage: reliary"),
        "--help usage line must name the binary 'reliary': {}",
        text
    );
}

// ── completions / man ─────────────────────────────────────────────────────
#[test]
fn e2e_cli_completions_and_man_emit_output() {
    let dir = tempfile::tempdir().unwrap();
    for shell in ["bash", "zsh", "fish"] {
        let out = run_cli(&["completions", shell], dir.path(), &[]);
        assert!(
            out.status.success(),
            "completions {} failed: {}",
            shell,
            stderr_of(&out)
        );
        assert!(
            !stdout_of(&out).trim().is_empty(),
            "completions {} produced no output",
            shell
        );
    }

    let out = run_cli(&["man"], dir.path(), &[]);
    let text = format!("{}{}", stdout_of(&out), stderr_of(&out));
    assert!(
        text.contains("reliary"),
        "man page must mention the binary: {}",
        &text[..text.len().min(200)]
    );
}

// ── version ───────────────────────────────────────────────────────────────

#[test]
fn e2e_cli_version_matches_crate_version() {
    let dir = tempfile::tempdir().unwrap();
    let out = run_cli(&["--version"], dir.path(), &[]);
    let text = stdout_of(&out);
    let expected = env!("CARGO_PKG_VERSION");
    assert!(
        text.contains(expected),
        "--version must report the crate version {}: {}",
        expected,
        text
    );
}

// ── integration conformance (init ↔ settings ↔ doctor ↔ uninstall) ────────
//
// The install path used to write hook files and register only one of them,
// and uninstall removed files without removing their registrations — leaving
// a command that fires a failing exec on every tool call. These tests pin the
// whole loop: every registered command must resolve to a file on disk, and
// uninstall must remove exactly what install added.

/// Read `~/.claude/settings.json` from the fake HOME.
fn read_settings(home: &Path) -> serde_json::Value {
    let raw = std::fs::read_to_string(home.join(".claude/settings.json"))
        .expect("settings.json must exist");
    serde_json::from_str(&raw).expect("settings.json must stay valid JSON")
}

/// Every hook command in settings.json, paired with its event.
fn hook_commands(settings: &serde_json::Value) -> Vec<(String, String)> {
    let mut out = Vec::new();
    if let Some(hooks) = settings.get("hooks").and_then(|h| h.as_object()) {
        for (event, entries) in hooks {
            let Some(arr) = entries.as_array() else { continue };
            for entry in arr {
                let Some(hs) = entry.get("hooks").and_then(|h| h.as_array()) else { continue };
                for h in hs {
                    if let Some(cmd) = h.get("command").and_then(|c| c.as_str()) {
                        out.push((event.clone(), cmd.to_string()));
                    }
                }
            }
        }
    }
    out
}

#[test]
fn e2e_cli_init_registers_resolvable_hooks() {
    let home = fake_home();
    let out = init_with(home.path(), "Y\nY\nY\nN\n");
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(!text.contains("panicked"), "init must not panic: {}", text);

    // Both hook files must exist and be executable.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        for name in ["reliary-session-reminder", "reliary-sift-pretooluse"] {
            let p = home.path().join(".claude/hooks").join(name);
            assert!(p.exists(), "hook file must be written: {}", p.display());
            let mode = std::fs::metadata(&p).unwrap().permissions().mode();
            assert_eq!(mode & 0o111, 0o111, "{} must be executable", p.display());
        }
    }

    // Every registered hook command must resolve to an existing file. A
    // registration without its file fires a failing exec on every call.
    let settings = read_settings(home.path());
    let commands = hook_commands(&settings);
    assert!(
        !commands.is_empty(),
        "init must register at least one hook: {}",
        settings
    );
    for (event, cmd) in &commands {
        let prog = cmd.split_whitespace().next().unwrap_or("");
        let path = if let Some(rest) = prog.strip_prefix("~/") {
            home.path().join(rest)
        } else {
            std::path::PathBuf::from(prog)
        };
        assert!(
            path.exists(),
            "registered {} hook command does not exist on disk: {} (resolved {})",
            event,
            cmd,
            path.display()
        );
    }
}

#[test]
fn e2e_cli_doctor_reports_wired_integrations() {
    let home = fake_home();
    init_with(home.path(), "Y\nY\nY\nN\n");

    let out = run_cli(
        &["doctor", "--format", "json"],
        home.path(),
        &[("HOME", home.path().to_str().unwrap())],
    );
    let text = stdout_of(&out);
    let v: serde_json::Value = serde_json::from_str(&text)
        .unwrap_or_else(|e| panic!("doctor --format json must emit JSON ({}): {}", e, text));
    let checks = v["checks"].as_array().expect("checks array");
    for name in ["claude", "opencode"] {
        let c = checks
            .iter()
            .find(|c| c["name"] == name)
            .unwrap_or_else(|| panic!("doctor must report a {} check: {}", name, v));
        assert_eq!(
            c["ok"], true,
            "doctor must report {} wired after init: {}",
            name, c
        );
    }
}

#[test]
fn e2e_cli_opencode_mcp_entry_matches_opencode_schema() {
    let home = fake_home();
    init_with(home.path(), "Y\nY\nY\nY\nY\n");

    let oc: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(home.path().join(".config/opencode/opencode.json")).unwrap(),
    )
    .expect("opencode config must stay valid JSON");

    let entry = &oc["mcp"]["reliary"];
    // OpenCode's local-server schema: type:"local" and an ARRAY command.
    // The Claude/Cline shape ({command:"<str>", args:[...]}) decodes as
    // invalid and the server never starts.
    assert_eq!(
        entry["type"], "local",
        "mcp.reliary must be type:\"local\" for OpenCode: {}",
        entry
    );
    let cmd = entry["command"]
        .as_array()
        .unwrap_or_else(|| panic!("mcp.reliary.command must be an array: {}", entry));
    assert!(!cmd.is_empty(), "command array must not be empty");
    assert_eq!(cmd[1], "mcp", "second element must be the `mcp` subcommand: {}", entry);
    assert!(
        entry.get("args").is_none(),
        "OpenCode entries must not carry a Claude-style \"args\" key: {}",
        entry
    );
}

#[test]
fn e2e_cli_opencode_plugin_entry_points_at_real_file() {
    let home = fake_home();
    init_with(home.path(), "Y\nY\nY\nY\nY\n");

    let oc: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(home.path().join(".config/opencode/opencode.json")).unwrap(),
    )
    .unwrap();
    let plugins = oc["plugin"].as_array().expect("plugin array must exist");
    let reliary_plugin = plugins
        .iter()
        .filter_map(|p| p.as_str())
        .find(|p| p.ends_with("opencode-plugin.js"))
        .unwrap_or_else(|| panic!("plugin array must name the reliary plugin: {}", oc));

    // The registered path must exist — registering a file we never wrote is
    // the failure this whole change fixes.
    assert!(
        std::path::Path::new(reliary_plugin).exists(),
        "registered plugin file must exist on disk: {}",
        reliary_plugin
    );
    // And it must be under the fake HOME, not the dev tree.
    assert!(
        reliary_plugin.starts_with(home.path().to_str().unwrap()),
        "plugin must be written into the data dir, not the source tree: {}",
        reliary_plugin
    );
}

#[test]
fn e2e_cli_uninstall_removes_opencode_plugin_and_file() {
    let home = fake_home();
    init_with(home.path(), "Y\nY\nY\nY\nY\n");

    let oc_path = home.path().join(".config/opencode/opencode.json");
    let plugin_path = serde_json::from_str::<serde_json::Value>(&std::fs::read_to_string(&oc_path).unwrap())
        .unwrap()["plugin"]
        .as_array()
        .unwrap()
        .iter()
        .filter_map(|p| p.as_str())
        .find(|p| p.ends_with("opencode-plugin.js"))
        .expect("precondition: plugin must be registered")
        .to_string();

    run_cli(&["uninstall"], home.path(), &[("HOME", home.path().to_str().unwrap())]);

    let after: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&oc_path).unwrap()).unwrap();
    let still = after["plugin"]
        .as_array()
        .map(|a| a.iter().filter_map(|p| p.as_str()).any(|p| p.contains("opencode-plugin.js")))
        .unwrap_or(false);
    assert!(!still, "uninstall must remove the reliary plugin entry: {}", after);
    assert!(
        !std::path::Path::new(&plugin_path).exists(),
        "uninstall must delete the materialized plugin file: {}",
        plugin_path
    );
}

#[test]
fn e2e_cli_opencode_jsonc_only_is_wired() {
    // A `.jsonc`-only setup (OpenCode's documented default) must be found and
    // edited, not silently skipped because we only looked for opencode.json.
    let home = tempfile::tempdir().unwrap();
    std::fs::write(home.path().join(".claude.json"), r#"{"mcpServers":{}}"#).unwrap();
    std::fs::create_dir_all(home.path().join(".claude")).unwrap();
    let oc = home.path().join(".config/opencode");
    std::fs::create_dir_all(&oc).unwrap();
    std::fs::write(oc.join("opencode.jsonc"), "{\n  // opencode config\n  \"mcp\": {}\n}\n").unwrap();

    // n for claude mcp/hooks, y for opencode mcp/plugin, y for rel alias.
    let out = init_with(home.path(), "N\nN\nY\nY\nY\n");
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(
        text.contains("Updated opencode.jsonc"),
        "init must edit the .jsonc config it found: {}",
        text
    );
    let raw = std::fs::read_to_string(oc.join("opencode.jsonc")).unwrap();
    assert!(
        raw.contains("reliary"),
        "the .jsonc config must contain the reliary MCP entry: {}",
        raw
    );
}

#[test]
fn e2e_cli_doctor_flags_malformed_opencode_entry() {
    // The old shape (string command + args) is invalid for OpenCode; doctor
    // must not report it green.
    let home = tempfile::tempdir().unwrap();
    let oc = home.path().join(".config/opencode");
    std::fs::create_dir_all(&oc).unwrap();
    std::fs::write(
        oc.join("opencode.json"),
        r#"{"mcp":{"reliary":{"command":"/usr/bin/reliary","args":["mcp"]}}}"#,
    )
    .unwrap();

    let out = run_cli(
        &["doctor", "--format", "json"],
        home.path(),
        &[("HOME", home.path().to_str().unwrap())],
    );
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    let c = v["checks"]
        .as_array()
        .unwrap()
        .iter()
        .find(|c| c["name"] == "opencode")
        .unwrap();
    assert_eq!(
        c["ok"], false,
        "doctor must flag a malformed OpenCode MCP entry, not report it green: {}",
        c
    );
}

#[test]
fn e2e_cli_init_dry_run_mutates_nothing() {    let home = fake_home();
    // Seed a settings file with unrelated content that must survive.
    let settings_path = home.path().join(".claude/settings.json");
    std::fs::write(&settings_path, r#"{"env":{"KEEP":"1"}}"#).unwrap();
    let before_settings = std::fs::read(&settings_path).unwrap();
    let before_claude = std::fs::read(home.path().join(".claude.json")).unwrap();

    let out = init_args(home.path(), &["init", "--dry-run"], "\n\n\n\n\n\n");
    assert!(out.status.success(), "dry-run init must exit 0");

    assert_eq!(
        std::fs::read(&settings_path).unwrap(),
        before_settings,
        "dry-run must not modify settings.json"
    );
    assert_eq!(
        std::fs::read(home.path().join(".claude.json")).unwrap(),
        before_claude,
        "dry-run must not modify .claude.json"
    );
    assert!(
        !home.path().join(".claude/hooks").exists(),
        "dry-run must not create hook files"
    );
}

#[test]
fn e2e_cli_reinit_does_not_duplicate_hooks() {
    let home = fake_home();
    init_with(home.path(), "Y\nY\nY\nN\n");
    let first = hook_commands(&read_settings(home.path()));
    init_with(home.path(), "Y\nY\nY\nN\n");
    let second = hook_commands(&read_settings(home.path()));
    assert_eq!(
        first.len(),
        second.len(),
        "a second init must not duplicate hook entries: {:?} -> {:?}",
        first,
        second
    );
}

#[test]
fn e2e_cli_uninstall_removes_hooks_and_registrations() {
    let home = fake_home();
    // Seed an unrelated hook that must survive uninstall.
    let settings_path = home.path().join(".claude/settings.json");
    std::fs::write(
        &settings_path,
        r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"/bin/true"}]}]}}"#,
    )
    .unwrap();

    init_with(home.path(), "Y\nY\nY\nN\n");
    assert!(
        !hook_commands(&read_settings(home.path())).is_empty(),
        "precondition: init must register hooks"
    );

    let out = run_cli(
        &["uninstall"],
        home.path(),
        &[("HOME", home.path().to_str().unwrap())],
    );
    let text = plain(&format!("{}{}", stdout_of(&out), stderr_of(&out)));
    assert!(!text.contains("panicked"), "uninstall must not panic: {}", text);

    // No reliary hook command may remain registered.
    let remaining = hook_commands(&read_settings(home.path()));
    let reliary: Vec<_> = remaining
        .iter()
        .filter(|(_, c)| c.contains("reliary"))
        .collect();
    assert!(
        reliary.is_empty(),
        "uninstall must strip every reliary hook registration: {:?}",
        reliary
    );
    // The unrelated hook must survive.
    assert!(
        remaining.iter().any(|(_, c)| c == "/bin/true"),
        "uninstall must not touch unrelated hooks: {:?}",
        remaining
    );
    // Hook files must be gone.
    assert!(
        !home.path().join(".claude/hooks/reliary-session-reminder").exists(),
        "uninstall must remove the reminder hook file"
    );
    assert!(
        !home.path().join(".claude/hooks/reliary-sift-pretooluse").exists(),
        "uninstall must remove the sift hook file"
    );
}

#[test]
fn e2e_cli_doctor_flags_unusable_index() {
    // A `.reliary/index.sqlite` that exists but is not a database used to be
    // reported as a green tick. It must now be a failure that names the file.
    let dir = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(dir.path().join(".reliary")).unwrap();
    std::fs::write(dir.path().join(".reliary/index.sqlite"), b"not a database").unwrap();

    let out = run_cli(&["doctor", "--format", "json"], dir.path(), &[]);
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    let index = v["checks"].as_array().unwrap().iter()
        .find(|c| c["name"] == "index").expect("index check");
    assert_eq!(
        index["ok"], false,
        "doctor must not report an unusable index as ok: {}", index
    );
    assert!(
        index["detail"].as_str().unwrap_or("").contains("not a usable index"),
        "doctor must explain the index is unusable: {}", index
    );
    assert_eq!(v["ready"], false, "an unusable index means not ready: {}", v);

    // And an absent index is still a failure with the rebuild hint.
    let dir2 = tempfile::tempdir().unwrap();
    let out = run_cli(&["doctor", "--format", "json"], dir2.path(), &[]);
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    let index = v["checks"].as_array().unwrap().iter()
        .find(|c| c["name"] == "index").expect("index check");
    assert_eq!(index["ok"], false, "no index must not be ok: {}", index);
    assert!(
        index["detail"].as_str().unwrap_or("").contains("reliary trust"),
        "doctor must suggest how to build the index: {}", index
    );
}

#[test]
fn e2e_cli_doctor_flags_dangling_hook_registration() {
    // A settings.json that registers a reliary hook whose file is missing is
    // a broken install: doctor must report claude as not-ok and name it.
    let home = fake_home();
    std::fs::write(home.path().join(".claude.json"),
        r#"{"mcpServers":{"reliary":{"command":"/bin/true","args":["mcp"]}}}"#).unwrap();
    std::fs::create_dir_all(home.path().join(".claude/hooks")).unwrap();
    std::fs::write(home.path().join(".claude/settings.json"),
        r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"~/.claude/hooks/reliary-sift-pretooluse"}]}]}}"#).unwrap();

    let out = run_cli(
        &["doctor", "--format", "json"],
        home.path(),
        &[("HOME", home.path().to_str().unwrap())],
    );
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    let claude = v["checks"].as_array().unwrap().iter()
        .find(|c| c["name"] == "claude").expect("claude check");
    assert_eq!(
        claude["ok"], false,
        "doctor must flag a registered hook with no file on disk: {}", claude
    );
    assert!(
        claude["detail"].as_str().unwrap_or("").contains("reliary-sift-pretooluse"),
        "doctor must name the dangling hook: {}", claude
    );

    // Creating the file must clear the failure.
    std::fs::write(home.path().join(".claude/hooks/reliary-sift-pretooluse"), "#!/bin/sh\n").unwrap();
    std::fs::write(home.path().join(".claude/hooks/reliary-session-reminder"), "#!/bin/sh\n").unwrap();
    let out = run_cli(
        &["doctor", "--format", "json"],
        home.path(),
        &[("HOME", home.path().to_str().unwrap())],
    );
    let v: serde_json::Value = serde_json::from_str(&stdout_of(&out)).unwrap();
    let claude = v["checks"].as_array().unwrap().iter()
        .find(|c| c["name"] == "claude").expect("claude check");
    assert_eq!(
        claude["ok"], true,
        "doctor must clear the flag once the hook file exists: {}", claude
    );
}

/// `.reliary/` must be invisible to git after `trust`, so `git add .` cannot
/// stage the source-derived index or the raw-command cache.
///
/// Negative control: with the self-ignore removed, the same `git add .` DOES
/// stage `.reliary/index.sqlite` — proving the assertion has teeth.
#[test]
fn trust_self_ignores_reliary_in_git() {
    let fx = Fixture::new();
    fx.trust();

    // The self-ignore file exists and contains the blanket pattern.
    let gi = fx.path().join(".reliary/.gitignore");
    assert!(gi.exists(), "trust must write .reliary/.gitignore");
    assert_eq!(std::fs::read_to_string(&gi).unwrap().trim(), "*");

    // `.reliary/` does not appear in git status (the fixture's own source is
    // untracked, so we assert on the absence of .reliary, not on emptiness).
    let status = std::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(fx.path())
        .output()
        .expect("git status");
    let status = String::from_utf8_lossy(&status.stdout);
    assert!(
        !status.contains(".reliary"),
        "git status must not mention .reliary, got: {status}"
    );

    let _ = std::process::Command::new("git")
        .args(["add", "."]).current_dir(fx.path()).output();
    let staged = std::process::Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .current_dir(fx.path())
        .output()
        .expect("git diff");
    let staged = String::from_utf8_lossy(&staged.stdout);
    assert!(
        !staged.contains(".reliary"),
        ".reliary must never be staged, got: {staged}"
    );

    // Negative control: removing the guard leaks the index.
    std::fs::remove_file(&gi).unwrap();
    let _ = std::process::Command::new("git")
        .args(["add", "."]).current_dir(fx.path()).output();
    let staged = std::process::Command::new("git")
        .args(["diff", "--cached", "--name-only"])
        .current_dir(fx.path())
        .output()
        .expect("git diff");
    let staged = String::from_utf8_lossy(&staged.stdout);
    assert!(
        staged.contains(".reliary/index.sqlite"),
        "negative control failed: without the guard the index MUST be stageable, got: {staged}"
    );
}

/// P1.2: piped stdin with no answers must FAIL CLOSED (exit 2), never auto-accept.
#[test]
fn e2e_cli_init_closed_stdin_exits_nonzero() {
    use std::process::{Command, Stdio};
    let home = fake_home();
    // Immediate EOF: no answers at all.
    let out = Command::new(crate::binary_path())
        .args(["init"])
        .current_dir(home.path())
        .env("HOME", home.path())
        .env("NO_RELIARY_WATCHER", "1")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("spawn init");
    assert!(!out.status.success(), "init with closed stdin must fail closed");
    assert_eq!(out.status.code(), Some(2), "exit code must be 2, got {:?}", out.status.code());
    // Nothing was written: no MCP entries added.
    let claude: serde_json::Value = serde_json::from_str(
        &std::fs::read_to_string(home.path().join(".claude.json")).unwrap(),
    ).unwrap();
    assert!(claude["mcpServers"]["reliary"].is_null(), "fail-closed init must not wire anything: {}", claude);
}

/// P1.2: `clean` with closed stdin must refuse (exit 2), not wipe.
#[test]
fn e2e_cli_clean_closed_stdin_refuses() {
    use std::process::{Command, Stdio};
    let fx = Fixture::new();
    fx.trust();
    assert!(fx.path().join(".reliary").exists());
    let out = Command::new(crate::binary_path())
        .args(["clean"])
        .current_dir(fx.path())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .expect("spawn clean");
    assert_eq!(out.status.code(), Some(2), "clean with closed stdin must exit 2");
    assert!(fx.path().join(".reliary").exists(), "fail-closed clean must not delete");
}

/// P1.4: `status --path` resolves a foreign project.
#[test]
fn e2e_cli_status_path_flag() {
    let fx = Fixture::new();
    fx.trust();
    let out = std::process::Command::new(crate::binary_path())
        .args(["status", "--path", &fx.path().to_string_lossy()])
        .current_dir("/tmp")
        .output()
        .expect("spawn status");
    assert!(out.status.success());
    let text = String::from_utf8_lossy(&out.stdout).to_string();
    assert!(text.contains("files indexed"), "status --path must report the foreign index: {}", text);
}

/// P2.2: `search` with no index exits 2 (not silent token fallback).
#[test]
fn e2e_cli_search_no_index_exits_two() {
    let tmp = tempfile::tempdir().unwrap();
    let out = std::process::Command::new(crate::binary_path())
        .args(["search", "foo", &tmp.path().to_string_lossy()])
        .stdin(std::process::Stdio::null())
        .output()
        .expect("spawn search");
    assert_eq!(out.status.code(), Some(2), "search with no index must exit 2");
}

/// F5: `cache-retrieve` falls back to the tee file (content-addressed SHA-256).
#[test]
fn e2e_cli_cache_retrieve_falls_back_to_tee() {
    let fx = Fixture::new();
    fx.trust();
    // Write a tee file directly (save_tee path) and retrieve it by hash.
    let raw = "tee-fallback-probe-output";
    let hash = {
        use sha2::{Digest, Sha256};
        format!("{:x}", Sha256::digest(raw.as_bytes()))
    };
    let tee_dir = std::path::PathBuf::from("/tmp/reliary-tee");
    std::fs::create_dir_all(&tee_dir).ok(); // GUARDED: intentional — test setup, failure surfaces as missing file below
    std::fs::write(tee_dir.join(&hash), raw).unwrap();
    let out = std::process::Command::new(crate::binary_path())
        .args(["cache-retrieve", &hash])
        .current_dir(fx.path())
        .output()
        .expect("spawn cache-retrieve");
    assert!(out.status.success(), "tee fallback must succeed");
    assert_eq!(String::from_utf8_lossy(&out.stdout), raw);
    let _ = std::fs::remove_file(tee_dir.join(&hash));
}

/// F5 negative control: a path-traversal tee name is refused, not read.
#[test]
fn e2e_cli_cache_retrieve_rejects_traversal() {
    let fx = Fixture::new();
    fx.trust();
    let out = std::process::Command::new(crate::binary_path())
        .args(["cache-retrieve", "../../etc/passwd"])
        .current_dir(fx.path())
        .output()
        .expect("spawn cache-retrieve");
    assert!(!out.status.success(), "traversal tee name must be refused");
}