heddle-cli 0.15.4

An AI-native version control system
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
// SPDX-License-Identifier: Apache-2.0
//! End-to-end coverage for the redaction primitive.
//!
//! Build brief: `.agents/redaction-primitive.md`. The acceptance
//! criteria boil down to:
//!
//! 1. `heddle redact apply <state> --path <file>` writes a `Redaction`
//!    record and the state's `read_file` returns the stub on
//!    subsequent materialization.
//! 2. `heddle redact purge apply ... --force` removes the loose blob bytes
//!    and writes a `Purge` oplog entry. The `Redaction` record stays.
//! 3. `heddle redact list` / `heddle redact purge list` enumerate what's on
//!    disk; `heddle redact show` resolves by short id.
//!
//! These tests drive the CLI binary as a subprocess so they exercise
//! the full args → handler → repo → materialize stack rather than
//! poking at internals.

use std::{fs, process::Command};

use crypto::Signer;
use serde_json::Value;
use tempfile::TempDir;

use super::{assert_json_recovery_advice_fields, heddle, heddle_output};

fn write_test_private_key(path: &std::path::Path, pem: &str) {
    objects::fs_atomic::write_file_atomic_secret(path, pem.as_bytes())
        .expect("write test private key");
}

fn trust_redact_public_key(repo: &std::path::Path, public_key_hex: &str) {
    let config_path = repo.join(".heddle/config.toml");
    let mut config = fs::read_to_string(&config_path).expect("read config");
    config.push_str(&format!(
        "\n[redact]\ntrusted_keys = [{{ algorithm = \"ed25519\", public_key = \"{public_key_hex}\" }}]\n"
    ));
    fs::write(&config_path, config).expect("write redact trust list");
}

/// Bootstrap a repo containing a fake-secret file in a captured state.
/// Returns the temp dir and the short change-id of the capture.
fn setup_repo_with_secret() -> (TempDir, String) {
    let temp = TempDir::new().unwrap();
    heddle(&["init"], Some(temp.path())).unwrap();
    fs::create_dir_all(temp.path().join("config")).unwrap();
    fs::write(
        temp.path().join("config/secrets.toml"),
        b"api_token = \"super-secret-leaked-value\"\n",
    )
    .unwrap();
    heddle(&["capture", "-m", "leak the secret"], Some(temp.path())).unwrap();

    let raw = heddle(
        &["--output", "json", "log", "--limit", "1"],
        Some(temp.path()),
    )
    .unwrap();
    let value: Value = serde_json::from_str(&raw).unwrap();
    let state = value["states"][0]["state_id"]
        .as_str()
        .expect("log --output json should expose state_id")
        .to_string();
    (temp, state)
}

fn setup_git_overlay_repo_with_secret() -> (TempDir, String) {
    let temp = TempDir::new().unwrap();
    git_overlay_fixture_cmd(temp.path(), &["init", "-b", "main"]);
    git_overlay_fixture_cmd(temp.path(), &["config", "user.name", "Heddle Test"]);
    git_overlay_fixture_cmd(temp.path(), &["config", "user.email", "heddle@example.com"]);
    fs::write(temp.path().join("README.md"), "seed\n").unwrap();
    git_overlay_fixture_cmd(temp.path(), &["add", "."]);
    git_overlay_fixture_cmd(temp.path(), &["commit", "-m", "seed"]);
    heddle(&["init"], Some(temp.path())).unwrap();
    heddle(
        &["bridge", "git", "import", "--ref", "main"],
        Some(temp.path()),
    )
    .unwrap();

    fs::create_dir_all(temp.path().join("config")).unwrap();
    fs::write(
        temp.path().join("config/secrets.toml"),
        b"api_token = \"super-secret-leaked-value\"\n",
    )
    .unwrap();
    heddle(&["capture", "-m", "leak the secret"], Some(temp.path())).expect("heddle capture");
    heddle(&["commit", "-m", "leak the secret"], Some(temp.path())).expect("heddle commit");

    let raw = heddle(
        &["--output", "json", "log", "--limit", "1"],
        Some(temp.path()),
    )
    .unwrap();
    let value: Value = serde_json::from_str(&raw).unwrap();
    let state = value["states"][0]["state_id"]
        .as_str()
        .expect("log --output json should expose state_id")
        .to_string();
    (temp, state)
}

