khive-pack-git 0.5.0

Git-lifecycle pack — commit/issue/pull_request provenance notes over the notes substrate (ADR-088)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
//! Handler-level tests for `git.commit` / `git.branch` / `git.push`
//! (ADR-108, amended by the ADR-108 Amendment), driven through the real
//! `pub(crate)` handler surface against a scratch git repo initialized
//! fresh in a `tempfile::tempdir()` for every test. Never touches
//! `~/.khive` or any production store: `KhiveRuntime` is always an
//! in-memory instance, and the git repo under test is always a throwaway
//! tempdir, never this workspace.
//!
//! The `[git_write]` policy is threaded in directly via
//! `RuntimeConfig::git_write` (see [`pack_and_token_with_policy`]) rather
//! than through `KHIVE_CONFIG`/file discovery: the write handlers read an
//! already-resolved policy from `RuntimeConfig`, they no longer re-run
//! config discovery themselves (ADR-108 review r2 finding -- a handler-level
//! reload ignored an explicit `--config` path not also exported as
//! `KHIVE_CONFIG`). This also means these tests carry zero ambient-env risk
//! for policy resolution.
//!
//! Every test still holds `cache::ENV_MUTEX` for its full body:
//! `crate::cache`'s and `crate::recovery_tests`' tests shadow the
//! process-global `PATH` to inject fake `git` binaries, which would
//! otherwise race against every `Command::new("git")` spawn here (both this
//! module's own `git_command` helper and the handler code under test
//! resolve `git` via `PATH` at spawn time).

use std::ffi::{OsStr, OsString};
use std::path::Path;
use std::process::Command;

use serde_json::{json, Value};

use khive_runtime::engine_config::{GitWriteEntryConfig, GitWriteSectionConfig};
use khive_runtime::{KhiveRuntime, Namespace, NamespaceToken, RuntimeConfig};
use khive_types::EventOutcome;

use crate::GitPack;

/// Restores one process-global environment variable when dropped. Callers
/// must hold [`crate::cache::ENV_MUTEX`] for the guard's full lifetime.
struct EnvVarGuard {
    key: &'static str,
    previous: Option<OsString>,
}

impl EnvVarGuard {
    fn set(key: &'static str, value: impl AsRef<OsStr>) -> Self {
        let previous = std::env::var_os(key);
        std::env::set_var(key, value);
        Self { key, previous }
    }
}

impl Drop for EnvVarGuard {
    fn drop(&mut self) {
        match &self.previous {
            Some(value) => std::env::set_var(self.key, value),
            None => std::env::remove_var(self.key),
        }
    }
}

/// Builds a `[git_write]` section allowlisting `repo` for `branches`.
fn policy(repo: &Path, branches: &[&str]) -> GitWriteSectionConfig {
    GitWriteSectionConfig {
        allowed: vec![GitWriteEntryConfig {
            repo: repo.display().to_string(),
            branches: branches.iter().map(|b| b.to_string()).collect(),
        }],
    }
}

/// Constructs an in-memory `GitPack` carrying the given `[git_write]`
/// section directly in `RuntimeConfig` -- no `KHIVE_CONFIG` env var, no
/// file I/O, no discovery. An empty `GitWriteSectionConfig::default()`
/// reproduces the fail-closed "not configured" state.
async fn pack_and_token_with_policy(git_write: GitWriteSectionConfig) -> (GitPack, NamespaceToken) {
    let config = RuntimeConfig {
        db_path: None,
        packs: vec!["kg".to_string()],
        brain_profile: None,
        actor_id: None,
        git_write,
        ..RuntimeConfig::no_embeddings()
    };
    let rt = KhiveRuntime::new(config).expect("in-memory runtime");
    let token = rt.authorize(Namespace::local()).expect("authorize");
    (GitPack::new(rt), token)
}

