shepherd-cli 6.7.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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
//! Host hook transport over the canonical Rust lifecycle and guard engine.
//!
//! The marketplace plugin calls the installed `shepherd` binary directly. This
//! boundary intentionally owns only host JSON envelopes and output shapes;
//! identity normalization, lifecycle planning, dispatch persistence, and guard
//! evaluation remain in the shared typed engine.

use std::{
    collections::BTreeSet,
    fs,
    io::{self, Read},
};

use serde::Deserialize;
use shepherd::run::RunKind;
use shepherd::{
    GuardValue, Harness,
    dispatch::{
        AgentId, DispatchBinding, DispatchPlan, DispatchRequest, LaneId, RawIdentity, Role, RunId,
        plan_lifecycle,
    },
};

use crate::{
    BindRootDispatchRequest, ContextInputs, DispatchService, DispatchStore, ExecutionContext,
    cmd::{dispatch::read_project_id, guard::load_engine},
    interface::{CliError, CliGlobals},
};

const MAX_HOOK_BYTES: usize = 1_048_576;
const DEFAULT_LEASE_MS: u64 = 86_400_000;

/// The label a host is named by in operator-facing hook messages.
fn hook_label(harness: Harness) -> &'static str {
    match harness {
        Harness::ClaudeCode => "Claude",
        Harness::Codex => "Codex",
        Harness::Pi => "Pi",
        Harness::PrimeAgent => "Prime",
        // `Harness` is `#[non_exhaustive]`: a host added upstream must not
        // silently inherit another host's label.
        _ => "unknown host",
    }
}

/// The capability source a host's native hook attests under.
fn capability_source(harness: Harness) -> &'static str {
    match harness {
        Harness::ClaudeCode => "claude-native-hook",
        Harness::Codex => "codex-native-hook",
        Harness::Pi => "pi-native-hook",
        Harness::PrimeAgent => "prime-native-hook",
        // A capability source is an attestation. An unknown host gets its own
        // name rather than borrowing one it was never granted.
        _ => "unknown-native-hook",
    }
}

#[derive(Debug, Deserialize)]
struct NativeHookInput {
    hook_event_name: String,
    session_id: String,
    #[serde(default)]
    turn_id: Option<String>,
    #[serde(default)]
    agent_id: Option<String>,
    #[serde(default)]
    agent_type: Option<String>,
    #[serde(default)]
    tool_use_id: Option<String>,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    #[serde(alias = "claude_version")]
    provider_version: Option<String>,
    #[serde(default)]
    tool_name: Option<String>,
    #[serde(default)]
    tool_input: Option<serde_json::Value>,
    #[serde(default)]
    shepherd_dispatch: Option<ClaudeDispatchBinding>,
    #[serde(default)]
    last_assistant_message: Option<String>,
}

#[derive(Debug, Default, Deserialize)]
struct ClaudeDispatchBinding {
    #[serde(default)]
    run: Option<String>,
    #[serde(default)]
    role: Option<String>,
    #[serde(default)]
    lane: Option<String>,
    #[serde(default)]
    parent_agent_id: Option<String>,
    #[serde(default)]
    write_scope: Option<Vec<String>>,
    #[serde(default)]
    model: Option<String>,
    #[serde(default)]
    observed_capabilities: Option<BTreeSet<String>>,
    #[serde(default)]
    capability_source: Option<String>,
    #[serde(default)]
    harness_version: Option<String>,
    #[serde(default)]
    provider_version: Option<String>,
    #[serde(default)]
    lease_ms: Option<u64>,
    #[serde(default)]
    expected_revision: Option<u64>,
    #[serde(default)]
    result_artifact: Option<String>,
    #[serde(default)]
    source_agent_id: Option<String>,
    #[serde(default)]
    mode: Option<String>,
}

pub(super) fn run_native_hook(host: Harness, globals: CliGlobals) -> Result<(), CliError> {
    let input = match read_input(host) {
        Ok(input) => input,
        Err(error) => return emit_parse_error(error, host),
    };
    let pre_tool_use = input.hook_event_name == "PreToolUse";
    let hook_event_name = input.hook_event_name.clone();
    match run_hook(input, host, globals) {
        Ok(HookOutput::Silent) => Ok(()),
        Ok(HookOutput::Context { event, detail }) => emit_json(&context(&event, &detail), host),
        // A POLICY refusal on child completion is a block: shepherd resolved the
        // child's identity and decided its result must not stand.
        Ok(HookOutput::Deny { detail }) if hook_event_name == "SubagentStop" => {
            emit_json(&block(&detail), host)
        }
        Ok(HookOutput::Deny { detail }) => emit_json(&deny(&hook_event_name, &detail), host),
        // Bootstrap commands are classified and handled before project or run
        // resolution. Every other PreToolUse infrastructure fault remains a
        // refusal: absence of authority cannot grant authority.
        Err(error) if pre_tool_use => emit_json(&deny("PreToolUse", &error.detail()), host),
        // An INFRASTRUCTURE fault on a lifecycle event is advisory, including
        // on `SubagentStop`.
        //
        // Fail-closed is correct for `PreToolUse`, where refusing a mutation
        // grants nothing and costs nothing. It is wrong here. Blocking a child's
        // completion authorizes nothing -- the work already happened -- and the
        // host discards the child's final report, so the only effect is to
        // destroy finished work. A session with no dispatch record for a child
        // is a session shepherd has nothing to say about; saying nothing is the
        // correct output, not blocking. This arm previously emitted `block`,
        // which silently threw away every subagent result in any session that
        // was not inside a fully bound sprint.
        Err(error) => emit_json(&context(&hook_event_name, &error.detail()), host),
    }
}

enum HookOutput {
    Silent,
    Context { event: String, detail: String },
    Deny { detail: String },
}

#[derive(Debug)]
enum HookFault {
    CallerPolicy(String),
    InvalidCustody(String),
    UnsupportedCapability(String),
    InternalCorruption(String),
}

impl HookFault {
    fn lifecycle(error: impl std::fmt::Display) -> Self {
        Self::InvalidCustody(error.to_string())
    }

    fn caller(error: impl std::fmt::Display) -> Self {
        Self::CallerPolicy(error.to_string())
    }

    fn from_cli_caller(error: CliError) -> Self {
        Self::CallerPolicy(
            error
                .message_text()
                .unwrap_or("native hook request is invalid")
                .into(),
        )
    }