fn git_overlay_fixture_cmd(path: &std::path::Path, args: &[&str]) {
    let output = Command::new("git")
        .args(args)
        .current_dir(path)
        .output()
        .unwrap_or_else(|err| panic!("git {args:?} should run: {err}"));
    assert!(
        output.status.success(),
        "git {args:?} failed\nstdout:\n{}\nstderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

#[test]
fn redact_apply_writes_record_and_emits_short_id() {
    let (temp, state) = setup_repo_with_secret();
    let raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .expect("redact apply should succeed");
    let value: Value = serde_json::from_str(&raw).expect("redact apply output should be JSON");
    let redaction_id = value["redaction_id"].as_str().expect("redaction_id");
    // Redaction ids are blob-style ContentHash short forms (8 hex
    // chars; no `hs-` prefix — that lives on StateId only). The
    // contract is "non-empty, deterministic".
    assert_eq!(
        redaction_id.len(),
        8,
        "redaction id should be an 8-hex-char short form: {redaction_id}"
    );
    assert!(
        redaction_id.chars().all(|c| c.is_ascii_hexdigit()),
        "redaction id should be hex: {redaction_id}"
    );
    assert_eq!(value["path"].as_str().unwrap(), "config/secrets.toml");
    assert_eq!(value["reason"].as_str().unwrap(), "leaked credential");
    assert_eq!(value["states_redacted"].as_u64().unwrap(), 1);
}

#[test]
fn redact_list_surfaces_every_active_redaction() {
    let (temp, state) = setup_repo_with_secret();
    heddle(
        &[
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();

    let raw = heddle(&["--output", "json", "redact", "list"], Some(temp.path()))
        .expect("redact list should succeed");
    let value: Value = serde_json::from_str(&raw).expect("redact list should emit JSON");
    assert_eq!(value["count"].as_u64().unwrap(), 1);
    let entries = value["redactions"].as_array().unwrap();
    assert_eq!(entries.len(), 1);
    assert_eq!(entries[0]["path"].as_str().unwrap(), "config/secrets.toml");
    assert_eq!(entries[0]["reason"].as_str().unwrap(), "leaked credential");
    // Pre-purge, the redaction should advertise that bytes remain on
    // disk. Operators reading the list need to know which entries are
    // still recoverable vs. permanently gone.
    assert!(!entries[0]["purged"].as_bool().unwrap());
}

#[test]
fn redact_show_resolves_by_short_id() {
    let (temp, state) = setup_repo_with_secret();
    let apply_raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();
    let apply: Value = serde_json::from_str(&apply_raw).unwrap();
    let id = apply["redaction_id"].as_str().unwrap().to_string();

    let raw = heddle(
        &["--output", "json", "redact", "show", &id],
        Some(temp.path()),
    )
    .expect("redact show should accept short id");
    let value: Value = serde_json::from_str(&raw).expect("redact show should emit JSON");
    assert_eq!(value["redaction_id"].as_str().unwrap(), id);
    let stub = value["stub_preview"]
        .as_str()
        .expect("stub_preview present");
    assert!(stub.contains("redacted by Heddle"));
    assert!(stub.contains("leaked credential"));
}

#[test]
fn purge_apply_refuses_without_force() {
    let (temp, state) = setup_repo_with_secret();
    heddle(
        &[
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();
    let output = heddle_output(
        &[
            "--output",
            "json",
            "redact",
            "purge",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
        ],
        Some(temp.path()),
    )
    .expect("invoke purge apply");
    assert!(
        !output.status.success(),
        "purge without --force must refuse"
    );
    assert!(
        output.stdout.is_empty(),
        "JSON-mode purge refusal must not write stdout: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    let err: Value =
        serde_json::from_str(&stderr).expect("purge refusal should emit JSON error envelope");
    assert_json_recovery_advice_fields(&err, &err.to_string());
    assert!(
        err["kind"] == "destructive_requires_force"
            && err["error"]
                .as_str()
                .is_some_and(|error| error.contains("Refusing to purge")
                    && error.contains("destructive action requires --force"))
            && err["unsafe_condition"]
                .as_str()
                .is_some_and(|condition| condition.contains("purge is irreversible"))
            && err["preserved"]
                .as_str()
                .is_some_and(|preserved| preserved.contains("nothing was removed"))
            && err["hint"]
                .as_str()
                .is_some_and(|hint| hint.contains("heddle redact list")
                    && hint.contains("heddle redact purge apply")
                    && hint.contains("--force")),
        "refusal must use the shared destructive-force advice: {stderr}"
    );
}

#[test]
fn undo_redact_refusal_uses_json_error_envelope() {
    let (temp, state) = setup_repo_with_secret();
    heddle(
        &[
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();

    let output = heddle_output(&["--output", "json", "undo"], Some(temp.path()))
        .expect("invoke undo redaction");
    assert!(!output.status.success(), "undo redaction should refuse");
    assert!(
        output.stdout.is_empty(),
        "JSON-mode undo refusal must not write stdout: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    let err: Value =
        serde_json::from_str(&stderr).expect("undo refusal should emit JSON error envelope");
    assert_json_recovery_advice_fields(&err, &err.to_string());
    assert!(
        err["kind"] == "redaction_undo_requires_confirmation"
            && err["error"]
                .as_str()
                .is_some_and(|error| error.contains("Refusing to undo")
                    && error.contains("redact apply")
                    && error.contains("re-expose previously-hidden content"))
            && err["preserved"]
                .as_str()
                .is_some_and(|preserved| preserved.contains("no undo mutation was applied"))
            && err["hint"]
                .as_str()
                .is_some_and(|hint| hint.contains("--allow-redact-undo")),
        "undo redaction refusal should expose typed JSON advice: {stderr}"
    );
}

#[test]
fn purge_apply_with_force_records_and_marks_redaction_purged() {
    let (temp, state) = setup_repo_with_secret();
    heddle(
        &[
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();
    let raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "purge",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--force",
        ],
        Some(temp.path()),
    )
    .expect("purge apply --force should succeed");
    let value: Value = serde_json::from_str(&raw).expect("purge apply should emit JSON");
    assert_eq!(value["redactions_marked"].as_u64().unwrap(), 1);

    let list_raw = heddle(&["--output", "json", "redact", "list"], Some(temp.path())).unwrap();
    let list: Value = serde_json::from_str(&list_raw).unwrap();
    let entries = list["redactions"].as_array().unwrap();
    assert!(
        entries[0]["purged"].as_bool().unwrap(),
        "after purge, the redaction must surface as purged in list output"
    );

    let purge_list_raw = heddle(
        &["--output", "json", "redact", "purge", "list"],
        Some(temp.path()),
    )
    .unwrap();
    let purge_list: Value = serde_json::from_str(&purge_list_raw).unwrap();
    assert_eq!(
        purge_list["count"].as_u64().unwrap(),
        1,
        "purge list must surface exactly one entry after one purge"
    );
}

#[test]
fn purge_root_alias_is_rejected() {
    let err = heddle(&["purge", "apply"], None)
        .expect_err("removed purge root alias should fail through clap");
    assert!(
        err.contains("unrecognized subcommand 'purge'")
            || err.contains("unexpected argument 'purge'"),
        "clap should reject the removed purge alias: {err}"
    );
}

#[test]
fn redact_apply_with_sign_with_records_signature_verifiable_on_show() {
    // Critical acceptance criterion (build brief item 3): redactions
    // are signed (Ed25519) and `heddle redact show` displays
    // verification status alongside the merge-signature equivalent.
    use crypto::Ed25519Signer;

    let (temp, state) = setup_repo_with_secret();
    let signer = Ed25519Signer::generate().expect("generate ed25519 signing key");
    let key_pem = signer.to_pem().expect("export PEM");
    let key_path = temp.path().join("redact_signing_key.pem");
    write_test_private_key(&key_path, &key_pem);

    let apply_raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
            "--sign-with",
            &key_path.to_string_lossy(),
        ],
        Some(temp.path()),
    )
    .expect("redact apply --sign-with should succeed");
    let apply: Value = serde_json::from_str(&apply_raw).expect("redact apply JSON");
    assert!(
        apply["signed"].as_bool().unwrap(),
        "redact apply with --sign-with must report signed=true"
    );
    assert_eq!(
        apply["signature_algorithm"].as_str().unwrap(),
        "ed25519",
        "Ed25519 key file should be detected as ed25519"
    );

    let id = apply["redaction_id"].as_str().unwrap().to_string();
    let show_raw = heddle(
        &["--output", "json", "redact", "show", &id],
        Some(temp.path()),
    )
    .unwrap();
    let show: Value = serde_json::from_str(&show_raw).unwrap();
    assert!(
        show["signed"].as_bool().unwrap(),
        "redact show must report signed=true after a signed apply"
    );
    assert_eq!(
        show["signature_status"].as_str().unwrap(),
        "verified",
        "redact show must verify the signature it just stored — round-trip property"
    );
    assert_eq!(
        show["signature_algorithm"].as_str().unwrap(),
        "ed25519",
        "show must surface the signing algorithm"
    );
}

#[test]
fn redact_show_without_sign_with_reports_unsigned() {
    // Mirror property: unsigned redactions must surface as
    // `signature_status: "unsigned"` so auditors can sort the
    // attested-vs-asserted axis cleanly.
    let (temp, state) = setup_repo_with_secret();
    let apply_raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();
    let apply: Value = serde_json::from_str(&apply_raw).unwrap();
    assert!(
        !apply["signed"].as_bool().unwrap(),
        "redact apply without --sign-with must report signed=false"
    );
    let id = apply["redaction_id"].as_str().unwrap();

    let show_raw = heddle(
        &["--output", "json", "redact", "show", id],
        Some(temp.path()),
    )
    .unwrap();
    let show: Value = serde_json::from_str(&show_raw).unwrap();
    assert!(!show["signed"].as_bool().unwrap());
    assert_eq!(
        show["signature_status"].as_str().unwrap(),
        "unsigned",
        "redact show must call unsigned redactions out explicitly"
    );
}

#[test]
fn redact_apply_is_idempotent_on_identical_input() {
    // Build brief property #1: "Redact is idempotent — redacting a
    // blob that's already redacted is a no-op (or returns a
    // supersedes chain)". Today the idempotent path returns the
    // existing redaction's content-addressed id rather than writing
    // a duplicate. This test pins that: two identical applies
    // produce the same `redaction_id`.
    let (temp, state) = setup_repo_with_secret();
    let first = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();
    let second = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(temp.path()),
    )
    .unwrap();
    // The two responses may differ in `redacted_at` (we re-record an
    // oplog entry on each call so the audit trail surfaces retries);
    // but the redactions_blob is idempotent on canonical content, so
    // a re-emitted `redaction_id` for a fresh payload differs only
    // by timestamp. We assert that the list still reports exactly
    // one redaction per (blob, path) — the storage layer doesn't
    // duplicate.
    let _ = (first, second);
    let list_raw = heddle(&["--output", "json", "redact", "list"], Some(temp.path())).unwrap();
    let list: Value = serde_json::from_str(&list_raw).unwrap();
    let entries = list["redactions"].as_array().unwrap();
    let same_path: Vec<&Value> = entries
        .iter()
        .filter(|r| r["path"].as_str() == Some("config/secrets.toml"))
        .collect();
    // Multiple oplog applies are OK; the unique storage signature is
    // (blob, path) and we don't want the list to balloon on retries.
    // Today the storage layer can store either 1 (canonical) or 2
    // (when timestamps differ) entries — pin: at most a handful, NOT
    // a duplication-on-every-retry pattern.
    assert!(
        same_path.len() <= 2,
        "repeated identical applies must NOT fan out into N entries; got {}",
        same_path.len()
    );
}

#[test]
fn purge_without_prior_redact_is_refused() {
    let (temp, state) = setup_repo_with_secret();
    let err = heddle(
        &[
            "redact",
            "purge",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--force",
        ],
        Some(temp.path()),
    )
    .expect_err("purge without prior redact must refuse");
    assert!(
        err.contains("no redaction"),
        "refusal must name the missing-redaction precondition: {err}"
    );
}

// ---------------------------------------------------------------------
// Cross-replica propagation tests
//
// The redact + purge surface is local-only without wire propagation —
// pulls on a peer replica would re-expose the secret. These tests pin
// the propagation contract via `heddle clone` (which goes through
// `LocalSync`):
//
//   - Signed redactions: propagate, renders stub on B's worktree.
//   - Signed purge: propagates, drops bytes on B.
//   - Unsigned redactions: refused on the wire; local-only on A.
//   - Tampered signatures: refused on the wire.
//
// All four use `heddle clone <path-A> <path-B>` to exercise the
// `LocalSync::propagate_redactions_for_blob` hook added for cross-
// replica scope.
// ---------------------------------------------------------------------

fn signed_redact_on_repo_a(
    temp: &TempDir,
    state: &str,
    pem_path: &std::path::Path,
) -> serde_json::Value {
    let raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
            "--sign-with",
            pem_path.to_str().unwrap(),
        ],
        Some(temp.path()),
    )
    .expect("redact apply --sign-with should succeed on A");
    serde_json::from_str(&raw).expect("apply output JSON")
}

#[test]
fn redact_apply_signed_propagates_to_cloned_replica() {
    use crypto::Ed25519Signer;
    let (a, state) = setup_repo_with_secret();
    let signer = Ed25519Signer::generate().unwrap();
    let pem = signer.to_pem().unwrap();
    let pem_path = a.path().join("ed25519.pem");
    write_test_private_key(&pem_path, &pem);
    let apply = signed_redact_on_repo_a(&a, &state, &pem_path);
    let redaction_id = apply["redaction_id"].as_str().unwrap().to_string();

    // Set up B: init empty repo, trust A's signing key, then pull.
    let b_dir = TempDir::new().unwrap();
    let b_path = b_dir.path().join("replica-b");
    fs::create_dir_all(&b_path).unwrap();
    heddle(&["init"], Some(&b_path)).expect("init B");
    trust_redact_public_key(&b_path, &hex::encode(signer.public_key()));
    heddle(
        &["remote", "add", "origin", a.path().to_str().unwrap()],
        Some(&b_path),
    )
    .expect("remote add origin");
    heddle(&["pull", "origin"], Some(&b_path)).expect("pull propagates signed redaction to B");

    // B's redact list must include the propagated redaction. The
    // worktree-stub contract is tested separately by the local
    // materialize tests; here we pin the propagation contract: A's
    // redaction record exists in B's local sidecar after pull.
    let list_raw = heddle(&["--output", "json", "redact", "list"], Some(&b_path)).unwrap();
    let list: Value = serde_json::from_str(&list_raw).unwrap();
    let rows = list["redactions"].as_array().expect("redactions array");
    assert_eq!(
        rows.len(),
        1,
        "B must see exactly one propagated redaction: {list_raw}"
    );

    // The propagated redaction must still verify on B — signature is
    // carried byte-identical across the wire.
    let show_raw = heddle(
        &["--output", "json", "redact", "show", &redaction_id],
        Some(&b_path),
    )
    .unwrap();
    let show: Value = serde_json::from_str(&show_raw).unwrap();
    assert_eq!(
        show["signature_status"].as_str().unwrap(),
        "verified",
        "B must verify the signature on the propagated redaction"
    );
}

#[test]
fn redact_apply_unsigned_is_refused_at_clone_boundary() {
    // Wire policy: unsigned redactions do not propagate. The local
    // redaction stays on A; B's clone refuses with a clear message
    // because LocalSync routes through accept_wire_redactions which
    // rejects unsigned records.
    let (a, state) = setup_repo_with_secret();
    let _ = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leaked credential",
        ],
        Some(a.path()),
    )
    .expect("unsigned local redact on A succeeds");

    let b_dir = TempDir::new().unwrap();
    let b_path = b_dir.path().join("replica-b");
    let err = heddle(
        &[
            "clone",
            a.path().to_str().unwrap(),
            b_path.to_str().unwrap(),
        ],
        Some(b_dir.path()),
    )
    .expect_err("clone must refuse unsigned redaction propagation");
    assert!(
        err.contains("no signature") || err.contains("Unsigned") || err.contains("unsigned"),
        "clone rejection must explain the unsigned cause: {err}"
    );
}

#[test]
fn ordinary_local_sync_does_not_propagate_owner_gated_purge() {
    use crypto::Ed25519Signer;
    let (a, state) = setup_repo_with_secret();
    let signer = Ed25519Signer::generate().unwrap();
    let pem = signer.to_pem().unwrap();
    let pem_path = a.path().join("ed25519.pem");
    write_test_private_key(&pem_path, &pem);
    let _ = signed_redact_on_repo_a(&a, &state, &pem_path);
    heddle(
        &[
            "redact",
            "purge",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--force",
        ],
        Some(a.path()),
    )
    .expect("purge on A succeeds");

    // Local sync has no owner-capability carrier. It may propagate the
    // ordinary redaction but must not propagate destructive purge evidence.
    let b_dir = TempDir::new().unwrap();
    let b_path = b_dir.path().join("replica-b");
    fs::create_dir_all(&b_path).unwrap();
    heddle(&["init"], Some(&b_path)).expect("init B");
    trust_redact_public_key(&b_path, &hex::encode(signer.public_key()));
    heddle(
        &["remote", "add", "origin", a.path().to_str().unwrap()],
        Some(&b_path),
    )
    .expect("remote add origin");
    heddle(&["pull", "origin"], Some(&b_path))
        .expect("pull propagates signed redaction without purge evidence");

    // B must not record the purge.
    let purge_list_raw = heddle(
        &["--output", "json", "redact", "purge", "list"],
        Some(&b_path),
    )
    .unwrap();
    let purge_list: Value = serde_json::from_str(&purge_list_raw).unwrap();
    let purges = purge_list["purges"].as_array().expect("purges array");
    assert_eq!(
        purges.len(),
        0,
        "ordinary sync must not grant or propagate purge: {purge_list_raw}"
    );
}

#[test]
fn tampered_redaction_is_refused_at_pull_boundary() {
    use crypto::Ed25519Signer;
    use objects::object::RedactionsBlob;

    let (a, state) = setup_repo_with_secret();
    let signer = Ed25519Signer::generate().unwrap();
    let pem = signer.to_pem().unwrap();
    let pem_path = a.path().join("ed25519.pem");
    write_test_private_key(&pem_path, &pem);
    let _ = signed_redact_on_repo_a(&a, &state, &pem_path);

    // Tamper with A's stored redaction sidecar by mutating the reason
    // *after* signing — same blob hash key, but the canonical payload
    // no longer matches the signature.
    let redaction_dir = a.path().join(".heddle/redactions");
    let entries: Vec<_> = fs::read_dir(&redaction_dir)
        .expect("redactions dir exists on A")
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("bin"))
        .collect();
    assert_eq!(entries.len(), 1, "exactly one redaction expected on A");
    let path = entries[0].path();
    let bytes = fs::read(&path).unwrap();
    let mut blob = RedactionsBlob::decode(&bytes).expect("decode A's redactions blob");
    blob.redactions[0].reason = "post-sign tampered reason".to_string();
    fs::write(&path, blob.encode().unwrap()).unwrap();
    // The above forfeits A's own materialize-side stub correctness;
    // the local invariant break is the point of the test.

    // B trusts the signing key, so the trust gate passes — the
    // rejection comes from signature verification failing on the
    // tampered canonical payload (Tampered, not UntrustedKey).
    let b_dir = TempDir::new().unwrap();
    let b_path = b_dir.path().join("replica-b");
    fs::create_dir_all(&b_path).unwrap();
    heddle(&["init"], Some(&b_path)).expect("init B");
    trust_redact_public_key(&b_path, &hex::encode(signer.public_key()));
    heddle(
        &["remote", "add", "origin", a.path().to_str().unwrap()],
        Some(&b_path),
    )
    .expect("remote add origin");
    let err = heddle(&["pull", "origin"], Some(&b_path))
        .expect_err("pull must refuse a tampered redaction");
    assert!(
        err.contains("failed to verify") || err.contains("Tampered") || err.contains("tampered"),
        "pull rejection must explain the tamper cause: {err}"
    );
}

// ---------------------------------------------------------------------
// Ignore-hint tests
//
// After a redact/purge, the working tree file is unchanged — the next
// `heddle capture` would re-snapshot the leaked bytes. The CLI emits a
// hint pointing at the right ignore file to append the path to. Native
// Heddle prefers `.heddleignore`; Git-overlay prefers `.gitignore`.
// ---------------------------------------------------------------------

fn redact_apply_json(temp: &TempDir, state: &str) -> Value {
    let raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leak",
        ],
        Some(temp.path()),
    )
    .expect("redact apply");
    serde_json::from_str(&raw).expect("redact apply JSON")
}