async fn audit_event(
    pack: &GitPack,
    token: &NamespaceToken,
    verb: &str,
) -> khive_storage::event::Event {
    let events_store = pack.runtime().events(token).expect("events store");
    let page = events_store
        .query_events(
            khive_storage::event::EventFilter {
                verbs: vec![verb.to_string()],
                ..Default::default()
            },
            khive_storage::types::PageRequest {
                offset: 0,
                limit: 10,
            },
        )
        .await
        .expect("query events");
    assert_eq!(
        page.items.len(),
        1,
        "exactly one supplementary {verb} audit event must be emitted"
    );
    page.items.into_iter().next().expect("length checked above")
}

/// Builds a `git` invocation hardened against ambient host state: a global
/// `core.hooksPath`, `init.templateDir`, or system/global config on the
/// machine running the tests must never be able to run a hook or inject
/// config into a scratch repo under test. Mirrors `crates/khive-pack-git/
/// src/cache.rs`'s hardened invocations, applied to every git call this test
/// module makes (not just the `run` helper).
fn git_command(dir: &Path) -> Command {
    let mut cmd = Command::new("git");
    cmd.arg("-c")
        .arg(format!(
            "core.hooksPath={}",
            dir.join(".khive-test-no-hooks").display()
        ))
        .arg("-C")
        .arg(dir)
        .env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_SYSTEM", "/dev/null")
        .env("GIT_TEMPLATE_DIR", "")
        .env("GIT_TERMINAL_PROMPT", "0");
    cmd
}

fn run(dir: &Path, args: &[&str]) {
    let out = git_command(dir).args(args).output().expect("spawn git");
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// Initializes a throwaway repo with one commit on `main`, a configured
/// identity, and a bare "remote" (also a tempdir) wired as `origin` so
/// `git.push` has somewhere real to push to. Returns `(repo_tempdir,
/// remote_tempdir)` — both must stay alive for the caller's test body.
fn init_repo_with_remote() -> (tempfile::TempDir, tempfile::TempDir) {
    let remote_dir = tempfile::tempdir().expect("remote tempdir");
    run(remote_dir.path(), &["init", "-q", "--bare", "-b", "main"]);

    let repo_dir = tempfile::tempdir().expect("repo tempdir");
    run(repo_dir.path(), &["init", "-q", "-b", "main"]);
    run(
        repo_dir.path(),
        &["config", "user.email", "test@example.com"],
    );
    run(repo_dir.path(), &["config", "user.name", "Test User"]);
    std::fs::write(repo_dir.path().join("a.txt"), b"hello").unwrap();
    run(repo_dir.path(), &["add", "a.txt"]);
    run(repo_dir.path(), &["commit", "-q", "-m", "initial"]);
    run(
        repo_dir.path(),
        &[
            "remote",
            "add",
            "origin",
            remote_dir.path().to_str().unwrap(),
        ],
    );
    run(repo_dir.path(), &["push", "-q", "origin", "main"]);

    (repo_dir, remote_dir)
}

// -- git.commit ---------------------------------------------------------------

#[tokio::test]
async fn commit_with_no_paths_commits_all_tracked_changes() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();

    let result = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "update a.txt" }),
        )
        .await
        .expect("commit succeeds");

    let sha = result
        .get("sha")
        .and_then(|v| v.as_str())
        .expect("sha present");
    assert_eq!(sha.len(), 40, "sha must be a full 40-char hex commit id");

    let log = git_command(repo.path())
        .args(["log", "-1", "--pretty=%s"])
        .output()
        .expect("git log");
    assert_eq!(String::from_utf8_lossy(&log.stdout).trim(), "update a.txt");
}

/// Regression for review round 6: the handler command used by this test
/// suite must not inherit a developer's global/system Git configuration.
/// Enabling commit signing with a nonexistent signer makes that ambient
/// configuration deterministically hostile to `git commit`.
#[tokio::test]
async fn commit_ignores_hostile_ambient_global_config_in_tests() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;
    let config_dir = tempfile::tempdir().expect("global config tempdir");
    let global_config = config_dir.path().join("gitconfig");
    std::fs::write(
        &global_config,
        format!(
            "[commit]\n\tgpgSign = true\n[gpg]\n\tprogram = {}\n",
            config_dir.path().join("missing-gpg").display()
        ),
    )
    .expect("write hostile global config");
    let _global_config = EnvVarGuard::set("GIT_CONFIG_GLOBAL", &global_config);
    let _system_config = EnvVarGuard::set("GIT_CONFIG_SYSTEM", "/dev/null");

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();

    pack.handle_commit(
        &token,
        json!({ "repo": repo.path().to_str().unwrap(), "message": "update a.txt" }),
    )
    .await
    .expect("handler test ignores hostile ambient git config");
}

