shepherd-core 6.6.1

The harness-agnostic shepherd engine: domain types, configuration schema, and run state. Knows nothing about any CLI, harness, or process.
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
/*
    Appellation: guard-engine <module>
    Created At: 2026.08.14:00:00:00
    Contrib: @FL03
*/
//! Pure request mapping and predicate evaluation.

use alloc::{
    collections::BTreeMap,
    format,
    string::{String, ToString},
    vec::Vec,
};

use super::{
    GuardError, GuardValue, PredicateDoc, RoleFact, Rule, Verdict, extract_git_subcommands,
};

type Context = BTreeMap<String, GuardValue>;
type HaltTable = BTreeMap<(String, String), Option<String>>;

const WRITE_TOOL_NAMES: &[&str] = &["Write", "Edit", "apply_patch"];
const DISPATCH_TOOL_NAMES: &[&str] = &["Agent", "Workflow"];
const GIT_INTEGRATE_VERBS: &[&str] = &["rebase", "merge", "cherry-pick", "worktree"];
const GIT_ALL_WRITE_VERBS: &[&str] = &[
    "add",
    "rm",
    "mv",
    "commit",
    "commit-tree",
    "merge",
    "merge-file",
    "merge-index",
    "rebase",
    "reset",
    "restore",
    "checkout",
    "checkout-index",
    "switch",
    "stash",
    "clean",
    "cherry-pick",
    "revert",
    "push",
    "pull",
    "fetch",
    "clone",
    "init",
    "gc",
    "prune",
    "repack",
    "apply",
    "am",
    "worktree",
    "remote",
    "tag",
    "branch",
    "config",
    "notes",
    "submodule",
    "update-ref",
    "update-index",
    "update-server-info",
    "replace",
    "filter-branch",
    "filter-repo",
    "fast-import",
    "sparse-checkout",
    "bisect",
    "format-patch",
    "request-pull",
    "write-tree",
    "hash-object",
    "symbolic-ref",
    "read-tree",
    "reflog",
    "send-pack",
    "receive-pack",
    "http-push",
    "http-fetch",
    "credential",
    "maintenance",
    "mergetool",
    "difftool",
    "commit-graph",
    "multi-pack-index",
    "pack-refs",
    "mktree",
    "mktag",
    "pack-objects",
    "unpack-objects",
    "prune-packed",
    "fsck",
];

/// A loaded predicate corpus and its role facts.
#[derive(Clone, Debug)]
pub struct GuardEngine {
    predicates: BTreeMap<String, PredicateDoc>,
    role_facts: BTreeMap<String, RoleFact>,
    halt_table: HaltTable,
    /// Project policy for `closed-flock-only` (`[guard] open_flock`). An engine
    /// built from content alone ENFORCES the rule, so the predicate corpus and
    /// its examples keep proving what the rule does. A host that has loaded
    /// project configuration applies the operator's choice through
    /// [`GuardEngine::with_open_flock`]; the shipped default is `true`.
    open_flock: bool,
}

impl GuardEngine {
    /// Build an engine from already parsed, caller-owned content.
    pub fn new(
        predicates: Vec<PredicateDoc>,
        role_facts: Vec<RoleFact>,
    ) -> Result<Self, GuardError> {
        let predicates: BTreeMap<_, _> = predicates
            .into_iter()
            .map(|predicate| (predicate.id.clone(), predicate))
            .collect();
        let role_facts: BTreeMap<_, _> = role_facts
            .into_iter()
            .map(|fact| (fact.role.clone(), fact))
            .collect();
        let halt_table = harvest_halt_codes(&predicates, &role_facts)?;

        Ok(Self {
            predicates,
            role_facts,
            halt_table,
            open_flock: false,
        })
    }

