shepherd-cli 6.5.2

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
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");
    root
}

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");
    root
}

fn hook(root: &Path, input: serde_json::Value) -> Output {
    let mut child = Command::new(binary())
        .args(["claude-hook"])
        .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 session_start_binds_root_and_safe_pretooluse_allows() {
    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")
            .is_file()
    );

    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)
    );
    assert!(safe.stdout.is_empty(), "safe tool use must emit no denial");
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn pretooluse_denies_unresolved_or_unbound_requests() {
    let root = repository("deny");
    // The run is healthy, so an unattributed session is a real refusal rather
    // than a symptom of shepherd's own bookkeeping being broken.
    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!(output["hookSpecificOutput"]["permissionDecision"], "deny");
    let reason = output["hookSpecificOutput"]["permissionDecisionReason"]
        .as_str()
        .expect("denial carries a non-empty reason");
    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 denial must name the remedy: {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/v645/dispatch/.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(["claude-hook"])
        .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");
}

#[test]
fn subagent_stop_blocks_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("blocked stop output is JSON");
    assert_eq!(output["decision"], "block");
    assert!(
        output["reason"]
            .as_str()
            .is_some_and(|reason| reason.contains("rejected")),
        "blocking stop output must explain why the lifecycle transition was rejected: {output}"
    );
    assert!(output.get("hookSpecificOutput").is_none());
    fs::remove_dir_all(root).expect("remove fixture directory");
}

#[test]
fn lifecycle_start_and_stop_follow_the_native_dispatch_ledger() {
    let root = repository("lifecycle");
    let session = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SessionStart",
            "session_id": "claude-session-lifecycle"
        }),
    );
    assert!(session.status.success());

    let binding = serde_json::json!({
        "run": "v645",
        "role": "coder",
        "lane": "l1-engine",
        "write_scope": ["crates/core/src/dispatch/**"],
        "model": "claude-sonnet-5",
        "observed_capabilities": [
            "read", "search", "shell", "write", "skill-load", "tool-discovery", "subagent-provider"
        ],
        "capability_source": "claude-hook-test",
        "harness_version": "test",
        "lease_ms": 60000
    });
    let started = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SubagentStart",
            "session_id": "claude-session-lifecycle",
            "agent_id": "claude-agent-lifecycle",
            "agent_type": "coder",
            "shepherd_dispatch": binding
        }),
    );
    assert!(
        started.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&started.stderr)
    );
    assert!(
        root.join(".shepherd/runs/v645/dispatch/claude-agent-lifecycle.json")
            .is_file()
    );

    let stopped = hook(
        &root,
        serde_json::json!({
            "hook_event_name": "SubagentStop",
            "session_id": "claude-session-lifecycle",
            "agent_id": "claude-agent-lifecycle",
            "agent_type": "coder",
            "shepherd_dispatch": {
                "run": "v645",
                "lane": "l1-engine",
                "expected_revision": 1,
                "result_artifact": "lanes/l1-engine/reports/claude-agent-lifecycle.md"
            }
        }),
    );
    assert!(
        stopped.status.success(),
        "stderr={}",
        String::from_utf8_lossy(&stopped.stderr)
    );
    let record: serde_json::Value = serde_json::from_slice(
        &fs::read(root.join(".shepherd/runs/v645/dispatch/claude-agent-lifecycle.json"))
            .expect("read stopped dispatch record"),
    )
    .expect("decode stopped dispatch record");
    assert_eq!(record["state"], "stopped");
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// A run shepherd cannot attribute against must not disable the tools that
/// repair it.
///
/// This is the v6.4.6 dogfooding deadlock: the `Write|Edit|Bash|Agent|Workflow`
/// matcher covers the entire repair surface, so one unusable run namespace made
/// the session structurally incapable of fixing its own run state.
#[test]
fn broken_run_namespace_allows_tools_instead_of_stranding_the_session() {
    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");

    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_ne!(
        output["hookSpecificOutput"]["permissionDecision"], "deny",
        "a broken run namespace must not deny the tools that repair it: {output}"
    );
    let detail = output["hookSpecificOutput"]["additionalContext"]
        .as_str()
        .expect("the advisory banner carries additionalContext");
    assert!(
        detail.contains("no usable run namespace"),
        "the fault must be surfaced, not swallowed: {output}"
    );
    // The banner used to print `Repair with `shepherd run layout <run>
    // --repair` then `shepherd run set <run> --status executing`.` -- both
    // of which are exactly the two conditions `run_namespace_is_usable`
    // checks, so an operator following that advice verbatim flips this very
    // advisory into a hard `Deny` without ever binding the session. The fix
    // prints no command at all here; a backtick anywhere in this banner
    // would be exactly that regression recurring.
    assert!(
        !detail.contains('`'),
        "the advisory banner must name no command, backtick-fenced or \
otherwise: {detail}"
    );
    assert!(
        !detail.contains("Repair with"),
        "the advisory banner must not point at the two-command remediation \
that flips allow into deny: {detail}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// #314: a replayed `SessionStart` for a session that already owns the
/// binding is a non-rejection re-affirmation, not
/// `native lifecycle hook rejected: dispatch record already exists: ...`.
#[test]
fn 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("bound root session to run v645"),
        "first SessionStart must bind: {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");

    // The idempotency property this fix implements is a NAMED
    // re-affirmation ("root session already bound to run v645"), not a
    // byte-identical replay of the bind confirmation -- and, above all, not
    // a rejection.
    assert!(
        !second_detail.contains("rejected"),
        "a replayed SessionStart must not be rejected: {second_detail}"
    );
    assert!(
        second_detail.contains("root session already bound to run v645"),
        "a replayed SessionStart must name the re-affirmation: {second_detail}"
    );
    assert_ne!(
        first_out, second_out,
        "the re-affirmation is a named, distinct response, not a byte-for-byte \
replay of the bind confirmation: first={first_out} second={second_out}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}

/// #314's other half: 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, and exactly
/// what `root_binding_reaffirmation` (native_hook.rs) checks the loaded
/// on-disk record against.
#[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"
        }),
    );
    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": {"role": "planter"}
        }),
    );
    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");
}