    fn from_cli_internal(error: CliError) -> Self {
        Self::InternalCorruption(
            error
                .message_text()
                .unwrap_or("native hook infrastructure failed")
                .into(),
        )
    }

    fn detail(&self) -> String {
        match self {
            Self::CallerPolicy(detail) => format!("caller policy violation: rejected: {detail}"),
            Self::InvalidCustody(detail) => format!(
                "lifecycle custody invalid: rejected: {detail}. Reload the plugin, re-bind the root, and respawn this worker; an existing session keeps the hook configuration it loaded at startup"
            ),
            Self::UnsupportedCapability(detail) => {
                format!("unsupported host capability: rejected: {detail}")
            }
            Self::InternalCorruption(detail) => format!(
                "Shepherd internal corruption: rejected: {detail}. Run `shepherd doctor`; mutation remains denied until Native state is repaired"
            ),
        }
    }
}

impl From<CliError> for HookFault {
    fn from(error: CliError) -> Self {
        Self::from_cli_internal(error)
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
enum BootstrapCommand {
    ProjectInit,
    RunInit {
        run: RunId,
    },
    RunShow {
        run: RunId,
    },
    BindRoot {
        run: RunId,
        mode: shepherd::dispatch::RootMode,
    },
}

fn read_input(host: Harness) -> Result<NativeHookInput, CliError> {
    let mut bytes = Vec::new();
    io::stdin()
        .take(u64::try_from(MAX_HOOK_BYTES + 1).expect("hook input limit fits in u64"))
        .read_to_end(&mut bytes)
        .map_err(|error| {
            CliError::message(format!(
                "cannot read {} hook input: {error}",
                hook_label(host)
            ))
        })?;
    if bytes.len() > MAX_HOOK_BYTES {
        return Err(CliError::message(format!(
            "{} hook input exceeds 1048576-byte limit",
            hook_label(host)
        )));
    }
    serde_json::from_slice(&bytes).map_err(|_| {
        CliError::message(format!(
            "{} hook input must be one valid RFC 8259 JSON value",
            hook_label(host)
        ))
    })
}

fn emit_parse_error(error: CliError, host: Harness) -> Result<(), CliError> {
    let fallback = format!("invalid {} hook input", hook_label(host));
    // The envelope did not parse, so the event it claimed is unknown; a
    // refusal is only meaningful pre-flight, which is what the host asked for.
    emit_json(
        &deny("PreToolUse", error.message_text().unwrap_or(&fallback)),
        host,
    )
}

fn bootstrap_command(input: &NativeHookInput) -> Option<BootstrapCommand> {
    if input.hook_event_name != "PreToolUse" || input.tool_name.as_deref() != Some("Bash") {
        return None;
    }
    let command = input.tool_input.as_ref()?.get("command")?.as_str()?;
    if command == "shepherd init --confirm" {
        return Some(BootstrapCommand::ProjectInit);
    }
    let arguments = command.split(' ').collect::<Vec<_>>();
    if arguments.iter().any(|argument| argument.is_empty()) {
        return None;
    }
    match arguments.as_slice() {
        ["shepherd", "run", "show", run, "--json"] => {
            canonical_run(run).map(|run| BootstrapCommand::RunShow { run })
        }
        [
            "shepherd",
            "run",
            "init",
            run,
            "--branch",
            branch,
            "--base",
            base,
            "--version",
            version,
        ] => canonical_run_initializer(run, branch, base, version)
            .map(|run| BootstrapCommand::RunInit { run }),
        [
            "shepherd",
            "dispatch",
            "bind-root",
            "--run",
            run,
            "--mode",
            // Both spellings: an operator or a stale skill may still say
            // `planning`, and `RootMode::from_str` maps it to `Planting`.
            mode @ ("planting" | "planning" | "execution"),
            "--confirm",
        ] => canonical_run(run).map(|run| BootstrapCommand::BindRoot {
            run,
            mode: mode
                .parse()
                .unwrap_or(shepherd::dispatch::RootMode::Execution),
        }),
        _ => None,
    }
}

fn canonical_run(value: &str) -> Option<RunId> {
    if !crate::cmd::run::is_canonical(value) {
        return None;
    }
    RunId::new(value).ok()
}

fn canonical_run_initializer(run: &str, branch: &str, base: &str, version: &str) -> Option<RunId> {
    let run = canonical_run(run)?;
    if !safe_git_ref(base) || !release_version(version) {
        return None;
    }
    let version_ref = format!("v{version}");
    if branch != version_ref || !safe_git_ref(branch) {
        return None;
    }
    let kind = if version.contains("-dev.") {
        RunKind::Sprint
    } else {
        RunKind::PatchArc
    };
    let derived = crate::cmd::run::derive_id(&version_ref, kind).ok()?;
    (run.as_str() == derived).then_some(run)
}

fn release_version(value: &str) -> bool {
    let (numbers, dev) = value.split_once("-dev.").unwrap_or((value, ""));
    let mut parts = numbers.split('.');
    let valid_numbers = [parts.next(), parts.next(), parts.next()]
        .into_iter()
        .all(|part| {
            part.is_some_and(|part| {
                !part.is_empty() && part.bytes().all(|byte| byte.is_ascii_digit())
            })
        })
        && parts.next().is_none();
    valid_numbers
        && (dev.is_empty() || (!dev.is_empty() && dev.bytes().all(|byte| byte.is_ascii_digit())))
}

fn safe_git_ref(value: &str) -> bool {
    let bytes = value.as_bytes();
    !bytes.is_empty()
        && bytes.len() <= 255
        && !value.starts_with(['/', '.'])
        && !value.ends_with(['/', '.'])
        && !value.ends_with(".lock")
        && !value.contains("..")
        && !value.contains("//")
        && !value.contains("@{")
        && bytes
            .iter()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(*byte, b'-' | b'_' | b'.' | b'/'))
}

/// Translate the observed Codex patch envelope at the host boundary (#472).
/// Planning and guard evaluation must consume the same canonical payload.
/// Keep all other fields so native validation, not this adapter, decides which
/// fields and write targets are authorized. Never choose between competing
/// payload aliases or change Bash and other harnesses' envelopes.
fn normalize_hook_tool_input(input: &mut NativeHookInput, host: Harness) -> Result<(), HookFault> {
    if host != Harness::Codex
        || !matches!(input.hook_event_name.as_str(), "PreToolUse" | "PostToolUse")
        || input.tool_name.as_deref() != Some("apply_patch")
    {
        return Ok(());
    }
    let Some(fields) = input
        .tool_input
        .as_mut()
        .and_then(serde_json::Value::as_object_mut)
    else {
        return Ok(());
    };
    let Some(command) = fields.get("command") else {
        return Ok(());
    };
    if fields.contains_key("input") || fields.contains_key("patch") {
        return Err(HookFault::caller(
            "Codex apply_patch command must not be combined with input or patch",
        ));
    }
    if !command.is_string() {
        return Err(HookFault::caller(
            "Codex apply_patch command must be a string",
        ));
    }
    let command = fields.remove("command").expect("command was checked above");
    fields.insert("input".into(), command);
    Ok(())
}

fn run_hook(
    mut input: NativeHookInput,
    host: Harness,
    globals: CliGlobals,
) -> Result<HookOutput, HookFault> {
    normalize_hook_tool_input(&mut input, host)?;
    if matches!(host, Harness::Codex | Harness::ClaudeCode)
        && matches!(
            input.hook_event_name.as_str(),
            "PreToolUse" | "SubagentStart" | "SubagentResume" | "SubagentStop" | "Stop"
        )
        && std::env::var_os("SHEPHERD_NATIVE_BROKER_ENDPOINT").is_some()
    {
        return run_broker_hook(&input, host, globals);
    }
    if input.hook_event_name == "Stop" {
        return Ok(HookOutput::Silent);
    }
    let bootstrap = bootstrap_command(&input);
    if bootstrap == Some(BootstrapCommand::ProjectInit) {
        return Ok(HookOutput::Context {
            event: "PreToolUse".into(),
            detail: "authorized exact native project initialization".into(),
        });
    }
    let identity = RawIdentity::new(
        host,
        &input.hook_event_name,
        input.session_id.clone(),
        input.agent_id.as_deref(),
        input.agent_type.as_deref(),
        input.tool_use_id.as_deref(),
        input.model.as_deref(),
        input.provider_version.as_deref(),
    )
    .normalize()
    .map_err(HookFault::caller)?;
    if matches!(
        input.hook_event_name.as_str(),
        "SubagentStart" | "SubagentResume" | "SubagentStop"
    ) {
        return Ok(HookOutput::Context {
            event: input.hook_event_name.clone(),
            detail: format!(
                "unsupported host capability: rejected: raw {} is correlation only and cannot authorize child lifecycle; use the native broker launch exchange",
                input.hook_event_name
            ),
        });
    }
    if input.hook_event_name == "SessionStart"
        && input
            .shepherd_dispatch
            .as_ref()
            .and_then(|binding| binding.run.as_deref())
            .is_none()
    {
        return Ok(HookOutput::Context {
            event: "SessionStart".into(),
            detail: format!(
                "root session remains unbound until an explicit run bootstrap; lifecycle_contract=shepherd-hook/1 cli={}. Hook configuration is fixed at session start, so reload the plugin and respawn existing workers after an upgrade; a new-session probe does not validate older sessions",
                env!("CARGO_PKG_VERSION")
            ),
        });
    }
    let binding =
        binding_for(&input, identity.event.as_str(), host).map_err(HookFault::from_cli_caller)?;
    let plan = plan_lifecycle(&identity, binding.as_ref()).map_err(HookFault::caller)?;
    let DispatchPlan::Request(request) = plan else {
        return match plan {
            DispatchPlan::Ignored => Ok(HookOutput::Silent),
            DispatchPlan::Blocked(error) => Err(HookFault::lifecycle(error)),
            DispatchPlan::Request(_) => unreachable!("request was matched above"),
        };
    };
    let context = execution_context(globals).map_err(HookFault::from_cli_internal)?;
    let project_id =
        read_project_id(&context.project_id_path).map_err(HookFault::from_cli_internal)?;
    let service = DispatchService::with_context(
        DispatchStore::new(&context.runs_root),
        project_id,
        &context.workspace_root,
        &context.registry_path,
    );
    let now = context.now_unix_millis();
    match bootstrap {
        Some(BootstrapCommand::RunInit { run }) => {
            let path = context.runs_root.join(run.as_str()).join("run.json");
            match fs::symlink_metadata(&path) {
                Err(error) if error.kind() == io::ErrorKind::NotFound => {}
                Ok(_) => {
                    return Ok(HookOutput::Deny {
                        detail: format!("run `{run}` already exists; init bootstrap refused"),
                    });
                }
                Err(error) => {
                    return Ok(HookOutput::Deny {
                        detail: format!("cannot inspect selected run `{run}`: {error}"),
                    });
                }
            }
            return Ok(HookOutput::Context {
                event: "PreToolUse".into(),
                detail: format!("authorized exact native initialization for run {run}"),
            });
        }
        Some(BootstrapCommand::RunShow { run }) => {
            // Absence is a valid result for the exact read-only show command:
            // Native reports it after the hook permits execution. Corrupt or
            // unsafe selected-run state still fails closed here.
            service
                .selected_run_status(run.as_str())
                .map_err(service_fault)?;
            return Ok(HookOutput::Context {
                event: "PreToolUse".into(),
                detail: format!("authorized exact read-only inspection for run {run}"),
            });
        }
        Some(BootstrapCommand::BindRoot { run, mode }) => {
            let response = service
                .bind_root(
                    BindRootDispatchRequest {
                        schema: "shepherd.dispatch-request/1".into(),
                        run: Some(run.to_string()),
                        harness: host,
                        session_id: input.session_id.clone(),
                        role_carrier: Role::Shepherd.carrier(),
                        mode,
                        lease_ms: DEFAULT_LEASE_MS,
                    },
                    now,
                )
                .map_err(service_fault)?;
            return Ok(HookOutput::Context {
                event: "PreToolUse".into(),
                detail: format!("bound trusted root session to run {}", response.run),
            });
        }
        Some(BootstrapCommand::ProjectInit) => unreachable!("handled before discovery"),
        None => {}
    }
    match request {
        DispatchRequest::BindRoot(request) => {
            let request: BindRootDispatchRequest = decode_request(&request)?;
            let response = service.bind_root(request, now).map_err(service_fault)?;
            Ok(HookOutput::Context {
                event: input.hook_event_name,
                detail: format!("bound root session to run {}", response.run),
            })
        }
        DispatchRequest::Start(_) => Err(HookFault::UnsupportedCapability(
            "child lifecycle requires the native broker launch exchange".into(),
        )),
        DispatchRequest::Stop(request) => {
            let request = decode_request(&request)?;
            let response = service.stop(request, now).map_err(service_fault)?;
            Ok(HookOutput::Context {
                event: input.hook_event_name,
                detail: format!("stopped native dispatch {}", response.agent_id),
            })
        }
        DispatchRequest::Resume(_) => Err(HookFault::UnsupportedCapability(
            "child lifecycle requires the native broker launch exchange".into(),
        )),
        DispatchRequest::Resolve(request) => {
            let request = decode_request(&request)?;
            match service.resolve(request, now) {
                // Both tool events resolve, but only the pre-flight one gates.
                // A `PostToolUse` verdict would be advice about a call that
                // already ran, emitted under a `PreToolUse` label -- so the
                // resolution is recorded and the guard is not consulted.
                Ok(_) if input.hook_event_name == "PostToolUse" => Ok(HookOutput::Silent),
                Ok(response) => evaluate_pre_tool_use(&input, &context, &response),
                Err(error) if input.hook_event_name == "PostToolUse" => Ok(HookOutput::Context {
                    event: input.hook_event_name.clone(),
                    detail: format!("dispatch state unavailable after the tool ran: {error}"),
                }),
                Err(error) => Ok(unresolved_pre_tool_use(&input, &context, &error)),
            }
        }
    }
}

/// A process-backed Codex thread uses its real tool/turn events, not synthetic
/// SubagentStart events (whose session ID would describe a different parent).
fn run_broker_hook(
    input: &NativeHookInput,
    host: Harness,
    globals: CliGlobals,
) -> Result<HookOutput, HookFault> {
    use super::native_broker::{
        ChildEvent, NativeChildEventRequest, handle_child_event, handle_child_event_with_result,
    };
    let env = |name: &str| {
        std::env::var(name)
            .map_err(|_| HookFault::lifecycle(format!("missing Native broker correlation: {name}")))
    };
    // App-server assigns the thread after its process starts. Its actual hook
    // identity is checked against the prepared identity by the PID broker;
    // an environment placeholder must never become a host thread ID.
    let managed_thread = std::env::var("SHEPHERD_NATIVE_BROKER_CODEX_THREAD").as_deref() == Ok("1");
    let session = if managed_thread {
        input.session_id.clone()
    } else {
        env("SHEPHERD_NATIVE_BROKER_SESSION_ID")?
    };
    let agent = if managed_thread {
        input.session_id.clone()
    } else {
        env("SHEPHERD_NATIVE_BROKER_AGENT_ID")?
    };
    let agent_type = env("SHEPHERD_NATIVE_BROKER_AGENT_TYPE")?;
    validate_broker_correlation(input, host, &session, &agent, &agent_type)?;
    let run = RunId::new(env("SHEPHERD_NATIVE_BROKER_RUN")?).map_err(HookFault::caller)?;
    let agent_id = AgentId::new(agent.clone()).map_err(HookFault::caller)?;
    let context = execution_context(globals).map_err(HookFault::from_cli_internal)?;
    let store = DispatchStore::new(&context.runs_root);
    let event = |event| NativeChildEventRequest {
        schema: "shepherd.native-child-event/1".into(),
        harness: host,
        event,
        session_id: input.session_id.clone(),
        agent_id: agent.clone(),
        agent_type: agent_type.clone(),
        turn_id: input.turn_id.clone(),
        last_assistant_message: None,
    };
    match input.hook_event_name.as_str() {
        "SubagentStart" => {
            match store.load_for_run(&run, &agent_id) {
                Ok(_) => {}
                Err(crate::DispatchStoreError::UnknownRecord { .. }) => {
                    // The broker still authenticates the real process, consumes
                    // the one-shot claim, and measures the installed carrier.
                    handle_child_event(event(ChildEvent::Start))
                        .map_err(HookFault::from_cli_caller)?;
                }
                Err(error) => return Err(HookFault::lifecycle(error)),
            }
            return Ok(HookOutput::Silent);
        }
        "SubagentResume" => {
            handle_child_event(event(ChildEvent::Resume)).map_err(HookFault::from_cli_caller)?;
            return Ok(HookOutput::Silent);
        }
        "Stop" | "SubagentStop" => {
            handle_child_event_with_result(
                event(ChildEvent::Stop),
                input.last_assistant_message.clone(),
            )
            .map_err(HookFault::from_cli_caller)?;
            return Ok(HookOutput::Silent);
        }
        _ => {}
    }
    match store.load_for_run(&run, &agent_id) {
        Ok(_) => {}
        Err(crate::DispatchStoreError::UnknownRecord { .. }) => {
            handle_child_event(event(ChildEvent::Start)).map_err(HookFault::from_cli_caller)?;
        }
        Err(error) => return Err(HookFault::lifecycle(error)),
    }
    let project_id =
        read_project_id(&context.project_id_path).map_err(HookFault::from_cli_internal)?;
    let service = DispatchService::with_context(
        store,
        project_id,
        &context.workspace_root,
        &context.registry_path,
    );
    let resolution = service
        .resolve(
            crate::ResolveDispatchRequest {
                schema: "shepherd.dispatch-request/1".into(),
                run: Some(run.to_string()),
                harness: host,
                agent_id: Some(agent),
                agent_type: Some(agent_type),
                role_carrier: None,
                lane: None,
                session_id: input.session_id.clone(),
                tool_call_id: input.tool_use_id.clone(),
                tool_name: input.tool_name.clone(),
                tool_input: input.tool_input.clone(),
            },
            context.now_unix_millis(),
        )
        .map_err(service_fault)?;
    evaluate_pre_tool_use(input, &context, &resolution)
}

fn validate_broker_correlation(
    input: &NativeHookInput,
    host: Harness,
    session: &str,
    agent: &str,
    agent_type: &str,
) -> Result<(), HookFault> {
    if input.session_id != session
        || input
            .agent_id
            .as_deref()
            .is_some_and(|value| value != agent)
        || input
            .agent_type
            .as_deref()
            .is_some_and(|value| value != agent_type)
        || (host == Harness::Codex && input.turn_id.as_deref().is_none_or(str::is_empty))
        || input.shepherd_dispatch.is_some()
    {
        return Err(HookFault::lifecycle(
            "hook does not match Native broker identity and real turn",
        ));
    }
    Ok(())
}

fn execution_context(globals: CliGlobals) -> Result<ExecutionContext, CliError> {
    let cwd = std::env::current_dir()
        .map_err(|error| CliError::message(format!("cannot resolve current directory: {error}")))?;
    let mut inputs = ContextInputs::from_environment(cwd)
        .map_err(|error| CliError::message(error.to_string()))?;
    inputs.explicit_config = globals.config;
    inputs.verbosity = globals.verbosity;
    ExecutionContext::discover(inputs).map_err(|error| CliError::message(error.to_string()))
}

fn binding_for(
    input: &NativeHookInput,
    event: &str,
    host: Harness,
) -> Result<Option<DispatchBinding>, CliError> {
    let Some(raw) = input.shepherd_dispatch.as_ref() else {
        // Stop can be observed without a provider binding, but it never
        // creates a dispatch record. Child start and resume are rejected by
        // `run_hook` before this function and can only arrive through the
        // broker client contract.
        if event == "SubagentStop" {
            let Some(agent_type) = input.agent_type.as_deref() else {
                return Ok(None);
            };
            let role = parse_role(agent_type).map_err(|error| {
                CliError::message(format!("cannot resolve dispatched role: {error}"))
            })?;
            let observed = role
                .dispatch_capability_contract()
                .map_err(|error| CliError::message(error.to_string()))?
                .required;
            let mut binding = DispatchBinding::new(
                None,
                Some(role),
                None,
                None,
                Vec::new(),
                input.model.clone(),
                observed,
                capability_source(host),
                "unknown",
                input.provider_version.as_deref(),
                DEFAULT_LEASE_MS,
            )
            .map_err(|error| CliError::message(error.to_string()))?;
            binding.mode = shepherd::dispatch::RootMode::Execution;
            return Ok(Some(binding));
        }
        if matches!(event, "PreToolUse" | "PostToolUse") {
            let mut binding = DispatchBinding::root(
                Role::Shepherd,
                shepherd::dispatch::RootMode::Execution,
                DEFAULT_LEASE_MS,
            )
            .map_err(|error| CliError::message(error.to_string()))?;
            binding.tool_name = input.tool_name.clone();
            binding.tool_input = input.tool_input.clone();
            return Ok(Some(binding));
        }
        return Ok(None);
    };
    let role = raw
        .role
        .as_deref()
        .map(parse_role)
        .transpose()
        .map_err(|error| CliError::message(error.to_string()))?;
    let write_scope = raw.write_scope.clone().unwrap_or_else(|| vec!["**".into()]);
    let mut binding = DispatchBinding::new(
        raw.run
            .as_deref()
            .map(RunId::new)
            .transpose()
            .map_err(|error| CliError::message(error.to_string()))?,
        role,
        raw.lane
            .as_deref()
            .map(LaneId::new)
            .transpose()
            .map_err(|error| CliError::message(error.to_string()))?,
        raw.parent_agent_id
            .as_deref()
            .map(AgentId::new)
            .transpose()
            .map_err(|error| CliError::message(error.to_string()))?,
        write_scope,
        raw.model.clone(),
        raw.observed_capabilities.clone().unwrap_or_default(),
        raw.capability_source
            .as_deref()
            .unwrap_or(capability_source(host)),
        raw.harness_version.as_deref().unwrap_or("unknown"),
        raw.provider_version.as_deref(),
        raw.lease_ms.unwrap_or(DEFAULT_LEASE_MS),
    )
    .map_err(|error| CliError::message(error.to_string()))?;
    binding.expected_revision = raw.expected_revision.unwrap_or(1);
    binding.result_artifact = raw.result_artifact.clone();
    binding.source_agent_id = raw
        .source_agent_id
        .as_deref()
        .map(AgentId::new)
        .transpose()
        .map_err(|error| CliError::message(error.to_string()))?;
    binding.mode = raw
        .mode
        .as_deref()
        // The envelope is untrusted harness JSON, so an unparseable mode falls
        // back rather than sinking the whole envelope; it is still typed from
        // here on.
        .and_then(|mode| mode.parse().ok())
        .unwrap_or(shepherd::dispatch::RootMode::Execution);
    if matches!(event, "PreToolUse" | "PostToolUse") {
        binding.tool_name = input.tool_name.clone();
        binding.tool_input = input.tool_input.clone();
    }
    Ok(Some(binding))
}

fn parse_role(value: &str) -> shepherd::dispatch::DispatchResult<Role> {
    if value.starts_with("shepherd:") {
        Role::from_carrier(value)
    } else {
        Role::from_name(value)
    }
}

fn decode_request<T: serde::de::DeserializeOwned>(
    value: &impl serde::Serialize,
) -> Result<T, HookFault> {
    serde_json::to_value(value)
        .and_then(serde_json::from_value)
        .map_err(|error| {
            HookFault::caller(format!("cannot decode planned native dispatch: {error}"))
        })
}

fn service_fault(error: crate::DispatchServiceError) -> HookFault {
    match crate::dispatch_service::classify_dispatch_error(&error) {
        crate::dispatch_service::DispatchFaultClass::CallerPolicyViolation => {
            HookFault::CallerPolicy(error.to_string())
        }
        crate::dispatch_service::DispatchFaultClass::InvalidLifecycleCustody => {
            HookFault::InvalidCustody(error.to_string())
        }
        crate::dispatch_service::DispatchFaultClass::UnsupportedHostCapability => {
            HookFault::UnsupportedCapability(error.to_string())
        }
        crate::dispatch_service::DispatchFaultClass::InternalCorruption => {
            HookFault::InternalCorruption(error.to_string())
        }
    }
}

fn cli_error_detail(error: &CliError) -> &str {
    error
        .message_text()
        .unwrap_or("native hook rejected the request")
}

fn evaluate_pre_tool_use(
    input: &NativeHookInput,
    context: &ExecutionContext,
    resolution: &crate::DispatchResolution,
) -> Result<HookOutput, HookFault> {
    // Guard integrity is the one fault class that stays fail-closed: an engine
    // that will not load or evaluate cannot vouch for the call. The self-repair
    // exemption in `guard_unavailable` is what keeps that from bricking a
    // session whose only route back to a working ruleset is a tool call.
    let engine = match load_engine(None) {
        // `GuardEngine::new` enforces `closed-flock-only`, because the predicate
        // corpus and its examples have to keep proving what the rule does. A
        // host that has loaded project configuration applies the OPERATOR's
        // choice, and this is the only place that happens -- without it,
        // `[guard] open_flock` was a documented default (`true`) that the live
        // engine ignored in favour of the content-only default (`false`).
        Ok(engine) => engine.with_open_flock(context.config.guard.open_flock),
        Err(error) => return Ok(guard_unavailable(input, cli_error_detail(&error))),
    };
    let tool_input = match (&input.tool_name, &input.tool_input) {
        (Some(tool_name), Some(serde_json::Value::String(patch))) if tool_name == "apply_patch" => {
            serde_json::json!({"input": patch})
        }
        (_, Some(value)) => value.clone(),
        (_, None) => serde_json::Value::Object(Default::default()),
    };
    let request = serde_json::json!({
        "role": resolution.role.as_str(),
        "tool_name": input.tool_name.as_deref().unwrap_or_default(),
        "tool_input": tool_input,
        "dispatch": resolution,
    });
    let verdict = match engine.evaluate(&GuardValue::from(request)) {
        Ok(verdict) => verdict,
        Err(error) => return Ok(guard_unavailable(input, &error.to_string())),
    };
    if verdict.decision.as_str() == "allow" {
        Ok(HookOutput::Silent)
    } else {
        Ok(HookOutput::Deny {
            detail: format!(
                "caller policy violation: {}",
                verdict
                    .reason
                    .unwrap_or_else(|| "Shepherd denied this tool request".into())
            ),
        })
    }
}

/// A `PreToolUse` whose dispatch could not be resolved.
///
/// Two different situations reach here and they deserve different answers.
///
/// A GENUINE FAULT -- `EACCES`, `EIO`, a record that exists but will not parse
/// -- is always a refusal. Shepherd's own bookkeeping is broken and it cannot
/// reason about the request, so it must not permit it.
///
/// AN UNBOUND SESSION is not a fault. It is the ordinary state of every session
/// that has not run a seed, a plan, and lane binding, and refusing there means
/// the plugin governs sessions that never entered a sprint. Whether it does is
/// project policy (`[guard] dispatch_custody`), not a law: `bound` (the default)
/// enforces custody only once a session actually holds a dispatch record,
/// `always` restores the old unconditional refusal, `never` disables it.
///
/// Fail-closed remains correct for the fault case, which is the case it was
/// written for. Applying it to a session that simply never opened a sprint is
/// what made this plugin refuse ordinary work in its own repository.
fn unresolved_pre_tool_use(
    input: &NativeHookInput,
    context: &ExecutionContext,
    error: &crate::DispatchServiceError,
) -> HookOutput {
    if is_unbound_session(error)
        && !context
            .config
            .guard
            .dispatch_custody
            .enforced(/* session_is_bound = */ false)
    {
        return HookOutput::Context {
            event: input.hook_event_name.clone(),
            detail: unbound_session_reason(error),
        };
    }
    HookOutput::Deny {
        detail: unbound_session_reason(error),
    }
}

/// The reason text for a fail-closed `PreToolUse` denial, once shepherd's own
/// run bookkeeping is confirmed usable.
///
/// An absent `.root-session.<id>.json` -- `DispatchStoreError::Io` whose
/// `source` is `ErrorKind::NotFound` -- is the normal on-disk representation
/// of "this session was never bound," not a filesystem fault, and deserves a
/// remedy an operator can act on rather than a bare errno. Every other `Io`
/// variant (`EACCES`, `EIO`, a record that exists but will not parse, ...)
/// stays a genuine fault and keeps its raw `Display`, errno included, exactly
/// as before: conflating the two would send an operator chasing a security
/// incident that is not one, or bury a real one behind reassuring prose.
/// Modeled on `crates/cli/src/cmd/dispatch.rs`'s `classify_nofollow_open_error`,
/// which draws the identical ENOENT/genuine-fault line for the same reason --
/// that function classifies a different error type (`rustix::io::Errno`) over
/// a different read (the project-identity document), so it is not called
/// directly here, only its pattern.
/// Whether this resolution failure means "never bound" rather than "broken".
fn is_unbound_session(error: &crate::DispatchServiceError) -> bool {
    matches!(
        error,
        crate::DispatchServiceError::Store(crate::DispatchStoreError::Io { source, .. })
            if source.kind() == io::ErrorKind::NotFound
    ) || matches!(
        error,
        crate::DispatchServiceError::Identity(
            shepherd::dispatch::IdentityError::MissingRootBinding
        ) | crate::DispatchServiceError::Store(crate::DispatchStoreError::Identity(
            shepherd::dispatch::IdentityError::MissingRootBinding
        ))
    )
}

fn unbound_session_reason(error: &crate::DispatchServiceError) -> String {
    let is_unbound_session = matches!(
        error,
        crate::DispatchServiceError::Store(crate::DispatchStoreError::Io { source, .. })
            if source.kind() == io::ErrorKind::NotFound
    ) || matches!(
        error,
        crate::DispatchServiceError::Identity(
            shepherd::dispatch::IdentityError::MissingRootBinding
        ) | crate::DispatchServiceError::Store(crate::DispatchStoreError::Identity(
            shepherd::dispatch::IdentityError::MissingRootBinding
        ))
    );
    if is_unbound_session {
        // Spawn is the primary entry point: it selects the run, bootstraps
        // Native, plants when a seed is missing, plans, and binds. Naming
        // `start` here sent operators at the one command that REFUSES the
        // state that most often triggers this deny, because start requires a
        // run that is already planned or executing.
        "this session is not bound to a shepherd run. Run /shepherd:spawn to \
select, bootstrap, and bind one before mutating the workspace; /shepherd:start \
only resumes a run that is already planned or executing."
            .into()
    } else {
        let class = crate::dispatch_service::classify_dispatch_error(error);
        let label = match class {
            crate::dispatch_service::DispatchFaultClass::CallerPolicyViolation => {
                "caller policy violation"
            }
            crate::dispatch_service::DispatchFaultClass::InvalidLifecycleCustody => {
                "lifecycle custody invalid"
            }
            crate::dispatch_service::DispatchFaultClass::UnsupportedHostCapability => {
                "unsupported host capability"
            }
            crate::dispatch_service::DispatchFaultClass::InternalCorruption => {
                "Shepherd internal corruption"
            }
        };
        format!("{label}: rejected: {error}")
    }
}

fn guard_unavailable(_input: &NativeHookInput, detail: &str) -> HookOutput {
    HookOutput::Deny {
        detail: format!(
            "Shepherd internal corruption: guard engine unavailable: {detail}. Run `shepherd doctor`; mutation remains denied until Native state is repaired"
        ),
    }
}

fn context(event: &str, detail: &str) -> serde_json::Value {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": event,
            "additionalContext": format!("[shepherd] {detail}"),
        }
    })
}