    /// Evaluate a normalized request or raw tool call.
    ///
    /// Raw calls validate and classify `tool_name` and `tool_input` before a
    /// mapped operation consumes `role`. Bash command shape is always required;
    /// opaque effects under native dispatch facts fail closed without trying to
    /// infer filesystem targets from shell text.
    ///
    /// # Errors
    ///
    /// Request-shape defects are verdicts rather than engine errors. The result
    /// boundary is retained for unrecoverable typed-engine failures.
    pub fn evaluate(&self, request: &GuardValue) -> Result<Verdict, GuardError> {
        let GuardValue::Object(payload) = request else {
            return Ok(Verdict::unresolved(
                "request body is not a JSON object",
                &["body"],
            ));
        };

        if payload.contains_key("predicate") {
            return Ok(self.evaluate_normalized(payload));
        }

        if payload.contains_key("tool_name") {
            Ok(self.evaluate_tool_call(payload))
        } else {
            Ok(Verdict::unresolved(
                "request carries neither `predicate` nor `tool_name`",
                &["predicate", "tool_name"],
            ))
        }
    }

    /// The parsed predicate identified by `id`.
    pub fn predicate(&self, id: &str) -> Option<&PredicateDoc> {
        self.predicates.get(id)
    }

    /// Iterate over loaded predicates in stable identifier order.
    pub fn predicates(&self) -> impl Iterator<Item = (&str, &PredicateDoc)> {
        self.predicates
            .iter()
            .map(|(id, predicate)| (id.as_str(), predicate))
    }

    /// The parsed role identified by `id`.
    pub fn role_fact(&self, id: &str) -> Option<&RoleFact> {
        self.role_facts.get(id)
    }

    fn evaluate_normalized(&self, payload: &Context) -> Verdict {
        let predicate_id = payload.get("predicate").and_then(GuardValue::as_str);
        let Some(predicate_id) = predicate_id.filter(|value| !value.is_empty()) else {
            return Verdict::unresolved("missing `predicate`", &["predicate"]);
        };
        if !self.predicates.contains_key(predicate_id) {
            return Verdict::unresolved(
                format!("no such predicate `{predicate_id}`"),
                &["predicate"],
            );
        }
        let action = payload.get("action").and_then(GuardValue::as_str);
        let Some(action) = action.filter(|value| !value.is_empty()) else {
            return Verdict::unresolved("missing `action`", &["action"]);
        };
        let Some(role) = payload.get("role").filter(|value| !value.is_null()) else {
            return Verdict::unresolved(
                "missing `role` -- cannot identify the acting role",
                &["role"],
            );
        };
        let context = match payload.get("context") {
            None | Some(GuardValue::Null) => BTreeMap::new(),
            Some(GuardValue::Object(context)) => context.clone(),
            Some(_) => {
                return Verdict::unresolved("`context` must be a JSON object", &["context"]);
            }
        };

        if predicate_id == "dispatch-scope"
            && action == "dispatch"
            && let Some(target) = context.get("target_role").and_then(GuardValue::as_str)
            && let Some(verdict) = native_dispatch_edge_verdict(role, target)
        {
            return verdict;
        }
        self.decide(predicate_id, action, role, &context)
    }

    fn evaluate_tool_call(&self, payload: &Context) -> Verdict {
        let tool_name = payload.get("tool_name").and_then(GuardValue::as_str);
        let Some(tool_name) = tool_name.filter(|value| !value.is_empty()) else {
            return Verdict::unresolved("missing `tool_name`", &["tool_name"]);
        };
        let empty = BTreeMap::new();
        let tool_input = match payload.get("tool_input") {
            None | Some(GuardValue::Null) => &empty,
            Some(GuardValue::Object(value)) => value,
            Some(_) => {
                return Verdict::unresolved("`tool_input` must be a JSON object", &["tool_input"]);
            }
        };
        let role = payload.get("role");
        if WRITE_TOOL_NAMES.contains(&tool_name) {
            self.evaluate_write_tool(role, tool_input, payload.get("dispatch"))
        } else if tool_name == "Bash" {
            self.evaluate_bash_tool(role, tool_input, payload.get("dispatch"))
        } else if DISPATCH_TOOL_NAMES.contains(&tool_name) {
            self.evaluate_dispatch_tool(role, tool_input, tool_name)
        } else {
            Verdict::unresolved(
                format!("no (predicate, action) mapping known for tool `{tool_name}`"),
                &["tool_name mapping"],
            )
        }
    }