#[tokio::test]
async fn commit_with_paths_scopes_to_those_paths() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    std::fs::write(repo.path().join("a.txt"), b"changed-a").unwrap();
    std::fs::write(repo.path().join("b.txt"), b"new-b").unwrap();

    let result = pack
        .handle_commit(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "message": "add b only",
                "paths": ["b.txt"],
            }),
        )
        .await
        .expect("commit succeeds");
    assert!(result.get("sha").is_some());

    // a.txt was modified but not in `paths` -- must still show as dirty.
    let status = git_command(repo.path())
        .args(["status", "--porcelain"])
        .output()
        .expect("git status");
    let status_str = String::from_utf8_lossy(&status.stdout);
    assert!(
        status_str.contains("a.txt"),
        "a.txt must remain uncommitted/dirty: {status_str}"
    );
    assert!(
        !status_str.contains("b.txt"),
        "b.txt must be committed and clean: {status_str}"
    );
}

#[tokio::test]
async fn commit_literalizes_pathspec_magic_in_caller_path() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    std::fs::write(repo.path().join(":(top)"), b"literal").unwrap();
    std::fs::write(
        repo.path().join("unrelated.txt"),
        b"must remain uncommitted",
    )
    .unwrap();

    pack.handle_commit(
        &token,
        json!({
            "repo": repo.path().to_str().unwrap(),
            "message": "commit literal magic name",
            "paths": [":(top)"],
        }),
    )
    .await
    .expect("caller pathspec magic is treated as a literal filename");

    let status = git_command(repo.path())
        .args(["status", "--porcelain"])
        .output()
        .expect("git status");
    let status = String::from_utf8_lossy(&status.stdout);
    assert!(status.contains("unrelated.txt"), "{status}");
    assert!(!status.contains(":(top)"), "{status}");
}

#[tokio::test]
async fn commit_accepts_special_and_unicode_literal_filename() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;
    let path = "docs/[draft]*?café.md";
    std::fs::create_dir_all(repo.path().join("docs")).unwrap();
    std::fs::write(repo.path().join(path), b"literal").unwrap();

    pack.handle_commit(
        &token,
        json!({
            "repo": repo.path().to_str().unwrap(),
            "message": "commit special literal name",
            "paths": [path],
        }),
    )
    .await
    .expect("special and unicode filename commits literally");

    let tree = git_command(repo.path())
        .args([
            "-c",
            "core.quotepath=false",
            "ls-tree",
            "-r",
            "--name-only",
            "HEAD",
        ])
        .output()
        .expect("git ls-tree");
    assert!(String::from_utf8_lossy(&tree.stdout).contains(path));
}

#[tokio::test]
async fn commit_rejects_empty_message() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("message"), "{err}");
}

#[tokio::test]
async fn commit_treats_flag_shaped_path_as_literal() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;
    std::fs::write(repo.path().join("--upload-pack=evil"), b"literal").unwrap();

    pack.handle_commit(
        &token,
        json!({
            "repo": repo.path().to_str().unwrap(),
            "message": "msg",
            "paths": ["--upload-pack=evil"],
        }),
    )
    .await
    .expect("flag-shaped filename is a literal path after --");
}

#[tokio::test]
async fn commit_invalid_path_emits_deny_audit() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    pack.handle_commit(
        &token,
        json!({
            "repo": repo.path().to_str().unwrap(),
            "message": "invalid path",
            "paths": ["../outside"],
        }),
    )
    .await
    .unwrap_err();

    let audit = audit_event(&pack, &token, "git.commit").await;
    assert_eq!(audit.outcome, EventOutcome::Denied);
    assert_eq!(audit.payload["decision"], "deny");
    assert_eq!(audit.payload["branch"], "main");
}