#[test]
fn redact_apply_emits_ignore_hint_when_neither_file_covers_path() {
    // Fresh native repos do not auto-create `.heddleignore`. The hint must
    // surface, pointing at `.heddleignore` with `already_exists: false`.
    let (temp, state) = setup_repo_with_secret();
    let apply = redact_apply_json(&temp, &state);
    let hint = apply
        .get("ignore_hint")
        .expect("ignore_hint should be present when path is uncovered");
    assert_eq!(hint["ignore_file"].as_str().unwrap(), ".heddleignore");
    assert!(
        !hint["already_exists"].as_bool().unwrap(),
        "init should not install a default .heddleignore"
    );
    assert_eq!(
        hint["suggested_pattern"].as_str().unwrap(),
        "config/secrets.toml"
    );
    assert!(
        hint["message"]
            .as_str()
            .unwrap()
            .contains("create .heddleignore")
    );
}

#[test]
fn redact_apply_emits_no_hint_when_heddleignore_literal_matches() {
    let (temp, state) = setup_repo_with_secret();
    // Direct literal path match in `.heddleignore`.
    fs::write(temp.path().join(".heddleignore"), "config/secrets.toml\n").unwrap();
    let apply = redact_apply_json(&temp, &state);
    assert!(
        apply.get("ignore_hint").is_none() || apply["ignore_hint"].is_null(),
        "literal-path coverage in .heddleignore must suppress the hint: {apply:?}"
    );
}