    fn evaluate_write_tool(
        &self,
        role: Option<&GuardValue>,
        tool_input: &Context,
        dispatch: Option<&GuardValue>,
    ) -> Verdict {
        let Some(role) = role.filter(|value| !value.is_null()) else {
            return Verdict::unresolved(
                "missing `role` -- cannot identify the acting role",
                &["role"],
            );
        };
        let fact = role
            .as_str()
            .and_then(|role_name| self.role_facts.get(role_name));
        let Some(fact) = fact else {
            return Verdict::unresolved(
                format!("unknown role `{}`", compatibility_display(role)),
                &["role_facts"],
            );
        };
        if !fact.permits_structured_write() && !fact.has_capability("report-write") {
            return Verdict::deny(
                "write-boundary",
                "role-write-eligibility",
                None,
                "role holds no write capability at all",
            );
        }
        let Some(GuardValue::Object(dispatch)) = dispatch else {
            return Verdict::unresolved(
                "native dispatch write-scope resolution is missing",
                &["dispatch.path_in_write_scope"],
            );
        };
        if dispatch.get("schema").and_then(GuardValue::as_str)
            != Some("shepherd.identity-resolution/1")
            || dispatch.get("role").and_then(GuardValue::as_str) != role.as_str()
        {
            return Verdict::unresolved(
                "native dispatch resolution does not match the acting role",
                &["dispatch.schema", "dispatch.role"],
            );
        }
        let write_paths = match dispatch.get("write_paths") {
            Some(GuardValue::Array(paths))
                if !paths.is_empty()
                    && paths
                        .iter()
                        .all(|path| path.as_str().is_some_and(|path| !path.is_empty())) =>
            {
                paths
            }
            _ => {
                return Verdict::unresolved(
                    "native dispatch resolution contains no validated write paths",
                    &["dispatch.write_paths"],
                );
            }
        };
        let path_in_scope = match dispatch.get("path_in_write_scope") {
            Some(GuardValue::Bool(value)) => *value,
            _ => {
                return Verdict::unresolved(
                    "native dispatch resolution contains no write-scope fact",
                    &["dispatch.path_in_write_scope"],
                );
            }
        };
        if !fact.permits_structured_write() && fact.has_capability("report-write") {
            let report_path = match dispatch.get("write_scope") {
                Some(GuardValue::Array(scope)) if scope.len() == 1 => {
                    scope[0].as_str().filter(|path| {
                        !path.is_empty()
                            && !path
                                .chars()
                                .any(|character| matches!(character, '*' | '?' | '[' | ']'))
                    })
                }
                _ => None,
            };
            let Some(report_path) = report_path else {
                return Verdict::unresolved(
                    "report-write requires one exact dispatch-declared output path",
                    &["dispatch.write_scope"],
                );
            };
            if write_paths.len() != 1 || write_paths[0].as_str() != Some(report_path) {
                return Verdict::unresolved(
                    "report-write target does not match its one declared output path",
                    &["dispatch.write_scope", "dispatch.write_paths"],
                );
            }
        }
        if let Some(path) = ["file_path", "path"]
            .into_iter()
            .find_map(|key| tool_input.get(key).and_then(GuardValue::as_str))
            .filter(|path| !path.starts_with('/'))
            && !write_paths
                .iter()
                .any(|resolved| resolved.as_str() == Some(path))
        {
            return Verdict::unresolved(
                "native dispatch write paths do not match the tool target",
                &["dispatch.write_paths"],
            );
        }
        let effective_write_eligibility =
            fact.permits_structured_write() || fact.has_capability("report-write");
        self.decide(
            "write-boundary",
            "fs.write",
            role,
            &BTreeMap::from([
                (
                    String::from("write_eligible"),
                    GuardValue::from(effective_write_eligibility),
                ),
                (
                    String::from("path_in_dispatch_write_scope"),
                    GuardValue::from(path_in_scope),
                ),
            ]),
        )
    }