#[tokio::test]
async fn commit_rejects_non_repo_path() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let dir = tempfile::tempdir().expect("tempdir");
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_commit(
            &token,
            json!({ "repo": dir.path().to_str().unwrap(), "message": "msg" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains(".git"), "{err}");
}

#[tokio::test]
async fn commit_rejects_non_string_author_without_committing() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;
    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();
    let head_before = git_command(repo.path())
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("git rev-parse before malformed commit")
        .stdout;

    let err = pack
        .handle_commit(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "message": "must not commit",
                "author": 42,
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("author must be a string"), "{err}");

    let head_after = git_command(repo.path())
        .args(["rev-parse", "HEAD"])
        .output()
        .expect("git rev-parse after malformed commit")
        .stdout;
    assert_eq!(head_after, head_before, "malformed author must not commit");
    let audit = audit_event(&pack, &token, "git.commit").await;
    assert_eq!(audit.outcome, EventOutcome::Denied);
}

#[tokio::test]
async fn commit_denied_when_no_policy_configured() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();

    let err = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "update a.txt" }),
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("git-write policy is configured"),
        "{err}"
    );
}

#[tokio::test]
async fn commit_denied_for_non_allowlisted_repo() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (other_repo, _other_remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(other_repo.path(), &["main"])).await;

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();

    let err = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "update a.txt" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("allowlist"), "{err}");
}

#[tokio::test]
async fn commit_denied_for_branch_outside_patterns() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["release-*"])).await;

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();

    let err = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "update a.txt" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("branch"), "{err}");
}

/// Regression for the H3 review finding: `run_git` must disable
/// repo-configured hooks (`core.hooksPath=/dev/null`) so a hook script
/// committed into an allowlisted repo cannot execute as a side effect of a
/// khive-mediated write, in the daemon's own credential context.
#[tokio::test]
async fn commit_does_not_execute_repo_configured_hooks() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    let sentinel = repo.path().join("hook-ran.sentinel");
    let hooks_dir = repo.path().join(".git/hooks");
    std::fs::create_dir_all(&hooks_dir).unwrap();
    let hook_path = hooks_dir.join("pre-commit");
    std::fs::write(
        &hook_path,
        format!("#!/bin/sh\ntouch {:?}\n", sentinel.display().to_string()),
    )
    .unwrap();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&hook_path, std::fs::Permissions::from_mode(0o755)).unwrap();
    }

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();

    pack.handle_commit(
        &token,
        json!({ "repo": repo.path().to_str().unwrap(), "message": "update a.txt" }),
    )
    .await
    .expect("commit succeeds");

    assert!(
        !sentinel.exists(),
        "pre-commit hook must not have executed during a khive-mediated commit"
    );
}

// -- git.branch -----------------------------------------------------------

#[tokio::test]
async fn branch_creates_from_head_by_default() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["feat/*"])).await;

    let result = pack
        .handle_branch(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "name": "feat/x" }),
        )
        .await
        .expect("branch succeeds");
    assert_eq!(result.get("name").and_then(|v| v.as_str()), Some("feat/x"));

    let branches = git_command(repo.path())
        .args(["branch", "--list", "feat/x"])
        .output()
        .expect("git branch --list");
    assert!(String::from_utf8_lossy(&branches.stdout).contains("feat/x"));
}

#[tokio::test]
async fn branch_rejects_injection_shaped_name() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_branch(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "name": "--upload-pack=evil" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("start with"), "{err}");
}

#[tokio::test]
async fn branch_rejects_path_traversal_name() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_branch(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "name": "../../etc/passwd" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains(".."), "{err}");

    let audit = audit_event(&pack, &token, "git.branch").await;
    assert_eq!(audit.outcome, EventOutcome::Denied);
    assert_eq!(audit.payload["decision"], "deny");
    assert_eq!(audit.payload["branch"], "../../etc/passwd");
}