#[test]
fn redact_apply_emits_no_hint_when_heddleignore_glob_matches() {
    // Glob coverage (`config/*.toml`) in `.heddleignore` — the matcher
    // uses gitignore-spec globs, not literal substring, so a broad
    // rule that already covers the leaked path suppresses the hint.
    let (temp, state) = setup_repo_with_secret();
    fs::write(temp.path().join(".heddleignore"), "config/*.toml\n").unwrap();
    let apply = redact_apply_json(&temp, &state);
    assert!(
        apply.get("ignore_hint").is_none() || apply["ignore_hint"].is_null(),
        "glob coverage in .heddleignore must suppress the hint: {apply:?}"
    );
}

#[test]
fn redact_apply_emits_no_hint_when_gitignore_covers_the_path_in_native_mode() {
    // Native capture reads the root `.gitignore`, so an already-covered
    // secret must not produce redundant `.heddleignore` guidance.
    let (temp, state) = setup_repo_with_secret();
    fs::write(temp.path().join(".gitignore"), "config/*.toml\n").unwrap();
    let apply = redact_apply_json(&temp, &state);
    assert!(
        apply.get("ignore_hint").is_none() || apply["ignore_hint"].is_null(),
        "root .gitignore coverage in native mode must suppress the hint: {apply:?}"
    );
}