    fn evaluate_bash_tool(
        &self,
        role: Option<&GuardValue>,
        tool_input: &Context,
        dispatch: Option<&GuardValue>,
    ) -> Verdict {
        if dispatch.is_none() || dispatch.is_some_and(GuardValue::is_null) {
            return Verdict::deny(
                "identity-resolution",
                "missing-native-dispatch",
                Some(String::from("NATIVE-IDENTITY-REQUIRED")),
                "PreToolUse Bash requires a native-issued dispatch record; caller role and shell text are not authority",
            );
        }
        let Some(command) = tool_input
            .get("command")
            .and_then(GuardValue::as_str)
            .filter(|command| !command.is_empty())
        else {
            return Verdict::unresolved(
                "missing or invalid Bash `command`",
                &["tool_input.command"],
            );
        };

        let bounded_dispatch = match dispatch {
            None | Some(GuardValue::Null) => false,
            Some(GuardValue::Object(native)) => {
                let Some(role) = role.filter(|value| !value.is_null()) else {
                    return Verdict::unresolved(
                        "missing `role` -- cannot identify the acting role",
                        &["role"],
                    );
                };
                let Some(role_name) = role.as_str() else {
                    return Verdict::unresolved(
                        format!("unknown role `{}`", compatibility_display(role)),
                        &["role"],
                    );
                };
                if native.get("schema").and_then(GuardValue::as_str)
                    != Some("shepherd.identity-resolution/1")
                    || native.get("role").and_then(GuardValue::as_str) != Some(role_name)
                {
                    return Verdict::unresolved(
                        "native dispatch resolution does not match the acting role",
                        &["dispatch.schema", "dispatch.role"],
                    );
                }
                if !self.role_facts.contains_key(role_name) {
                    return Verdict::unresolved(
                        format!("unknown role `{role_name}`"),
                        &["role_facts"],
                    );
                }
                let has_child_agent_id = match native.get("agent_id") {
                    Some(GuardValue::Null) => false,
                    Some(GuardValue::String(value)) if !value.is_empty() => true,
                    _ => {
                        return Verdict::unresolved(
                            "native dispatch `agent_id` must be null or a non-empty string",
                            &["dispatch.agent_id"],
                        );
                    }
                };
                let has_named_lane = match native.get("lane") {
                    Some(GuardValue::Null) => false,
                    Some(GuardValue::String(value)) if !value.is_empty() => true,
                    _ => {
                        return Verdict::unresolved(
                            "native dispatch `lane` must be null or a non-empty string",
                            &["dispatch.lane"],
                        );
                    }
                };
                let root_role = matches!(role_name, "shepherd" | "planter");
                let root_shape = !has_child_agent_id && !has_named_lane;
                if !has_child_agent_id && has_named_lane {
                    return Verdict::unresolved(
                        "native child lane requires an agent identity",
                        &["dispatch.agent_id", "dispatch.lane"],
                    );
                }
                if root_role != root_shape {
                    return Verdict::unresolved(
                        "native root and child dispatch facts disagree",
                        &["dispatch.role", "dispatch.agent_id", "dispatch.lane"],
                    );
                }
                let exact_root = root_role && root_shape;
                if exact_root {
                    let root_mode = native
                        .get("mode")
                        .and_then(GuardValue::as_str)
                        .is_some_and(|mode| matches!(mode, "planting" | "planning" | "execution"));
                    let root_scope = match (role_name, native.get("write_scope")) {
                        ("shepherd", Some(GuardValue::Array(scope))) => {
                            scope.len() == 1 && scope[0].as_str() == Some("*.md")
                        }
                        ("planter", Some(GuardValue::Array(scope))) if scope.len() == 2 => {
                            let mesh = scope[0]
                                .as_str()
                                .and_then(|path| path.strip_suffix("/mesh.md"));
                            let seed = scope[1]
                                .as_str()
                                .and_then(|path| path.strip_suffix("/seed.md"));
                            mesh.is_some_and(|prefix| {
                                prefix.starts_with(".shepherd/runs/v") && seed == Some(prefix)
                            })
                        }
                        _ => false,
                    };
                    if !root_mode || !root_scope {
                        return Verdict::unresolved(
                            "native root dispatch resolution is incomplete",
                            &["dispatch.mode", "dispatch.write_scope"],
                        );
                    }
                }
                !exact_root
            }
            Some(_) => {
                return Verdict::unresolved(
                    "native dispatch resolution must be a JSON object",
                    &["dispatch"],
                );
            }
        };

        let subcommands = extract_git_subcommands(command);
        let action = if subcommands
            .iter()
            .any(|subcommand| GIT_INTEGRATE_VERBS.contains(&subcommand.as_str()))
        {
            Some("vcs.integrate")
        } else if subcommands.iter().any(|subcommand| {
            GIT_ALL_WRITE_VERBS.contains(&subcommand.as_str())
                && !GIT_INTEGRATE_VERBS.contains(&subcommand.as_str())
        }) {
            Some("vcs.write")
        } else {
            None
        };

        if let Some(action) = action {
            let Some(role) = role.filter(|value| !value.is_null()) else {
                return Verdict::unresolved(
                    "missing `role` -- cannot identify the acting role",
                    &["role"],
                );
            };
            let tier = role.as_str().and_then(role_tier);
            let Some(tier) = tier else {
                return Verdict::unresolved(
                    format!("unknown role `{}`", compatibility_display(role)),
                    &["role"],
                );
            };
            return self.decide(
                "git-custody",
                action,
                role,
                &BTreeMap::from([(String::from("role_tier"), GuardValue::from(tier))]),
            );
        }

        let non_writable_role = role
            .and_then(GuardValue::as_str)
            .and_then(|role| self.role_facts.get(role))
            .is_some_and(|fact| !fact.write_eligible);
        if bounded_dispatch || non_writable_role {
            return Verdict::deny(
                "write-boundary",
                "opaque-shell-effect",
                None,
                "opaque Bash effects require an unbounded native authorization; bounded or non-writable dispatch facts fail closed without shell-text inference",
            );
        }

        Verdict::allow()
    }

