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
//! 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::{
    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;

#[derive(Clone, Copy)]
pub(super) enum HookHost {
    Claude,
    Codex,
}

impl HookHost {
    const fn capability_source(self) -> &'static str {
        match self {
            Self::Claude => "claude-native-hook",
            Self::Codex => "codex-native-hook",
        }
    }

    const fn harness(self) -> Harness {
        match self {
            Self::Claude => Harness::ClaudeCode,
            Self::Codex => Harness::Codex,
        }
    }

    const fn label(self) -> &'static str {
        match self {
            Self::Claude => "Claude",
            Self::Codex => "Codex",
        }
    }
}

#[derive(Debug, Deserialize)]
struct NativeHookInput {
    hook_event_name: String,
    session_id: 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>,
}

#[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: HookHost, 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),
        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",
                &format!("dispatch state unavailable: {}", cli_error_detail(&error)),
            ),
            host,
        ),
        Err(error) if hook_event_name == "SubagentStop" => emit_json(
            &block(&format!(
                "native lifecycle hook rejected: {}",
                cli_error_detail(&error)
            )),
            host,
        ),
        Err(error) => emit_json(
            &context(
                &hook_event_name,
                &format!(
                    "native lifecycle hook rejected: {}",
                    cli_error_detail(&error)
                ),
            ),
            host,
        ),
    }
}

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

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

fn read_input(host: HookHost) -> 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}", host.label()))
        })?;
    if bytes.len() > MAX_HOOK_BYTES {
        return Err(CliError::message(format!(
            "{} hook input exceeds 1048576-byte limit",
            host.label()
        )));
    }
    serde_json::from_slice(&bytes).map_err(|_| {
        CliError::message(format!(
            "{} hook input must be one valid RFC 8259 JSON value",
            host.label()
        ))
    })
}

fn emit_parse_error(error: CliError, host: HookHost) -> Result<(), CliError> {
    let fallback = format!("invalid {} hook input", host.label());
    // 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",
            mode @ ("planning" | "execution"),
            "--confirm",
        ] => canonical_run(run).map(|run| BootstrapCommand::BindRoot {
            run,
            mode: (*mode).into(),
        }),
        _ => None,
    }
}

fn canonical_run(value: &str) -> Option<RunId> {
    if !crate::cmd::wave_b2_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.") {
        "sprint"
    } else {
        "patch-arc"
    };
    let derived = crate::cmd::wave_b2_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'/'))
}

fn run_hook(
    input: NativeHookInput,
    host: HookHost,
    globals: CliGlobals,
) -> Result<HookOutput, CliError> {
    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.harness(),
        &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(|error| CliError::message(error.to_string()))?;
    if matches!(
        input.hook_event_name.as_str(),
        "SubagentStart" | "SubagentResume" | "SubagentStop"
    ) {
        return Err(CliError::message(
            "child lifecycle requires the native broker launch exchange",
        ));
    }
    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: "root session remains unbound until an explicit run bootstrap".into(),
        });
    }
    let binding = binding_for(&input, identity.event.as_str(), host)?;
    let plan = plan_lifecycle(&identity, binding.as_ref())
        .map_err(|error| CliError::message(error.to_string()))?;
    let DispatchPlan::Request(request) = plan else {
        return match plan {
            DispatchPlan::Ignored => Ok(HookOutput::Silent),
            DispatchPlan::Blocked(error) => Err(CliError::message(error.to_string())),
            DispatchPlan::Request(_) => unreachable!("request was matched above"),
        };
    };
    let context = execution_context(globals)?;
    let project_id = read_project_id(&context.project_id_path)?;
    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_error)?;
            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.harness(),
                        session_id: input.session_id.clone(),
                        role_carrier: Role::Shepherd.carrier(),
                        mode,
                        lease_ms: DEFAULT_LEASE_MS,
                    },
                    now,
                )
                .map_err(service_error)?;
            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_error)?;
            Ok(HookOutput::Context {
                event: input.hook_event_name,
                detail: format!("bound root session to run {}", response.run),
            })
        }
        DispatchRequest::Start(_) => Err(CliError::message(
            "child lifecycle requires the native broker launch exchange",
        )),
        DispatchRequest::Stop(request) => {
            let request = decode_request(&request)?;
            let response = service.stop(request, now).map_err(service_error)?;
            Ok(HookOutput::Context {
                event: input.hook_event_name,
                detail: format!("stopped native dispatch {}", response.agent_id),
            })
        }
        DispatchRequest::Resume(_) => Err(CliError::message(
            "child lifecycle requires the native broker launch exchange",
        )),
        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, &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)),
            }
        }
    }
}

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: HookHost,
) -> 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,
                host.capability_source(),
                "unknown",
                input.provider_version.as_deref(),
                DEFAULT_LEASE_MS,
            )
            .map_err(|error| CliError::message(error.to_string()))?;
            binding.mode = "execution".into();
            return Ok(Some(binding));
        }
        if matches!(event, "PreToolUse" | "PostToolUse") {
            let mut binding = DispatchBinding::root(Role::Shepherd, "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(host.capability_source()),
        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.clone().unwrap_or_else(|| "execution".into());
    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, CliError> {
    serde_json::to_value(value)
        .and_then(serde_json::from_value)
        .map_err(|error| {
            CliError::message(format!("cannot decode planned native dispatch: {error}"))
        })
}

fn service_error(error: crate::DispatchServiceError) -> CliError {
    CliError::message(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,
    resolution: &crate::DispatchResolution,
) -> Result<HookOutput, CliError> {
    // 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) {
        Ok(engine) => engine,
        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: verdict
                .reason
                .unwrap_or_else(|| "Shepherd denied this tool request".into()),
        })
    }
}

fn unresolved_pre_tool_use(
    _input: &NativeHookInput,
    _context: &ExecutionContext,
    error: &crate::DispatchServiceError,
) -> HookOutput {
    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.
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 {
        error.to_string()
    }
}

fn guard_unavailable(_input: &NativeHookInput, detail: &str) -> HookOutput {
    HookOutput::Deny {
        detail: format!("guard engine unavailable: {detail}"),
    }
}

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: HookHost) -> Result<(), CliError> {
    let value = serde_json::to_string(value).map_err(|error| {
        CliError::message(format!(
            "cannot encode {} hook output: {error}",
            host.label()
        ))
    })?;
    println!("{value}");
    Ok(())
}