#[tokio::test]
async fn branch_rejects_non_string_from_without_creating_branch() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["feat/*"])).await;

    let err = pack
        .handle_branch(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "name": "feat/malformed-from",
                "from": 42,
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("from must be a string"), "{err}");

    let branches = git_command(repo.path())
        .args(["branch", "--list", "feat/malformed-from"])
        .output()
        .expect("git branch --list");
    assert!(
        branches.stdout.is_empty(),
        "malformed from must not create a branch"
    );
    let audit = audit_event(&pack, &token, "git.branch").await;
    assert_eq!(audit.outcome, EventOutcome::Denied);
}

#[tokio::test]
async fn branch_denied_when_no_policy_configured() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_branch(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "name": "feat/x" }),
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("git-write policy is configured"),
        "{err}"
    );
}

// -- git.push -----------------------------------------------------------

#[tokio::test]
async fn push_sends_branch_to_remote() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["feat/*"])).await;

    run(repo.path(), &["checkout", "-q", "-b", "feat/pushme"]);
    std::fs::write(repo.path().join("c.txt"), b"c").unwrap();
    run(repo.path(), &["add", "c.txt"]);
    run(repo.path(), &["commit", "-q", "-m", "add c"]);

    let result = pack
        .handle_push(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "branch": "feat/pushme" }),
        )
        .await
        .expect("push succeeds");
    assert_eq!(
        result.get("remote").and_then(|v| v.as_str()),
        Some("origin")
    );

    let branches = git_command(remote.path())
        .args(["branch", "--list", "feat/pushme"])
        .output()
        .expect("git branch --list on remote");
    assert!(String::from_utf8_lossy(&branches.stdout).contains("feat/pushme"));
}

#[tokio::test]
async fn push_rejects_explicit_force_true() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_push(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "branch": "main",
                "force": true,
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("force-push"), "{err}");

    let audit = audit_event(&pack, &token, "git.push").await;
    assert_eq!(audit.outcome, EventOutcome::Denied);
    assert_eq!(audit.payload["decision"], "deny");
    assert_eq!(audit.payload["branch"], "main");
}

#[tokio::test]
async fn push_allows_force_false() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    let result = pack
        .handle_push(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "branch": "main",
                "force": false,
            }),
        )
        .await;
    assert!(result.is_ok(), "{result:?}");
}

#[tokio::test]
async fn push_rejects_non_boolean_force() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_push(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "branch": "main",
                "force": "true",
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("boolean"), "{err}");
}

#[tokio::test]
async fn push_rejects_injection_shaped_remote() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_push(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "branch": "main",
                "remote": "--upload-pack=evil",
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("start with"), "{err}");
}

#[tokio::test]
async fn push_rejects_non_string_remote_without_pushing() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["feat/*"])).await;
    run(
        repo.path(),
        &["checkout", "-q", "-b", "feat/malformed-remote"],
    );
    std::fs::write(repo.path().join("new.txt"), b"new").unwrap();
    run(repo.path(), &["add", "new.txt"]);
    run(repo.path(), &["commit", "-q", "-m", "new commit"]);

    let err = pack
        .handle_push(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "branch": "feat/malformed-remote",
                "remote": 42,
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("remote must be a string"), "{err}");

    let branches = git_command(remote.path())
        .args(["branch", "--list", "feat/malformed-remote"])
        .output()
        .expect("git branch --list on remote");
    assert!(
        branches.stdout.is_empty(),
        "malformed remote must not push to origin"
    );
    let audit = audit_event(&pack, &token, "git.push").await;
    assert_eq!(audit.outcome, EventOutcome::Denied);
}