    fn evaluate_dispatch_tool(
        &self,
        role: Option<&GuardValue>,
        tool_input: &Context,
        tool_name: &str,
    ) -> Verdict {
        let raw_target = ["subagent_type", "target_role", "role"]
            .into_iter()
            .filter_map(|key| tool_input.get(key))
            .find(|value| value.is_truthy())
            .and_then(GuardValue::as_str)
            .filter(|value| !value.is_empty());
        let target = raw_target
            .map(carrier_role)
            .filter(|value| !value.is_empty());
        // `Workflow` fans out inside its own script, so its `tool_input` carries
        // no single target role. `Agent` always carries one, so a missing target
        // there is still unresolved.
        if target.is_none() && tool_name != "Workflow" {
            return Verdict::unresolved(
                "cannot determine the dispatch target role from `tool_input`",
                &["tool_input.subagent_type"],
            );
        }
        let Some(role) = role.filter(|value| !value.is_null()) else {
            return Verdict::unresolved(
                "missing `role` -- cannot identify the dispatching role",
                &["role"],
            );
        };
        let tier = role.as_str().map(carrier_role).and_then(role_tier);
        let Some(tier) = tier else {
            return Verdict::unresolved(
                format!("unknown role `{}`", compatibility_display(role)),
                &["role"],
            );
        };
        // Only a target addressed to THIS flock is inside the predicate's
        // jurisdiction. A host agent (`general-purpose`, `Explore`) or another
        // plugin's agent is not a tenth flock role -- it is not a role at all,
        // and refusing it would annex the harness's own dispatch primitive on
        // behalf of a sprint contract it was never part of. Target-keyed rules
        // therefore see no `target_role` for such a dispatch and cannot fire,
        // while every dispatcher-keyed rule (notably
        // `implementer-roles-never-dispatch`) still evaluates unchanged: an
        // implementer may not fan out to anything, flock or not.
        let governed = match (raw_target, target) {
            (Some(raw), Some(stripped)) if self.governs_target(raw, stripped) => Some(stripped),
            _ => None,
        };
        if let Some(target_role) = governed
            && let Some(verdict) = native_dispatch_edge_verdict(role, target_role)
        {
            return verdict;
        }
        // Two dispatch-scope rules key on the TARGET, so an undeclared target
        // makes them unenforceable. That is fine for a role no target-keyed rule
        // restricts -- there is nothing to evade. It is NOT fine for a role that
        // one does: a lane lead denied `engineer` by name could otherwise obtain
        // it by writing the dispatch as a script string, which is a bypass by
        // payload shape rather than by permission. Such a role must declare.
        if target.is_none() && restricted_by_target_rule(tier) {
            return Verdict::deny(
                "dispatch-scope",
                "plan-authorship-and-gating-are-root-tier-exclusive",
                Some(String::from("WRONG-TIER-DISPATCH")),
                "a lane-executor lead must DECLARE the roles it dispatches: pass \
`target_role` (or `subagent_type`) in `tool_input`. Two dispatch-scope rules key on the \
target, so an undeclared target would let a refused dispatch through by payload shape.",
            );
        }
        let mut context =
            BTreeMap::from([(String::from("dispatcher_tier"), GuardValue::from(tier))]);
        if let Some(target) = target {
            context.insert(String::from("target_role"), GuardValue::from(target));
        }
        // The raw address is what carries jurisdiction: `shepherd:` says the
        // dispatch was addressed to this flock. `target_role` is the stripped
        // id the tier rules match on, so both are needed and they are not the
        // same value.
        //
        // Under `open_flock` the address is withheld, which is what makes
        // `closed-flock-only` unable to fire: the rule needs a carrier address
        // to identify an invented tenth role, and without one there is nothing
        // for it to refuse. Every other rule keys on `target_role` or on the
        // dispatcher and is unaffected, so the tier rules keep working.
        if let Some(raw) = raw_target.filter(|_| !self.open_flock) {
            context.insert(String::from("target_address"), GuardValue::from(raw));
        }
        self.decide("dispatch-scope", "dispatch", role, &context)
    }

