shepherd-cli 6.6.1

The canonical shepherd command-line interface over the per-project registry, run artifacts, and sprint pipeline.
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
use std::{
    fs,
    io::Write,
    path::{Path, PathBuf},
    process::{Command, Output, Stdio},
    time::{SystemTime, UNIX_EPOCH},
};

fn binary() -> &'static str {
    env!("CARGO_BIN_EXE_shepherd")
}

fn fixture_dir(label: &str) -> PathBuf {
    let nonce = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .expect("clock")
        .as_nanos();
    let root = std::env::temp_dir().join(format!(
        "shepherd-claude-hook-{label}-{}-{nonce:x}",
        std::process::id()
    ));
    fs::create_dir_all(&root).expect("create fixture directory");
    fs::canonicalize(root).expect("canonical fixture directory")
}

fn repository(label: &str) -> PathBuf {
    let root = fixture_dir(label);
    let status = Command::new("git")
        .args(["init", "--quiet"])
        .current_dir(&root)
        .status()
        .expect("initialize fixture repository");
    assert!(status.success());
    fs::create_dir_all(root.join(".shepherd/runs/v645/dispatch")).expect("create run namespace");
    fs::write(
        root.join(".shepherd/project.json"),
        br#"{"id":"018f47ce-72d7-7f64-9eb1-2f651d521c2a","scaffolded_at":1000}"#,
    )
    .expect("write project identity");
    fs::write(
        root.join(".shepherd/runs/v645/run.json"),
        br#"{"run":"v645","status":"executing"}"#,
    )
    .expect("write active run");
    let registry = shepherd_cli::shepherd::registry::Registry::open_migrated(
        root.join(".shepherd/shepherd.db"),
    )
    .expect("authoritative registry");
    registry
        .execute(
            "INSERT INTO projects (id, name, created_at, updated_at) VALUES (?1, ?2, ?3, ?3)",
            (
                "018f47ce-72d7-7f64-9eb1-2f651d521c2a",
                "Claude hook fixture",
                1_i64,
            ),
        )
        .expect("register project identity");
    root
}

/// Restore the pre-6.6.0 posture for one fixture.
///
/// `[guard] dispatch_custody` defaults to `bound`: a session that never opened
/// a sprint has no custody to enforce, so it is advised rather than refused.
/// The refusals below are the `always` posture, kept under test so the knob is
/// proven in BOTH directions and the old behavior stays available to a project
/// that wants it.
fn enforce_custody_always(root: &Path) {
    fs::write(
        root.join(".shepherd/shepherd.toml"),
        b"[guard]\ndispatch_custody = \"always\"\n",
    )
    .expect("write guard configuration");
}

/// The `permissionDecision` a hook response carries, or `None` when it advised.
fn decision(output: &serde_json::Value) -> Option<&str> {
    output["hookSpecificOutput"]["permissionDecision"].as_str()
}

/// The reason text of a denial, or the advisory context of an allow -- the two
/// carry the same sentence, which is why relaxing the decision loses nothing.
fn advice(output: &serde_json::Value) -> &str {
    output["hookSpecificOutput"]["permissionDecisionReason"]
        .as_str()
        .or_else(|| output["hookSpecificOutput"]["additionalContext"].as_str())
        .expect("a hook response says what it decided and why")
}

fn hook(root: &Path, input: serde_json::Value) -> Output {
    let mut child = Command::new(binary())
        .args(["hook", "--harness", "claude"])
        .current_dir(root)
        .env("SHEPHERD_HOME", root.join("isolated-home"))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn shepherd claude hook");
    child
        .stdin
        .take()
        .expect("hook stdin")
        .write_all(&serde_json::to_vec(&input).expect("encode hook input"))
        .expect("write hook input");
    child.wait_with_output().expect("wait for hook")
}