#[cfg(unix)]
#[tokio::test]
async fn invalid_repo_values_emit_denied_audits_without_invoking_git() {
    use std::os::unix::fs::PermissionsExt;

    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let fake_bin = tempfile::tempdir().expect("fake git bin");
    let sentinel = fake_bin.path().join("git-invoked");
    let fake_git = fake_bin.path().join("git");
    std::fs::write(
        &fake_git,
        format!("#!/bin/sh\ntouch \"{}\"\nexit 99\n", sentinel.display()),
    )
    .expect("write fake git");
    std::fs::set_permissions(&fake_git, std::fs::Permissions::from_mode(0o755))
        .expect("make fake git executable");
    let _path = EnvVarGuard::set("PATH", fake_bin.path());

    let cases: [(&str, Value, &str); 6] = [
        ("git.commit", json!({ "message": "msg" }), "required"),
        (
            "git.commit",
            json!({ "repo": 42, "message": "msg" }),
            "string",
        ),
        ("git.branch", json!({ "name": "feat/x" }), "required"),
        (
            "git.branch",
            json!({ "repo": 42, "name": "feat/x" }),
            "string",
        ),
        ("git.push", json!({ "branch": "main" }), "required"),
        (
            "git.push",
            json!({ "repo": 42, "branch": "main" }),
            "string",
        ),
    ];

    for (verb, params, expected_error) in cases {
        let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;
        let result = match verb {
            "git.commit" => pack.handle_commit(&token, params).await,
            "git.branch" => pack.handle_branch(&token, params).await,
            "git.push" => pack.handle_push(&token, params).await,
            _ => unreachable!("fixed test case verb"),
        };
        let err = result.unwrap_err();
        assert!(err.to_string().contains(expected_error), "{verb}: {err}");
        let audit = audit_event(&pack, &token, verb).await;
        assert_eq!(audit.outcome, EventOutcome::Denied, "{verb}");
        assert_eq!(audit.payload["decision"], "deny", "{verb}");
        assert_eq!(audit.payload["repo"], "<invalid-repo>", "{verb}");
        assert!(!sentinel.exists(), "{verb} must not invoke git");
    }
}

#[tokio::test]
async fn push_rejects_nonexistent_branch() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["*"])).await;

    let err = pack
        .handle_push(
            &token,
            json!({
                "repo": repo.path().to_str().unwrap(),
                "branch": "does-not-exist",
            }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("git"), "{err}");
}

#[tokio::test]
async fn push_denied_when_no_policy_configured() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(GitWriteSectionConfig::default()).await;

    let err = pack
        .handle_push(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "branch": "main" }),
        )
        .await
        .unwrap_err();
    assert!(
        err.to_string().contains("git-write policy is configured"),
        "{err}"
    );
}

#[tokio::test]
async fn push_denied_for_branch_outside_patterns() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["release-*"])).await;

    let err = pack
        .handle_push(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "branch": "main" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("branch"), "{err}");
}

// -- symlink TOCTOU (ADR-108 review r2 High finding) -----------------------

/// A symlink pointing at the allowlisted repo when `handle_commit` starts,
/// retargeted to a decoy (unallowlisted) repo mid-flight, must not let the
/// commit land in the decoy: the handler must operate only on the canonical
/// path resolved at check time, never re-traverse the caller-supplied
/// symlink for the actual git invocations.
/// `handle_commit` invoked through a symlink must resolve and report the
/// canonical repo path, and land the commit in the real repo -- not the
/// symlink's own (mutable) path string. This is the property that closes
/// the TOCTOU: every git invocation after the policy check uses the
/// canonical path returned by `enforce_write_policy`, so a later symlink
/// retarget (see `write_policy::tests::
/// canonical_path_returned_at_check_time_is_immune_to_later_retarget` for
/// the direct check-level regression) cannot redirect an in-flight write.
#[cfg(unix)]
#[tokio::test]
async fn commit_via_symlink_resolves_and_lands_in_canonical_repo() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (real_repo, _real_remote) = init_repo_with_remote();
    let parent = tempfile::tempdir().expect("parent tempdir");
    let link = parent.path().join("repo-link");
    std::os::unix::fs::symlink(real_repo.path(), &link).unwrap();

    let (pack, token) = pack_and_token_with_policy(policy(real_repo.path(), &["main"])).await;

    std::fs::write(real_repo.path().join("a.txt"), b"changed-via-link").unwrap();

    let result = pack
        .handle_commit(
            &token,
            json!({ "repo": link.to_str().unwrap(), "message": "via symlink" }),
        )
        .await
        .expect("commit succeeds against the canonical repo");

    let reported_repo = result.get("repo").and_then(|v| v.as_str()).unwrap();
    assert_eq!(
        Path::new(reported_repo),
        std::fs::canonicalize(real_repo.path()).unwrap(),
        "handler must report the canonical repo path, not the symlink path"
    );

    let real_log = git_command(real_repo.path())
        .args(["log", "-1", "--pretty=%s"])
        .output()
        .expect("git log on real repo");
    assert_eq!(
        String::from_utf8_lossy(&real_log.stdout).trim(),
        "via symlink",
        "the commit must have landed in the real repo"
    );
}