    /// Apply the project's `[guard] open_flock` choice.
    ///
    /// `true` (the shipped config default) stops `closed-flock-only` from
    /// firing on a live dispatch, so a session may use the agents its harness
    /// ships. `false` enforces the closed flock for the whole sprint.
    #[must_use]
    pub fn with_open_flock(mut self, open_flock: bool) -> Self {
        self.open_flock = open_flock;
        self
    }

    /// Whether a dispatch target is addressed to THIS flock.
    ///
    /// Two spellings count: an explicit carrier address (`shepherd:discovery`),
    /// and a bare flock role id (`discovery`) for harnesses that do not prefix.
    /// Anything else -- a host agent, another plugin's agent -- is outside this
    /// predicate's jurisdiction. Used by the native edge rules, which key on a
    /// role id and would otherwise fire on a host agent that merely happens to
    /// share a flock role's name.
    fn governs_target(&self, raw: &str, stripped: &str) -> bool {
        raw.starts_with("shepherd:") || self.role_facts.contains_key(stripped)
    }

    fn decide(
        &self,
        predicate_id: &str,
        action: &str,
        role: &GuardValue,
        context: &Context,
    ) -> Verdict {
        let fired = match evaluate_predicate(
            predicate_id,
            action,
            context,
            &self.predicates,
            &self.role_facts,
        ) {
            Ok(fired) => fired,
            Err(error) => return Verdict::unresolved(error.to_string(), &[]),
        };
        if fired.is_empty() {
            return Verdict::allow();
        }

        let halt_code = self.resolve_halt_code(predicate_id, &fired, context, role);
        let predicate = &self.predicates[predicate_id];
        let descriptions: Vec<&str> = predicate
            .rules
            .iter()
            .filter(|rule| fired.iter().any(|id| id == &rule.id))
            .map(|rule| rule.description.as_str())
            .collect();
        let rule_ids = fired.join(",");
        let reason = if descriptions.is_empty() {
            format!("{predicate_id}: rule(s) {} fired", fired.join(", "))
        } else {
            descriptions.join(" / ")
        };
        Verdict::deny(predicate_id, rule_ids, halt_code, reason)
    }

    fn resolve_halt_code(
        &self,
        predicate_id: &str,
        fired: &[String],
        context: &Context,
        role: &GuardValue,
    ) -> Option<String> {
        if predicate_id == "write-boundary" {
            let fact = role.as_str().and_then(|role| self.role_facts.get(role));
            if fact.is_some_and(|fact| {
                fact.capabilities
                    .iter()
                    .any(|capability| capability == "report-write")
            }) {
                return Some(String::from("DISCOVERY-WRITE-PATH"));
            }
            if context
                .get("write_eligible")
                .is_some_and(GuardValue::is_true)
            {
                return Some(String::from("SCOPE OVERFLOW"));
            }
            return None;
        }
        if fired.len() == 1 {
            return self
                .halt_table
                .get(&(String::from(predicate_id), fired[0].clone()))
                .cloned()
                .flatten();
        }
        None
    }
}