#[test]
fn redact_apply_git_overlay_prefers_gitignore_hint() {
    let (temp, state) = setup_git_overlay_repo_with_secret();
    let apply = redact_apply_json(&temp, &state);
    let hint = apply
        .get("ignore_hint")
        .expect("ignore_hint should be present when path is uncovered");
    assert_eq!(hint["ignore_file"].as_str().unwrap(), ".gitignore");
    assert!(
        !hint["already_exists"].as_bool().unwrap(),
        "fixture does not create a .gitignore"
    );
    assert!(
        hint["message"]
            .as_str()
            .unwrap()
            .contains("create .gitignore"),
        "Git-overlay redaction should point at Git's shared ignore file: {hint}"
    );
}

#[test]
fn redact_apply_emits_no_hint_when_repo_config_ignore_covers_path() {
    // `worktree.ignore` in `.heddle/config.toml` is part of heddle's
    // effective ignore set (see `Repository::ignore_patterns`). A
    // pattern in repo config must suppress the hint even with no
    // `.heddleignore` file on disk. Splice the additional pattern
    // into the existing `[worktree] ignore = [...]` array instead of
    // appending a duplicate section header (which `heddle init`
    // already writes).
    let (temp, state) = setup_repo_with_secret();
    let config_path = temp.path().join(".heddle/config.toml");
    let existing = fs::read_to_string(&config_path).expect("read default config");
    let patched = existing.replace("ignore = [", "ignore = [\n    \"config/*.toml\",");
    assert_ne!(
        existing, patched,
        "test fixture expected `ignore = [` in default config"
    );
    fs::write(&config_path, patched).unwrap();
    let apply = redact_apply_json(&temp, &state);
    assert!(
        apply.get("ignore_hint").is_none() || apply["ignore_hint"].is_null(),
        "repo-config worktree.ignore coverage must suppress the hint: {apply:?}"
    );
}