/// `shepherd` invoking itself is always permitted, so a session can never be
/// denied the one command that repairs the state doing the denying.
#[test]
fn shepherd_self_repair_is_always_permitted() {
    let root = repository("self-repair");
    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 set v645 --status executing"}
        }),
    );
    assert!(repair.status.success());
    let output: serde_json::Value =
        serde_json::from_slice(&repair.stdout).expect("hook output is JSON");
    assert_ne!(
        output["hookSpecificOutput"]["permissionDecision"], "deny",
        "shepherd self-repair must never be denied: {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!(
        chained["hookSpecificOutput"]["permissionDecision"], "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": "SessionStart",
            "session_id": "claude-session-write"
        }),
    );
    assert!(session.status.success());

    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 dispatched_agents_are_recorded_and_their_role_rules_enforce() {
    let root = repository("subagent-ledger");
    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"),
    ] {
        let started = hook(
            &root,
            serde_json::json!({
                "hook_event_name": "SubagentStart",
                "session_id": "s1",
                "agent_id": agent,
                "agent_type": agent_type,
                "model": "test-model"
            }),
        );
        assert!(started.status.success());
        assert!(
            root.join(format!(".shepherd/runs/v645/dispatch/{agent}.json"))
                .is_file(),
            "{agent_type} must be recorded in the dispatch ledger"
        );
    }

    // Tool calls carry agent_id only; the record supplies the type.
    let decision = |agent: &str, tool: &str, input: serde_json::Value| -> String {
        let out = hook(
            &root,
            serde_json::json!({
                "hook_event_name": "PreToolUse",
                "session_id": "s1",
                "agent_id": agent,
                "tool_use_id": format!("{agent}-{tool}"),
                "tool_name": tool,
                "tool_input": input
            }),
        );
        assert!(out.status.success());
        String::from_utf8_lossy(&out.stdout).into_owned()
    };

    assert!(
        decision(
            "cond-1",
            "Bash",
            serde_json::json!({"command": "printf hi"})
        )
        .is_empty(),
        "a recorded conductor may run a safe shell command"
    );
    assert!(
        decision(
            "cond-1",
            "Agent",
            serde_json::json!({"subagent_type": "shepherd:coder"})
        )
        .is_empty(),
        "a conductor may dispatch an implementer"
    );
    assert!(
        decision(
            "cond-1",
            "Agent",
            serde_json::json!({"subagent_type": "shepherd:engineer"})
        )
        .contains("deny"),
        "a conductor must not dispatch the plan-author role"
    );
    assert!(
        decision(
            "code-1",
            "Agent",
            serde_json::json!({"subagent_type": "shepherd:worker"})
        )
        .contains("deny"),
        "an implementer must not dispatch at all"
    );

    // An agent shepherd never recorded is shepherd's own gap, not a claim by
    // the caller, so it is surfaced and allowed rather than refused. Denying
    // would strand every agent already running when the ledger began working.
    let unrecorded = decision(
        "never-started",
        "Write",
        serde_json::json!({"file_path": "x.md", "content": "y"}),
    );
    assert!(
        !unrecorded.contains("\"permissionDecision\""),
        "an unrecorded agent must not be denied: {unrecorded}"
    );
    assert!(
        unrecorded.contains("never recorded this agent"),
        "the gap must be surfaced, not swallowed: {unrecorded}"
    );
    fs::remove_dir_all(root).expect("remove fixture directory");
}