/// Strip shepherd's own carrier prefix from a dispatch target.
///
/// A host names a plugin agent `<plugin>:<agent>`, so Claude Code sends
/// `shepherd:conductor` where `role_facts` is keyed on the bare `conductor`.
/// Without this, every dispatch to a real flock role was refused as off-flock
/// and the plugin could not dispatch through its own guard. Only shepherd's
/// prefix is stripped: another plugin's `coder` is not this flock's `coder`.
fn native_dispatch_edge_verdict(role: &GuardValue, target_role: &str) -> Option<Verdict> {
    let dispatcher = role.as_str().map(carrier_role);
    let target = carrier_role(target_role);
    if target == "discovery" && dispatcher != Some("engineer") {
        return Some(Verdict::deny(
            "dispatch-scope",
            "engineer-only-discovery",
            Some(String::from("WRONG-TIER-DISPATCH")),
            "Discovery may be dispatched only by the Engineer orientation owner; external research is not a Conductor capability.",
        ));
    }
    None
}

/// Whether any `dispatch-scope` rule restricts this tier BY TARGET.
///
/// Only the lane lead is: `plan-authorship-and-gating-are-root-tier-exclusive`
/// forbids it `engineer`, `critic`, and another `conductor`. Root has no target-keyed restriction it
/// could evade, and an implementer is refused by acting role alone, which no
/// payload shape can hide.
fn restricted_by_target_rule(tier: &str) -> bool {
    tier == "lane-lead"
}

fn carrier_role(value: &str) -> &str {
    value.strip_prefix("shepherd:").unwrap_or(value)
}

fn role_tier(role: &str) -> Option<&'static str> {
    match role {
        "shepherd" => Some("root"),
        "planter" => Some("meta"),
        "conductor" => Some("lane-lead"),
        "engineer" => Some("plan-author"),
        "critic" | "coder" | "auditor" | "discovery" | "worker" => Some("implementer"),
        _ => None,
    }
}

fn compatibility_display(value: &GuardValue) -> String {
    match value {
        GuardValue::Null => String::from("None"),
        GuardValue::Bool(true) => String::from("True"),
        GuardValue::Bool(false) => String::from("False"),
        GuardValue::Integer(value) => value.to_string(),
        GuardValue::Unsigned(value) => value.to_string(),
        GuardValue::Float(value) => value.to_string(),
        GuardValue::String(value) => value.clone(),
        GuardValue::Array(_) => String::from("[...]"),
        GuardValue::Object(_) => String::from("{...}"),
    }
}

fn harvest_halt_codes(
    predicates: &BTreeMap<String, PredicateDoc>,
    role_facts: &BTreeMap<String, RoleFact>,
) -> Result<HaltTable, GuardError> {
    let mut halt_table = BTreeMap::new();
    for (predicate_id, predicate) in predicates {
        for example in &predicate.examples {
            if example.result != "deny" {
                continue;
            }
            let fired = evaluate_predicate(
                predicate_id,
                &example.action,
                &example.flattened_context(),
                predicates,
                role_facts,
            )?;
            if fired.len() != 1 {
                continue;
            }
            let key = (predicate_id.clone(), fired[0].clone());
            if let Some(existing) = halt_table.get(&key)
                && existing != &example.halt_code
            {
                return Err(GuardError::Predicate(format!(
                    "ambiguous halt code for ({:?}, {:?}): {:?} vs {:?} (example `{}`)",
                    key.0, key.1, existing, example.halt_code, example.name
                )));
            }
            halt_table.insert(key, example.halt_code.clone());
        }
    }
    Ok(halt_table)
}

fn evaluate_predicate(
    predicate_id: &str,
    action: &str,
    context: &Context,
    predicates: &BTreeMap<String, PredicateDoc>,
    role_facts: &BTreeMap<String, RoleFact>,
) -> Result<Vec<String>, GuardError> {
    let predicate = predicates
        .get(predicate_id)
        .ok_or_else(|| GuardError::Predicate(format!("no such predicate `{predicate_id}`")))?;
    let applicable: Vec<&Rule> = predicate
        .rules
        .iter()
        .filter(|rule| rule.action == action)
        .collect();
    if applicable.is_empty() {
        return Err(GuardError::Predicate(format!(
            "predicate `{predicate_id}` has no rule scoped to action `{action}`"
        )));
    }

    let mut fired = Vec::new();
    for rule in applicable {
        if effect_fires(rule, context, role_facts).map_err(|effect| {
            GuardError::Predicate(format!(
                "no handler for effect `{effect}` (predicate `{predicate_id}`, rule `{}`)",
                rule.id
            ))
        })? {
            fired.push(rule.id.clone());
        }
    }
    Ok(fired)
}