#[test]
fn exact_bind_root_uses_the_trusted_claude_session_and_selected_planted_run() {
    let root = repository("explicit-root-binding");
    fs::create_dir_all(root.join(".shepherd/runs/v657/dispatch")).expect("v657 dispatch namespace");
    fs::write(
        root.join(".shepherd/runs/v657/run.json"),
        br#"{"run":"v657","status":"planted"}"#,
    )
    .expect("v657 planted state");
    fs::create_dir_all(root.join(".shepherd/runs/v646")).expect("corrupt sibling namespace");
    fs::write(root.join(".shepherd/runs/v646/run.json"), b"{").expect("corrupt sibling document");

    let bound = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "trusted-claude-session",
            "tool_use_id": "bind-v657",
            "tool_name": "Bash",
            "tool_input": {
                "command": "shepherd dispatch bind-root --run v657 --mode planning --confirm"
            }
        }),
    );
    assert!(bound.status.success());
    let bound_output = if bound.stdout.is_empty() {
        serde_json::Value::Null
    } else {
        serde_json::from_slice(&bound.stdout).expect("bind hook output is JSON")
    };
    assert_ne!(
        bound_output["hookSpecificOutput"]["permissionDecision"], "deny",
        "the exact trusted bootstrap must be permitted: {bound_output}"
    );
    let binding: serde_json::Value = serde_json::from_slice(
        &fs::read(
            root.join(".shepherd/runs/v657/dispatch/.root-session.trusted-claude-session.json"),
        )
        .expect("trusted Claude root binding"),
    )
    .expect("root binding is JSON");
    assert_eq!(binding["run"], "v657");
    assert_eq!(binding["harness"], "claude");
    assert_eq!(binding["session_id"], "trusted-claude-session");
    // `planting`, not `planning`: the root SEEDS, the engineer plans. The
    // legacy spelling is still accepted as INPUT (the bootstrap command below
    // still sends it), but only the correct one is ever persisted.
    assert_eq!(binding["mode"], "planting");
    assert!(
        !root
            .join(".shepherd/runs/v645/dispatch/.root-session.trusted-claude-session.json")
            .exists(),
        "ambient v645 must not receive the explicit v657 binding"
    );

    let denied_execution = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "other-claude-session",
            "tool_use_id": "bind-v657-execution",
            "tool_name": "Bash",
            "tool_input": {
                "command": "shepherd dispatch bind-root --run v657 --mode execution --confirm"
            }
        }),
    );
    assert!(denied_execution.status.success());
    let denied_execution: serde_json::Value =
        serde_json::from_slice(&denied_execution.stdout).expect("mode mismatch denial is JSON");
    assert_eq!(
        denied_execution["hookSpecificOutput"]["permissionDecision"], "deny",
        "planted runs must not grant execution authority: {denied_execution}"
    );
    assert!(
        !root
            .join(".shepherd/runs/v657/dispatch/.root-session.other-claude-session.json")
            .exists(),
        "mode mismatch must not persist a binding"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn session_start_keeps_root_unbound_and_opaque_bash_is_advisory_until_bound() {
    let root = repository("root-allow");
    let session = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SessionStart",
            "session_id": "claude-session-a"
        }),
    );
    assert!(
        session.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&session.stderr)
    );
    let output: serde_json::Value =
        serde_json::from_slice(&session.stdout).expect("SessionStart hook output is JSON");
    assert_eq!(
        output["hookSpecificOutput"]["hookEventName"],
        "SessionStart"
    );
    assert!(
        !root
            .join(".shepherd/runs/v645/dispatch/.root-session.claude-session-a.json")
            .exists(),
        "SessionStart without an explicit run must not bind ambient v645"
    );

    let safe = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "claude-session-a",
            "tool_use_id": "safe-tool-a",
            "tool_name": "Bash",
            "tool_input": {"command": "printf safe"}
        }),
    );
    assert!(
        safe.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&safe.stderr)
    );
    let advised: serde_json::Value =
        serde_json::from_slice(&safe.stdout).expect("opaque Bash response is JSON");
    assert_eq!(
        decision(&advised),
        None,
        "a session that never opened a sprint runs its own shell: {advised}"
    );
    assert!(
        advice(&advised).contains("not bound"),
        "the advisory must still name the missing explicit binding: {advised}"
    );

    // Under `always`, the same call is the refusal this test pinned before
    // `bound` became the default.
    enforce_custody_always(&root);
    let refused: serde_json::Value = serde_json::from_slice(
        &hook(
            &root,
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "claude-session-a",
                "tool_use_id": "safe-tool-b",
                "tool_name": "Bash",
                "tool_input": {"command": "printf safe"}
            }),
        )
        .stdout,
    )
    .expect("opaque Bash denial is JSON");
    assert_eq!(
        decision(&refused),
        Some("deny"),
        "`always` must keep refusing opaque Bash in an unbound session: {refused}"
    );
    assert!(
        advice(&refused).contains("not bound"),
        "denial must name the missing explicit binding: {refused}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn unbound_pretooluse_names_the_remedy_without_leaking_an_errno() {
    let root = repository("deny");
    // The run is healthy, so an unattributed session is genuinely "never
    // bound" rather than a symptom of shepherd's own bookkeeping being broken.
    // Under the default that is advice; the SENTENCE it carries is the point,
    // and it is identical in both postures.
    let denied = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "unbound-session",
            "tool_use_id": "deny-tool-a",
            "tool_name": "Write",
            "tool_input": {"file_path": "README.md", "content": "nope"}
        }),
    );
    assert!(
        denied.status.success(),
        "PreToolUse must emit a fail-closed Claude denial instead of crashing: stderr={}",
        String::from_utf8_lossy(&denied.stderr)
    );
    let output: serde_json::Value =
        serde_json::from_slice(&denied.stdout).expect("denial output is JSON");
    assert_eq!(output["hookSpecificOutput"]["hookEventName"], "PreToolUse");
    assert_eq!(
        decision(&output),
        None,
        "the default posture advises a session that never opened a sprint: {output}"
    );
    let reason = advice(&output);
    assert!(!reason.is_empty());
    // #315: the unbound-session denial must stay fail-closed, but the reason
    // must name the remedy instead of leaking `DispatchStoreError::Io`'s raw
    // `os error` display -- an absent `.root-session.<id>.json` is the
    // normal representation of "never bound," not a filesystem fault.
    assert!(
        !reason.contains("os error"),
        "the unbound-session denial must not leak a raw errno: {reason}"
    );
    assert!(
        !reason.contains("No such file or directory"),
        "the unbound-session denial must not leak the raw io::Error text: {reason}"
    );
    assert!(
        reason.contains("not bound") && reason.contains("/shepherd:start"),
        "the unbound-session response must name the remedy: {reason}"
    );

    // `always` restores the refusal, carrying the same clean sentence.
    enforce_custody_always(&root);
    let refused: serde_json::Value = serde_json::from_slice(
        &hook(
            &root,
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "unbound-session",
                "tool_use_id": "deny-tool-b",
                "tool_name": "Write",
                "tool_input": {"file_path": "README.md", "content": "nope"}
            }),
        )
        .stdout,
    )
    .expect("denial output is JSON");
    assert_eq!(decision(&refused), Some("deny"), "{refused}");
    let reason = advice(&refused);
    assert!(
        !reason.contains("os error") && reason.contains("not bound"),
        "the refusal keeps the same clean remedy text: {reason}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// A GENUINE dispatch I/O failure -- distinct from "this session was never
/// bound" -- must keep its raw errno. `EACCES` on the root-session binding
/// file proves `unbound_session_reason` (native_hook.rs) discriminates by
/// `io::ErrorKind` rather than blanket-rewriting every `DispatchStoreError::Io`.
/// Unix only: permission bits are what makes this reproducible without
/// mocking the filesystem, and the classifier this test exercises only
/// special-cases the unix `open_regular_at` -> `DispatchStoreError::Io` path
/// (the non-unix twin reports the same "never bound" family of outcomes
/// through a different code path entirely, `crate::safe_fs`).
#[cfg(unix)]
#[test]
fn pretooluse_denial_keeps_the_errno_for_a_genuine_io_fault() {
    use std::os::unix::fs::PermissionsExt;

    let root = repository("genuine-io-fault");
    let binding_path = root.join(".shepherd/runs/.root-session.locked-session.json");
    fs::write(&binding_path, b"{}").expect("plant an unreadable root-session record");
    fs::set_permissions(&binding_path, fs::Permissions::from_mode(0o000))
        .expect("strip read permission to force a genuine EACCES");

    let denied = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "locked-session",
            "tool_use_id": "deny-tool-locked",
            "tool_name": "Write",
            "tool_input": {"file_path": "README.md", "content": "nope"}
        }),
    );
    // Restore permissions before `remove_dir_all` below has to delete it.
    fs::set_permissions(&binding_path, fs::Permissions::from_mode(0o644))
        .expect("restore permissions for cleanup");

    assert!(
        denied.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&denied.stderr)
    );
    let output: serde_json::Value =
        serde_json::from_slice(&denied.stdout).expect("denial output is JSON");
    assert_eq!(output["hookSpecificOutput"]["permissionDecision"], "deny");
    let reason = output["hookSpecificOutput"]["permissionDecisionReason"]
        .as_str()
        .expect("denial carries a reason");
    assert!(
        reason.contains("os error"),
        "a genuine I/O fault (EACCES, not ENOENT) must keep its raw errno, \
not the unbound-session remedy: {reason}"
    );
    assert!(
        !reason.contains("/shepherd:start"),
        "a genuine I/O fault must not be mistaken for the unbound-session \
remedy: {reason}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn malformed_input_and_unbound_subagent_events_have_safe_host_outputs() {
    let root = repository("malformed-and-blocked");
    let mut malformed = Command::new(binary())
        .args(["hook", "--harness", "claude"])
        .current_dir(&root)
        .env("SHEPHERD_HOME", root.join("isolated-home"))
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn malformed hook");
    malformed
        .stdin
        .take()
        .expect("malformed stdin")
        .write_all(b"{")
        .expect("write malformed input");
    let malformed = malformed.wait_with_output().expect("wait malformed hook");
    assert!(malformed.status.success());
    let malformed: serde_json::Value =
        serde_json::from_slice(&malformed.stdout).expect("malformed input denial is JSON");
    assert_eq!(
        malformed["hookSpecificOutput"]["permissionDecision"],
        "deny"
    );

    // An in-flock SubagentStart is now recorded rather than rejected, so the
    // unresolvable case is an agent type outside the closed flock -- which is
    // what this assertion was really about.
    let blocked = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SubagentStart",
            "session_id": "claude-session-blocked",
            "agent_id": "claude-agent-blocked",
            "agent_type": "general-purpose"
        }),
    );
    assert!(blocked.status.success());
    let blocked: serde_json::Value =
        serde_json::from_slice(&blocked.stdout).expect("blocked lifecycle context is JSON");
    assert_eq!(
        blocked["hookSpecificOutput"]["hookEventName"],
        "SubagentStart"
    );
    assert!(
        blocked["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .is_some_and(|detail| detail.contains("rejected"))
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// An unresolvable dispatch on child completion is ADVISORY, never a block.
///
/// Regression for the most expensive defect this plugin has shipped. This arm
/// used to emit `{"decision":"block"}`, and Claude Code responds to a blocked
/// `SubagentStop` by discarding the child's final report. So in any session not
/// inside a fully bound sprint -- which is every session that has not run a
/// seed, a plan, and lane binding -- every subagent completed its work and then
/// had its entire result thrown away by shepherd's own hook. Three agents in
/// one session burned 440k tokens and returned empty strings because of it.
///
/// Blocking a completion authorizes nothing: the work already happened. The
/// fail-closed law that makes `PreToolUse` refuse a mutation does not transfer
/// to a lifecycle event, because there is no mutation left to refuse. A POLICY
/// refusal on child completion is still a block; see the `Ok(HookOutput::Deny)`
/// arm in `native_hook.rs`. Infrastructure absence is not policy.
#[test]
fn subagent_stop_is_advisory_when_dispatch_cannot_be_resolved() {
    let root = repository("stop-unresolved");
    let stopped = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SubagentStop",
            "session_id": "claude-session-unresolved",
            "agent_id": "claude-agent-unresolved",
            "agent_type": "coder"
        }),
    );
    assert!(
        stopped.status.success(),
        "SubagentStop must return Claude's blocking decision instead of crashing: stderr={}",
        String::from_utf8_lossy(&stopped.stderr)
    );
    let output: serde_json::Value =
        serde_json::from_slice(&stopped.stdout).expect("stop output is JSON");
    assert!(
        output.get("decision").is_none(),
        "an unresolvable dispatch must not block a child's completion -- blocking \
         discards the child's finished report and authorizes nothing: {output}"
    );
    let detail = output["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .unwrap_or_default();
    assert!(
        detail.contains("rejected"),
        "advisory stop output must still explain what shepherd could not resolve: {output}"
    );
    assert_eq!(
        output["hookSpecificOutput"]["hookEventName"],
        "SubagentStop"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn direct_subagent_lifecycle_requires_native_broker() {
    let root = repository("lifecycle-broker-required");
    assert!(
        hook(
            &root,
            serde_json::json!({"hook_event_name": "SessionStart", "session_id": "s1"})
        )
        .status
        .success()
    );
    let started = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SubagentStart",
            "session_id": "s1",
            "agent_id": "direct-child",
            "agent_type": "shepherd:coder",
            "shepherd_dispatch": {
                "role": "coder",
                "lane": "l1-engine",
                "write_scope": ["crates/core/src/dispatch/**"],
                "lease_ms": 60000
            }
        }),
    );
    assert!(started.status.success());
    let output = format!(
        "{}{}",
        String::from_utf8_lossy(&started.stdout),
        String::from_utf8_lossy(&started.stderr)
    );
    assert!(
        output.contains("broker"),
        "direct child rejection must name broker custody: {output}"
    );
    assert!(
        !root
            .join(".shepherd/runs/v645/dispatch/direct-child.json")
            .exists()
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// A run that exists but is not executing is not a fault, and an unbound
/// session is not a fault either.
///
/// This was named for "broken bookkeeping" but constructs neither: the fixture
/// is a well-formed `planted` run, and the session simply never opened a
/// sprint. Under the default that is advice, so the refusal is asserted under
/// `always`. The property it was really guarding -- that shepherd's OWN
/// bookkeeping being broken must never manufacture authority -- lives in
/// `pretooluse_denial_keeps_the_errno_for_a_genuine_io_fault`, which is
/// unaffected by `dispatch_custody` in any mode because `is_unbound_session`
/// classifies a genuine fault separately.
#[test]
fn a_planted_run_does_not_authorize_an_unbound_mutation_under_always() {
    let root = repository("broken-namespace");
    // Exactly the v646 state: a run that exists but is not executing.
    fs::write(
        root.join(".shepherd/runs/v645/run.json"),
        br#"{"run":"v645","status":"planted"}"#,
    )
    .expect("write non-executing run");
    enforce_custody_always(&root);

    let blocked = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "stranded-session",
            "tool_use_id": "repair-tool-a",
            "tool_name": "Write",
            "tool_input": {"file_path": ".shepherd/runs/v645/run.json", "content": "{}"}
        }),
    );
    assert!(blocked.status.success());
    let output: serde_json::Value =
        serde_json::from_slice(&blocked.stdout).expect("hook output is JSON");
    assert_eq!(
        decision(&output),
        Some("deny"),
        "a non-executing run must not create mutation authority under `always`: {output}"
    );
    assert!(
        advice(&output).contains("not bound"),
        "the denial must name the missing root binding: {output}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn unbound_session_start_is_idempotent_for_the_same_session() {
    let root = repository("session-start-idempotent");
    let envelope = serde_json::json!({
        "hook_event_name": "SessionStart",
        "session_id": "replay-session"
    });

    let first = hook(&root, envelope.clone());
    assert!(
        first.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&first.stderr)
    );
    let first_out: serde_json::Value =
        serde_json::from_slice(&first.stdout).expect("first SessionStart output is JSON");
    let first_detail = first_out["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .expect("first SessionStart carries additionalContext");
    assert!(
        !first_detail.contains("rejected"),
        "first SessionStart must not be a rejection: {first_detail}"
    );
    assert!(first_detail.contains("remains unbound"), "{first_detail}");

    let second = hook(&root, envelope);
    assert!(
        second.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&second.stderr)
    );
    let second_out: serde_json::Value =
        serde_json::from_slice(&second.stdout).expect("second SessionStart output is JSON");
    let second_detail = second_out["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .expect("second SessionStart carries additionalContext");

    assert!(
        !second_detail.contains("rejected"),
        "a replayed SessionStart must not be rejected: {second_detail}"
    );
    assert!(second_detail.contains("remains unbound"), "{second_detail}");
    assert_eq!(
        first_out, second_out,
        "the native adapter must not need a separate replay suppression path"
    );
    assert!(
        !root
            .join(".shepherd/runs/v645/dispatch/.root-session.replay-session.json")
            .exists()
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// Idempotency must not become amnesia. A second
/// `SessionStart` for the SAME session id that asks to bind as a different
/// identity (role) than the one already on record must still refuse.
///
/// A literal *different session id* can never collide with an existing
/// binding in the first place: `dispatch_store.rs`'s no-clobber write keys
/// the binding file by session id
/// (`.root-session.<session id>.json`), so two distinct session ids resolve
/// to two distinct paths and just bind independently -- there is no
/// `AlreadyExists` to discriminate. The reachable form of "the record
/// belongs to a different session" is the SAME session id reused by what is,
/// in substance, a different actor, which is exactly what a changed `role`
/// on a replayed `SessionStart` looks like from shepherd's side. The dispatch
/// service compares that claim against the loaded durable identity.
#[test]
fn session_start_refuses_a_replay_with_a_different_identity() {
    let root = repository("session-start-different-identity");
    let first = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SessionStart",
            "session_id": "reused-session",
            "shepherd_dispatch": {"run": "v645", "mode": "execution"}
        }),
    );
    assert!(
        first.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&first.stderr)
    );
    let first_out: serde_json::Value =
        serde_json::from_slice(&first.stdout).expect("first SessionStart output is JSON");
    assert!(
        first_out["hookSpecificOutput"]["additionalContext"]
            .as_str()
            .is_some_and(|detail| detail.contains("bound root session to run v645")),
        "{first_out}"
    );

    let conflicting = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SessionStart",
            "session_id": "reused-session",
            "shepherd_dispatch": {"run": "v645", "role": "planter", "mode": "execution"}
        }),
    );
    assert!(
        conflicting.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&conflicting.stderr)
    );
    let conflicting_out: serde_json::Value =
        serde_json::from_slice(&conflicting.stdout).expect("conflicting output is JSON");
    let detail = conflicting_out["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .expect("conflicting SessionStart carries additionalContext");
    assert!(
        detail.contains("rejected"),
        "a same-session replay claiming a different identity must still \
refuse: {detail}"
    );
    assert!(
        detail.contains("different identity"),
        "the refusal must name which case fired: {detail}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// Under `always`, the self-repair exemption is exact: only the canonical
/// bootstrap passes, and nothing rides it.
///
/// The exemption exists only in the `always` posture. Under the default,
/// `bound`, an unbound session was never governed, so there is no door to
/// squeeze through -- which is why this opts in explicitly rather than
/// relying on the default.
#[test]
fn unbound_shepherd_commands_require_an_exact_bootstrap_under_always() {
    let root = repository("self-repair");
    enforce_custody_always(&root);
    let repair = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "unbound-session",
            "tool_use_id": "repair-tool-b",
            "tool_name": "Bash",
            "tool_input": {"command": "shepherd run transition v645 --to executing"}
        }),
    );
    assert!(repair.status.success());
    let output: serde_json::Value =
        serde_json::from_slice(&repair.stdout).expect("hook output is JSON");
    assert_eq!(
        decision(&output),
        Some("deny"),
        "a broad shepherd prefix must not bypass root binding: {output}"
    );

    // The exemption is narrow: chaining past it is refused, so it cannot be
    // used to smuggle an unrelated command through an unbound session.
    let chained = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "unbound-session",
            "tool_use_id": "repair-tool-c",
            "tool_name": "Bash",
            "tool_input": {"command": "shepherd --version; rm -rf /tmp/shepherd-escape"}
        }),
    );
    assert!(chained.status.success());
    let chained: serde_json::Value =
        serde_json::from_slice(&chained.stdout).expect("hook output is JSON");
    assert_eq!(
        decision(&chained),
        Some("deny"),
        "a chained command must not ride the self-repair exemption: {chained}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// A host tool envelope carries no `shepherd_dispatch` block, so the tool name
/// never reached the resolver, no write paths were derived, and the guard
/// refused every `Write` and `Edit` a root session attempted for lack of them.
#[test]
fn root_session_may_write_inside_the_repository_but_not_outside_it() {
    let root = repository("root-write");
    let session = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "claude-session-write",
            "tool_use_id": "bind-root-write",
            "tool_name": "Bash",
            "tool_input": {
                "command": "shepherd dispatch bind-root --run v645 --mode execution --confirm"
            }
        }),
    );
    assert!(session.status.success());
    if !session.stdout.is_empty() {
        let session: serde_json::Value =
            serde_json::from_slice(&session.stdout).expect("bind output is JSON");
        assert_ne!(session["hookSpecificOutput"]["permissionDecision"], "deny");
    }

    let shell = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "claude-session-write",
            "tool_use_id": "root-shell",
            "tool_name": "Bash",
            "tool_input": {"command": "git status --short --branch"}
        }),
    );
    assert!(
        shell.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&shell.stderr)
    );
    assert!(
        shell.stdout.is_empty(),
        "the exact bound Claude root must retain ordinary host-shell authority: {}",
        String::from_utf8_lossy(&shell.stdout)
    );

    let inside = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "claude-session-write",
            "tool_use_id": "write-inside",
            "tool_name": "Write",
            // Relative: the fixture root resolves through a /var -> /private/var
            // symlink on macOS, which is a temp-dir artifact, not a scope escape.
            "tool_input": {"file_path": "notes.md", "content": "ok"}
        }),
    );
    assert!(
        inside.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&inside.stderr)
    );
    assert!(
        inside.stdout.is_empty(),
        "a root session must be able to write inside its own repository: {}",
        String::from_utf8_lossy(&inside.stdout)
    );

    // Deriving the path is what makes the scope check meaningful, so the
    // escape must still be refused rather than passing for want of a path.
    let outside = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "claude-session-write",
            "tool_use_id": "write-outside",
            "tool_name": "Write",
            "tool_input": {"file_path": "/etc/passwd", "content": "no"}
        }),
    );
    assert!(outside.status.success());
    let outside: serde_json::Value =
        serde_json::from_slice(&outside.stdout).expect("hook output is JSON");
    assert_eq!(
        outside["hookSpecificOutput"]["permissionDecision"], "deny",
        "a write outside the primary repository must stay refused: {outside}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// `PostToolUse` resolves like `PreToolUse` but must not be gated by it: a
/// verdict about a call that already ran is advice, and it was being emitted
/// under a hardcoded `PreToolUse` label.
#[test]
fn post_tool_use_records_without_running_the_pre_flight_guard() {
    let root = repository("post-tool-use");
    let session = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SessionStart",
            "session_id": "claude-session-post"
        }),
    );
    assert!(session.status.success());

    // The same shape that PreToolUse refuses outside the repository.
    let after = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PostToolUse",
            "session_id": "claude-session-post",
            "tool_use_id": "post-tool-a",
            "tool_name": "Write",
            "tool_input": {"file_path": "/etc/passwd", "content": "no"}
        }),
    );
    assert!(
        after.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&after.stderr)
    );
    let text = String::from_utf8_lossy(&after.stdout);
    assert!(
        !text.contains("\"permissionDecision\""),
        "PostToolUse must not emit a permission decision: {text}"
    );
    assert!(
        !text.contains("PreToolUse"),
        "PostToolUse must never label its output PreToolUse: {text}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// The dispatch ledger stayed empty on every harness: `SubagentStart` blocked
/// on a missing binding because a host envelope carries no `shepherd_dispatch`
/// block and has no way to add one. With no record, no tool call could be
/// attributed to a role, so not one role-scoped guard rule could ever fire.
#[test]
fn direct_role_starts_cannot_bypass_native_broker() {
    let root = repository("role-broker-required");
    assert!(
        hook(
            &root,
            serde_json::json!({"hook_event_name": "SessionStart", "session_id": "s1"})
        )
        .status
        .success()
    );
    for (agent, agent_type) in [
        ("cond-1", "shepherd:conductor"),
        ("code-1", "shepherd:coder"),
        ("critic-1", "shepherd:critic"),
    ] {
        let started = hook(
            &root,
            serde_json::json!({
                "hook_event_name": "SubagentStart",
                "session_id": "s1",
                "agent_id": agent,
                "agent_type": agent_type
            }),
        );
        assert!(started.status.success());
        let output = format!(
            "{}{}",
            String::from_utf8_lossy(&started.stdout),
            String::from_utf8_lossy(&started.stderr)
        );
        assert!(
            output.contains("broker"),
            "{agent_type} direct start must require broker: {output}"
        );
        assert!(
            !root
                .join(format!(".shepherd/runs/v645/dispatch/{agent}.json"))
                .exists()
        );
    }
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// `[guard] dispatch_custody` defaults to `bound`, and `always` restores the
/// posture that shipped for one release.
///
/// `bound` enforces custody only once a session actually holds a dispatch
/// record, so a session that never opened a sprint is advised rather than
/// refused. That is the fix: `always` is what made the plugin refuse ordinary
/// work in its own repository, down to refusing an agent a write to its own
/// home directory.
///
/// A GENUINE FAULT is unaffected in either mode. `bound` relaxes exactly one
/// thing -- "this session was never bound" -- and never "shepherd's own
/// bookkeeping is broken", which is why `is_unbound_session` classifies the two
/// separately and why `pretooluse_denial_keeps_the_errno_for_a_genuine_io_fault`
/// still passes untouched.
#[test]
fn dispatch_custody_defaults_to_bound_and_always_restores_the_refusal() {
    let root = repository("custody-bound");
    let probe = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "session_id": "never-bound",
        "tool_name": "Write",
        "tool_input": {"file_path": "src/x.rs"},
    });

    // Default (`bound`): advice, naming what is missing.
    let advised: serde_json::Value = serde_json::from_slice(&hook(&root, probe.clone()).stdout)
        .expect("default custody output is JSON");
    assert_eq!(
        decision(&advised),
        None,
        "the default must not refuse a session that never opened a sprint: {advised}"
    );
    assert!(
        advice(&advised).contains("not bound"),
        "the advisory must still say what is missing: {advised}"
    );

    // Opt in to `always`: the same request becomes a refusal.
    enforce_custody_always(&root);
    let denied: serde_json::Value =
        serde_json::from_slice(&hook(&root, probe).stdout).expect("always custody output is JSON");
    assert_eq!(
        decision(&denied),
        Some("deny"),
        "`always` must refuse an unbound mutation: {denied}"
    );
    assert!(
        advice(&denied).contains("not bound"),
        "the refusal names the same remedy: {denied}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// `[guard] open_flock` reaches the live engine.
///
/// `GuardEngine::new` enforces `closed-flock-only` so the predicate corpus keeps
/// proving what the rule does; the config default is the opposite (`true`), and
/// nothing connected the two. `with_open_flock` existed and had no caller, so
/// the documented default was inert and the shipped runtime always enforced.
/// The sibling field `write_scope` was deleted for the same defect; this one is
/// wired instead, because the engine can actually act on it.
///
/// Needs a BOUND root: an unbound session never reaches the guard at all, it is
/// answered by `unresolved_pre_tool_use` first.
#[test]
fn open_flock_configuration_reaches_the_live_guard_engine() {
    let root = repository("open-flock");
    let bind = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "claude-session-flock",
            "tool_use_id": "bind-flock",
            "tool_name": "Bash",
            "tool_input": {
                "command": "shepherd dispatch bind-root --run v645 --mode execution --confirm"
            }
        }),
    );
    assert!(bind.status.success());
    assert!(
        root.join(".shepherd/runs/v645/dispatch/.root-session.claude-session-flock.json")
            .is_file(),
        "the fixture must actually bind before the guard can be consulted"
    );

    // An invented tenth role is the only thing this rule can refuse: a target
    // with no `shepherd:` carrier is a host agent, not a role.
    let probe = serde_json::json!({
        "hook_event_name": "PreToolUse",
        "session_id": "claude-session-flock",
        "tool_use_id": "flock-probe",
        "tool_name": "Agent",
        "tool_input": {"subagent_type": "shepherd:reviewer"},
    });

    fs::write(
        root.join(".shepherd/shepherd.toml"),
        b"[guard]\nopen_flock = false\n",
    )
    .expect("write guard configuration");
    let closed: serde_json::Value =
        serde_json::from_slice(&hook(&root, probe.clone()).stdout).expect("closed-flock is JSON");
    assert_eq!(
        decision(&closed),
        Some("deny"),
        "`open_flock = false` must refuse an invented tenth role: {closed}"
    );

    // `true` is the documented default and must actually take effect.
    fs::write(
        root.join(".shepherd/shepherd.toml"),
        b"[guard]\nopen_flock = true\n",
    )
    .expect("write guard configuration");
    let opened = hook(&root, probe);
    assert!(opened.status.success());
    let opened: serde_json::Value = if opened.stdout.is_empty() {
        serde_json::json!({"hookSpecificOutput": {}})
    } else {
        serde_json::from_slice(&opened.stdout).expect("open-flock is JSON")
    };
    assert_ne!(
        decision(&opened),
        Some("deny"),
        "`open_flock = true` must reach the engine and withhold the carrier address: {opened}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}