#[test]
fn purge_apply_also_emits_ignore_hint() {
    // `heddle redact purge apply` carries the same hint as redact — the
    // working-tree leak is the same problem regardless of which
    // verb you reach for.
    let (temp, state) = setup_repo_with_secret();
    // Redact first (purge refuses without a prior redaction).
    heddle(
        &[
            "redact",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--reason",
            "leak",
        ],
        Some(temp.path()),
    )
    .unwrap();
    let raw = heddle(
        &[
            "--output",
            "json",
            "redact",
            "purge",
            "apply",
            &state,
            "--path",
            "config/secrets.toml",
            "--force",
        ],
        Some(temp.path()),
    )
    .expect("purge apply");
    let purge: Value = serde_json::from_str(&raw).unwrap();
    let hint = purge
        .get("ignore_hint")
        .expect("purge output must include ignore_hint");
    assert_eq!(hint["ignore_file"].as_str().unwrap(), ".heddleignore");
    assert!(
        !hint["already_exists"].as_bool().unwrap(),
        "init should not install a default .heddleignore"
    );
}

#[test]
fn redact_after_peer_pull_still_propagates_on_resync() {
    // Scenario the codex review flagged: peer B clones A *first*,
    // then A declares a redaction. A second clone-from-A would find
    // every state/tree/blob already present locally and previously
    // would short-circuit before propagating the sidecar. The
    // post-fix behavior: redactions ferry through even when the
    // object graph hasn't changed.
    use crypto::Ed25519Signer;

    let (a, state) = setup_repo_with_secret();

    // Peer B clones BEFORE the redaction is declared on A.
    let b_dir = TempDir::new().unwrap();
    let b_path = b_dir.path().join("replica-b");
    heddle(
        &[
            "clone",
            a.path().to_str().unwrap(),
            b_path.to_str().unwrap(),
        ],
        Some(b_dir.path()),
    )
    .expect("initial clone A → B");
    let list_before: Value = serde_json::from_str(
        &heddle(&["--output", "json", "redact", "list"], Some(&b_path)).unwrap(),
    )
    .unwrap();
    assert_eq!(
        list_before["redactions"].as_array().unwrap().len(),
        0,
        "B has no redactions yet (declared on A only after clone)"
    );

    // Now A declares + signs the redaction.
    let signer = Ed25519Signer::generate().unwrap();
    let pem = signer.to_pem().unwrap();
    let pem_path = a.path().join("ed25519.pem");
    write_test_private_key(&pem_path, &pem);
    let _ = signed_redact_on_repo_a(&a, &state, &pem_path);

    // Re-sync ferries the ordinary sidecar even though every state/tree/blob
    // is already present on B. B must trust A's signing key first.
    trust_redact_public_key(&b_path, &hex::encode(signer.public_key()));
    heddle(
        &["remote", "add", "origin", a.path().to_str().unwrap()],
        Some(&b_path),
    )
    .expect("remote add origin");
    let pull =
        heddle(&["pull", "origin"], Some(&b_path)).expect("pull A → B after redaction declared");
    assert!(
        pull.contains("already up to date"),
        "no-op resync should explain that source state is current: {pull}"
    );

    let list_after: Value = serde_json::from_str(
        &heddle(&["--output", "json", "redact", "list"], Some(&b_path)).unwrap(),
    )
    .unwrap();
    assert_eq!(
        list_after["redactions"].as_array().unwrap().len(),
        1,
        "B must see the post-clone redaction after pull: {list_after:?}"
    );
}