fn effect_fires<'a>(
    rule: &'a Rule,
    context: &Context,
    role_facts: &BTreeMap<String, RoleFact>,
) -> Result<bool, &'a str> {
    let value = match rule.effect.as_str() {
        "deny_if_false" => {
            context
                .get("write_eligible")
                .is_some_and(GuardValue::is_false)
                && !context
                    .get("path_in_dispatch_write_scope")
                    .is_some_and(GuardValue::is_true)
        }
        "deny_if_path_outside_scope" => context
            .get("path_in_dispatch_write_scope")
            .is_some_and(GuardValue::is_false),
        "allow_if_no_hit" => false,
        "deny_if_hit_without_justification" => {
            context.get("dedup_hit").is_some_and(GuardValue::is_true)
                && !context
                    .get("justification_present")
                    .is_some_and(GuardValue::is_true)
        }
        // Fires only for a dispatch ADDRESSED TO THIS FLOCK that names something
        // outside it -- i.e. an invented tenth role such as `shepherd:reviewer`.
        // A target with no carrier address is a host agent or another plugin's
        // agent; it is not a role, and refusing it would claim authority over
        // the harness's own dispatch primitive. The address is read from
        // `target_address` when present and falls back to `target_role`, so a
        // predicate example that carries only the raw spelling evaluates the
        // same way a live hook payload does.
        "deny_if_target_outside_flock" => {
            let role_id = context.get("target_role").and_then(GuardValue::as_str);
            let address = context
                .get("target_address")
                .and_then(GuardValue::as_str)
                .or(role_id);
            matches!((address, role_id), (Some(address), Some(role_id))
                if address.starts_with("shepherd:") && !role_facts.contains_key(role_id))
        }
        // `planter` and `shepherd` are profiles the ROOT session adopts, not
        // subagents. This keys on the TARGET and so refuses everyone, root
        // included -- distinct from the tier rule below, which only stops a
        // lane lead reaching upward. A root that needs the planter perspective
        // adopts it in place; dispatching one would mint a second root for a
        // session that already has one.
        "deny_if_target_is_root_profile" => context
            .get("target_role")
            .and_then(GuardValue::as_str)
            .is_some_and(|target| matches!(target, "planter" | "shepherd")),
        "deny_if_dispatcher_is_lane_lead_and_target_is_plan_or_gate_role" => {
            context.get("dispatcher_tier").and_then(GuardValue::as_str) == Some("lane-lead")
                // `planter` holds the operator channel (`AskUserQuestion`) and
                // `shepherd` is the root orchestrator itself -- a lane lead
                // reaching either inverts the dispatch tier the same way
                // reaching `engineer`/`critic` or another `conductor` does (#323).
                // `planter` and `shepherd` are NOT listed here any more.
                // `root-profiles-are-never-dispatched` owns them, for everyone
                // rather than just for a lane lead. Naming them in both rules
                // made both fire, which collapsed the halt code to None and
                // left the clearer diagnostic unreachable -- two authorities
                // for one refusal, which is the shape this project subtracts.
                && matches!(
                    context.get("target_role").and_then(GuardValue::as_str),
                    Some("engineer" | "critic" | "conductor")
                )
        }
        "deny_if_dispatcher_is_implementer" => {
            context.get("dispatcher_tier").and_then(GuardValue::as_str) == Some("implementer")
        }
        "deny_if_role_is_implementer" => {
            context.get("role_tier").and_then(GuardValue::as_str) == Some("implementer")
        }
        "deny_if_role_is_meta" => {
            context.get("role_tier").and_then(GuardValue::as_str) == Some("meta")
        }
        "deny_if_branch_outside_own_lane" => context
            .get("is_own_lane_branch")
            .is_some_and(GuardValue::is_false),
        "deny_unless_root" => context.get("role_tier").and_then(GuardValue::as_str) != Some("root"),
        effect => return Err(effect),
    };
    Ok(value)
}