// -- audit completeness (ADR-108 review r2 High finding) -------------------

/// `handle_commit` discovers the checked-out branch internally -- the
/// resulting audit event must carry it, not `None` (the pre-fix bug).
#[tokio::test]
async fn commit_audit_captures_resolved_branch_and_sha() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();
    let result = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "audit check" }),
        )
        .await
        .expect("commit succeeds");
    let sha = result
        .get("sha")
        .and_then(|v| v.as_str())
        .unwrap()
        .to_string();

    let events_store = pack.runtime().events(&token).expect("events store");
    let page = events_store
        .query_events(
            khive_storage::event::EventFilter {
                verbs: vec!["git.commit".to_string()],
                ..Default::default()
            },
            khive_storage::types::PageRequest {
                offset: 0,
                limit: 10,
            },
        )
        .await
        .expect("query events");
    let audit = page.items.first().expect("git.commit audit event present");
    assert_eq!(
        audit.payload.get("branch").and_then(|v| v.as_str()),
        Some("main")
    );
    assert_eq!(
        audit.payload.get("decision").and_then(|v| v.as_str()),
        Some("allow")
    );
    assert_eq!(
        audit.payload.get("sha").and_then(|v| v.as_str()),
        Some(sha.as_str())
    );
}

/// A handler-allowlist denial must itself emit a `deny` decision audit
/// event, not leave the trail entirely to the dispatch-level Gate audit
/// (which records only its own Allow/Deny, paired with an errored outcome).
#[tokio::test]
async fn commit_denial_emits_deny_decision_audit() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["release-*"])).await;

    std::fs::write(repo.path().join("a.txt"), b"changed").unwrap();
    let err = pack
        .handle_commit(
            &token,
            json!({ "repo": repo.path().to_str().unwrap(), "message": "denied" }),
        )
        .await
        .unwrap_err();
    assert!(err.to_string().contains("branch"));

    let events_store = pack.runtime().events(&token).expect("events store");
    let page = events_store
        .query_events(
            khive_storage::event::EventFilter {
                verbs: vec!["git.commit".to_string()],
                ..Default::default()
            },
            khive_storage::types::PageRequest {
                offset: 0,
                limit: 10,
            },
        )
        .await
        .expect("query events");
    let audit = page
        .items
        .first()
        .expect("git.commit audit event present even on denial");
    assert_eq!(
        audit.payload.get("decision").and_then(|v| v.as_str()),
        Some("deny")
    );
    assert_eq!(
        audit.payload.get("branch").and_then(|v| v.as_str()),
        Some("main")
    );
}

#[tokio::test]
async fn detached_head_commit_failure_emits_error_audit() {
    let _env_guard = crate::cache::ENV_MUTEX.lock().await;
    let (repo, _remote) = init_repo_with_remote();
    let (pack, token) = pack_and_token_with_policy(policy(repo.path(), &["main"])).await;
    run(repo.path(), &["checkout", "-q", "--detach", "HEAD"]);
    std::fs::write(repo.path().join("a.txt"), b"detached change").unwrap();

    pack.handle_commit(
        &token,
        json!({ "repo": repo.path().to_str().unwrap(), "message": "detached" }),
    )
    .await
    .unwrap_err();

    let audit = audit_event(&pack, &token, "git.commit").await;
    assert_eq!(audit.outcome, EventOutcome::Error);
    assert_eq!(audit.payload["decision"], "deny");
    assert!(audit.payload.get("branch").is_none());
}