fn deny(event: &str, detail: &str) -> serde_json::Value {
    serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": event,
            "permissionDecision": "deny",
            "permissionDecisionReason": format!("[shepherd] {detail}"),
        }
    })
}

fn block(detail: &str) -> serde_json::Value {
    serde_json::json!({
        "decision": "block",
        "reason": format!("[shepherd] {detail}"),
    })
}

fn emit_json(value: &serde_json::Value, host: Harness) -> Result<(), CliError> {
    let value = serde_json::to_string(value).map_err(|error| {
        CliError::message(format!(
            "cannot encode {} hook output: {error}",
            hook_label(host)
        ))
    })?;
    println!("{value}");
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{HookFault, service_fault};
    use crate::DispatchStoreError;
    use shepherd::{
        Harness,
        dispatch::{AgentId, RunId},
    };

    fn codex_patch_input(tool_input: serde_json::Value) -> super::NativeHookInput {
        serde_json::from_value(serde_json::json!({
            "hook_event_name": "PreToolUse",
            "session_id": "codex-envelope-test",
            "tool_name": "apply_patch",
            "tool_input": tool_input,
        }))
        .unwrap()
    }

    const CODEX_PATCH: &str =
        "*** Begin Patch\n*** Add File: report.md\n+evidence\n*** End Patch\n";

    #[test]
    fn codex_broker_hook_requires_actual_thread_and_turn_without_caller_authority() {
        let mut input = codex_patch_input(serde_json::json!({"command": CODEX_PATCH}));
        let verify = |input: &super::NativeHookInput| {
            super::validate_broker_correlation(
                input,
                Harness::Codex,
                "codex-envelope-test",
                "child",
                "worker",
            )
        };
        assert!(
            verify(&input).is_err(),
            "a turnless lifecycle event cannot activate"
        );
        input.turn_id = Some("host-turn".into());
        assert!(verify(&input).is_ok());
        input.session_id = "parent-session".into();
        assert!(
            verify(&input).is_err(),
            "parent session is not child identity"
        );
        input.session_id = "codex-envelope-test".into();
        input.agent_id = Some("sibling".into());
        assert!(verify(&input).is_err());
        input.agent_id = Some("child".into());
        input.agent_type = Some("explorer".into());
        assert!(verify(&input).is_err());
        input.agent_type = Some("worker".into());
        assert!(verify(&input).is_ok());
        input.shepherd_dispatch = Some(super::ClaudeDispatchBinding::default());
        assert!(
            verify(&input).is_err(),
            "hook JSON cannot supply launch authority"
        );
    }

    #[test]
    fn stop_payload_preserves_last_assistant_message_for_native_result_transport() {
        let input: super::NativeHookInput = serde_json::from_value(serde_json::json!({
            "hook_event_name": "Stop",
            "session_id": "codex-child",
            "turn_id": "turn-1",
            "last_assistant_message": "{\"schema\":\"shepherd.review-result/1\"}"
        }))
        .unwrap();
        assert_eq!(
            input.last_assistant_message.as_deref(),
            Some("{\"schema\":\"shepherd.review-result/1\"}")
        );
    }

    #[test]
    fn codex_command_envelope_reaches_native_write_path_derivation() {
        let workspace = tempfile::tempdir().unwrap();
        let mut input = codex_patch_input(serde_json::json!({"command": CODEX_PATCH}));
        super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
        let binding = super::binding_for(&input, "PreToolUse", shepherd::Harness::Codex)
            .unwrap()
            .unwrap();
        assert_eq!(
            binding.tool_input,
            Some(serde_json::json!({"input": CODEX_PATCH}))
        );
        let paths = crate::dispatch_scope::derive_write_paths(
            workspace.path(),
            binding.tool_name.as_deref(),
            binding.tool_input.as_ref(),
        )
        .unwrap();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0].path, "report.md");
        assert!(paths[0].inside_workspace);
    }

    #[test]
    fn claude_broker_correlation_allows_missing_turn_but_keeps_identity_bound() {
        let input: super::NativeHookInput = serde_json::from_value(serde_json::json!({
            "hook_event_name": "SubagentStart",
            "session_id": "claude-child-session",
        }))
        .unwrap();
        assert!(
            super::validate_broker_correlation(
                &input,
                Harness::ClaudeCode,
                "claude-child-session",
                "child-agent",
                "engineer",
            )
            .is_ok()
        );
        assert!(
            super::validate_broker_correlation(
                &input,
                Harness::ClaudeCode,
                "other-session",
                "child-agent",
                "engineer",
            )
            .is_err()
        );
    }

    #[test]
    fn codex_normalization_preserves_patch_bytes_and_is_idempotent() {
        let patch =
            "*** Begin Patch\r\n*** Add File: report.md\r\n+naive \u{03bb}\r\n*** End Patch\r\n";
        let mut input = codex_patch_input(serde_json::json!({"command": patch}));
        super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
        assert_eq!(input.tool_input, Some(serde_json::json!({"input": patch})));
        let once = input.tool_input.clone();
        super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
        assert_eq!(input.tool_input, once);
    }

    #[test]
    fn codex_legacy_patch_inputs_remain_unchanged() {
        for payload in [
            serde_json::json!(CODEX_PATCH),
            serde_json::json!({"input": CODEX_PATCH}),
            serde_json::json!({"patch": CODEX_PATCH}),
        ] {
            let mut input = codex_patch_input(payload.clone());
            super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
            assert_eq!(input.tool_input, Some(payload));
        }
    }

    #[test]
    fn codex_competing_patch_aliases_fail_without_mutating_input() {
        for alias in ["input", "patch"] {
            let mut payload = serde_json::json!({"command": CODEX_PATCH});
            payload[alias] = serde_json::json!(CODEX_PATCH);
            let mut input = codex_patch_input(payload.clone());
            let error =
                super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap_err();
            assert!(matches!(error, HookFault::CallerPolicy(_)));
            assert_eq!(input.tool_input, Some(payload));
        }
    }

    #[test]
    fn codex_non_string_commands_fail_without_mutating_input() {
        for command in [
            serde_json::Value::Null,
            serde_json::json!(false),
            serde_json::json!(42),
            serde_json::json!([]),
            serde_json::json!({}),
        ] {
            let payload = serde_json::json!({"command": command});
            let mut input = codex_patch_input(payload.clone());
            let error =
                super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap_err();
            assert!(matches!(error, HookFault::CallerPolicy(_)));
            assert_eq!(input.tool_input, Some(payload));
        }
    }

    #[test]
    fn codex_normalization_does_not_change_other_harnesses_or_tools() {
        for (host, tool) in [
            (shepherd::Harness::ClaudeCode, "apply_patch"),
            (shepherd::Harness::Pi, "apply_patch"),
            (shepherd::Harness::PrimeAgent, "apply_patch"),
            (shepherd::Harness::Codex, "Bash"),
            (shepherd::Harness::Codex, "Edit"),
        ] {
            let payload = serde_json::json!({"command": CODEX_PATCH});
            let mut input = codex_patch_input(payload.clone());
            input.tool_name = Some(tool.into());
            super::normalize_hook_tool_input(&mut input, host).unwrap();
            assert_eq!(input.tool_input, Some(payload));
        }
    }

    #[test]
    fn codex_unknown_fields_remain_visible_to_native_validation() {
        let workspace = tempfile::tempdir().unwrap();
        let mut input = codex_patch_input(serde_json::json!({
            "command": CODEX_PATCH,
            "unexpected": true,
        }));
        super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
        assert_eq!(
            input.tool_input,
            Some(serde_json::json!({"input": CODEX_PATCH, "unexpected": true}))
        );
        let error = crate::dispatch_scope::derive_write_paths(
            workspace.path(),
            input.tool_name.as_deref(),
            input.tool_input.as_ref(),
        )
        .unwrap_err();
        assert!(error.to_string().contains("unknown field `unexpected`"));
    }

    #[test]
    fn codex_unsafe_patch_targets_stay_rejected() {
        let workspace = tempfile::tempdir().unwrap();
        for patch in [
            "",
            "not a patch",
            "*** Add File: report.md\n+\0\n",
            "*** Add File: ../escape.md\n+no\n",
        ] {
            let mut input = codex_patch_input(serde_json::json!({"command": patch}));
            super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
            assert!(
                crate::dispatch_scope::derive_write_paths(
                    workspace.path(),
                    input.tool_name.as_deref(),
                    input.tool_input.as_ref(),
                )
                .is_err(),
                "unsafe patch accepted: {patch:?}"
            );
        }
    }

    #[test]
    fn codex_update_delete_and_move_targets_reach_native_validation() {
        let workspace = tempfile::tempdir().unwrap();
        std::fs::write(workspace.path().join("old.md"), "old\n").unwrap();
        for (patch, expected) in [
            (
                "*** Begin Patch\n*** Update File: old.md\n@@\n-old\n+new\n*** End Patch\n",
                vec!["old.md"],
            ),
            (
                "*** Begin Patch\n*** Delete File: old.md\n*** End Patch\n",
                vec!["old.md"],
            ),
            (
                "*** Begin Patch\n*** Update File: old.md\n*** Move to: moved.md\n@@\n-old\n+new\n*** End Patch\n",
                vec!["moved.md", "old.md"],
            ),
        ] {
            let mut input = codex_patch_input(serde_json::json!({"command": patch}));
            super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
            let paths = crate::dispatch_scope::derive_write_paths(
                workspace.path(),
                input.tool_name.as_deref(),
                input.tool_input.as_ref(),
            )
            .unwrap();
            assert_eq!(
                paths
                    .iter()
                    .map(|target| target.path.as_str())
                    .collect::<Vec<_>>(),
                expected
            );
            assert!(paths.iter().all(|target| target.inside_workspace));
        }
    }

    #[test]
    fn codex_absolute_outside_target_is_not_reclassified_as_workspace_owned() {
        let workspace = tempfile::tempdir().unwrap();
        let outside = tempfile::tempdir().unwrap();
        let target = outside.path().join("outside.md");
        let patch = format!(
            "*** Begin Patch\n*** Add File: {}\n+no\n*** End Patch\n",
            target.display()
        );
        let mut input = codex_patch_input(serde_json::json!({"command": patch}));
        super::normalize_hook_tool_input(&mut input, shepherd::Harness::Codex).unwrap();
        let paths = crate::dispatch_scope::derive_write_paths(
            workspace.path(),
            input.tool_name.as_deref(),
            input.tool_input.as_ref(),
        )
        .unwrap();
        assert_eq!(paths.len(), 1);
        assert!(!paths[0].inside_workspace);
    }

    #[test]
    fn hook_faults_keep_four_operator_actionable_classes() {
        let cases = [
            (
                HookFault::caller("tool payload is not authorized"),
                "caller policy violation",
            ),
            (
                HookFault::lifecycle("session record is ambiguous"),
                "lifecycle custody invalid",
            ),
            (
                HookFault::UnsupportedCapability("host has no broker correlation".into()),
                "unsupported host capability",
            ),
            (
                HookFault::InternalCorruption("dispatch index is corrupt".into()),
                "Shepherd internal corruption",
            ),
        ];
        for (fault, class) in cases {
            let detail = fault.detail();
            assert!(detail.contains(class), "{detail}");
            assert!(detail.contains("rejected"), "{detail}");
        }
    }

    #[test]
    fn missing_agent_id_record_is_lifecycle_custody_not_internal_corruption() {
        let run = RunId::new("v657").unwrap();
        let agent = AgentId::new("missing-agent").unwrap();
        let fault = service_fault(crate::DispatchServiceError::Store(
            DispatchStoreError::UnknownRecord {
                run,
                agent_id: agent,
                reason: "record is absent".into(),
            },
        ));
        assert!(fault.detail().starts_with("lifecycle custody invalid"));
    }
}