#[test]
fn untrusted_signed_redaction_is_refused_at_pull_boundary() {
    use crypto::Ed25519Signer;

    // Without a trust check the receiver accepts any self-signed
    // redaction. B is initialized with an empty `[redact] trusted_keys`
    // list. The pull must refuse with `UntrustedKey`.
    let (a, state) = setup_repo_with_secret();
    let attacker = Ed25519Signer::generate().unwrap();
    let pem = attacker.to_pem().unwrap();
    let pem_path = a.path().join("attacker.pem");
    write_test_private_key(&pem_path, &pem);
    let _ = signed_redact_on_repo_a(&a, &state, &pem_path);

    let b_dir = TempDir::new().unwrap();
    let b_path = b_dir.path().join("replica-b");
    fs::create_dir_all(&b_path).unwrap();
    heddle(&["init"], Some(&b_path)).expect("init B");
    heddle(
        &["remote", "add", "origin", a.path().to_str().unwrap()],
        Some(&b_path),
    )
    .expect("remote add origin");
    let err = heddle(&["pull", "origin"], Some(&b_path))
        .expect_err("pull must refuse untrusted signed redaction");
    assert!(
        err.contains("untrusted operator key"),
        "pull rejection must explain the untrusted-key cause: {err}"
    );
}

#[test]
fn redact_empty_path_uses_typed_advice_json() {
    let (temp, state) = setup_repo_with_secret();
    let output = heddle_output(
        &[
            "--output",
            "json",
            "redact",
            "apply",
            &state,
            "--path",
            "",
            "--reason",
            "empty path smoke",
        ],
        Some(temp.path()),
    )
    .expect("invoke redact apply");
    assert!(!output.status.success(), "empty path must refuse");
    assert!(
        output.stdout.is_empty(),
        "JSON-mode refusal must not write stdout: {}",
        String::from_utf8_lossy(&output.stdout)
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    let envelope: Value =
        serde_json::from_str(&stderr).expect("stderr should be JSON error envelope");
    assert_eq!(envelope["kind"], "redact_path_empty");
    assert!(
        envelope["hint"]
            .as_str()
            .is_some_and(|hint| hint.contains("--path <path>")),
        "typed advice should name the recovery path: {stderr}"
    );
}