shepherd-core 6.7.0

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
use alloc::{
    collections::{BTreeMap, BTreeSet},
    format,
    string::{String, ToString},
    vec::Vec,
};

use super::{
    PLAN_SCHEMA, PlanDocument, PlanError, PlanLane, PlanNode, PlanTopology, SessionReclamation,
    TOPOLOGY_SCHEMA, TurnResetBehavior, TurnStrategy, VerifiedPlanSeed,
};

const FOURTH_REJECTION: &str =
    "malignant-revoke-quarantine-preserve-evidence-no-resume-root-lineage-replacement";
const ROOT_CONTINUATION: &str = "fresh-root-preferred-new-run-binding-clears-child-authority";

pub fn validate_plan_structure(
    plan: &PlanDocument,
    seed: &VerifiedPlanSeed,
) -> Result<PlanTopology, PlanError> {
    let manifest = &plan.manifest;
    if manifest.schema != PLAN_SCHEMA {
        return Err(structure(format!(
            "schema must be `{PLAN_SCHEMA}`, found `{}`",
            manifest.schema
        )));
    }
    if manifest.run != seed.run || manifest.seed != seed.relative_path || manifest.mesh != seed.mesh
    {
        return Err(structure(
            "run, seed, and mesh must match the verified seed",
        ));
    }
    validate_identifier(&manifest.run, "run")?;
    validate_relative_path(&manifest.seed, "seed")?;
    validate_relative_path(&manifest.mesh, "mesh")?;
    validate_relative_path(&manifest.planning_evidence, "planning evidence")?;
    require_text(&manifest.goal, "goal")?;
    validate_closed_roles(manifest)?;

    let deliverables = unique_set(&manifest.deliverables, "deliverable")?;
    let seed_deliverables = unique_set(&seed.deliverables, "seed deliverable")?;
    if deliverables != seed_deliverables {
        return Err(structure(format!(
            "plan deliverables do not exactly cover verified seed deliverables: plan={deliverables:?} seed={seed_deliverables:?}"
        )));
    }
    let lanes = unique_set(&manifest.lanes, "lane")?;
    if lanes.is_empty() {
        return Err(structure("plan has zero lanes"));
    }
    for lane in &lanes {
        validate_identifier(lane, "lane")?;
    }
    validate_capacity(plan, seed, &lanes)?;

    let mut node_by_id = BTreeMap::new();
    let mut deliverable_producers: BTreeMap<&str, &str> = BTreeMap::new();
    let mut interface_producers: BTreeMap<&str, &str> = BTreeMap::new();
    for node in &manifest.nodes {
        validate_node(node, &lanes, &deliverables)?;
        if node_by_id.insert(node.id.as_str(), node).is_some() {
            return Err(structure(format!("duplicate node id `{}`", node.id)));
        }
        for deliverable in &node.seed_deliverables {
            if let Some(previous) = deliverable_producers.insert(deliverable, &node.id) {
                return Err(structure(format!(
                    "seed deliverable `{deliverable}` has duplicate producer nodes `{previous}` and `{}`",
                    node.id
                )));
            }
        }
        for interface in &node.produces {
            validate_interface(interface)?;
            if let Some(previous) = interface_producers.insert(interface, &node.id) {
                return Err(structure(format!(
                    "interface producer is duplicated for `{interface}` by `{previous}` and `{}`",
                    node.id
                )));
            }
        }
        for interface in &node.consumes {
            validate_interface(interface)?;
        }
    }
    for deliverable in &deliverables {
        if !deliverable_producers.contains_key(deliverable.as_str()) {
            return Err(structure(format!(
                "verified seed deliverable `{deliverable}` is uncovered"
            )));
        }
    }

    for node in &manifest.nodes {
        for dependency in &node.depends_on {
            if !node_by_id.contains_key(dependency.as_str()) {
                return Err(structure(format!(
                    "node `{}` has dangling dependency `{dependency}`",
                    node.id
                )));
            }
            if dependency == &node.id {
                return Err(structure(format!("dependency cycle at `{}`", node.id)));
            }
        }
    }
    let topological_order = topological_order(&node_by_id)?;
    validate_reachability(&node_by_id)?;
    validate_concurrent_ownership(&node_by_id)?;

    let cargo_targets = manifest
        .capacity
        .cargo_targets
        .iter()
        .map(|binding| (binding.lane.as_str(), binding.value.as_str()))
        .collect::<BTreeMap<_, _>>();
    let conductors = manifest
        .capacity
        .conductors
        .iter()
        .map(|binding| (binding.lane.as_str(), binding.value.as_str()))
        .collect::<BTreeMap<_, _>>();
    let mut topology_lanes = Vec::new();
    for lane in &manifest.lanes {
        let mut node_ids = manifest
            .nodes
            .iter()
            .filter(|node| &node.lane == lane)
            .map(|node| node.id.clone())
            .collect::<Vec<_>>();
        node_ids.sort();
        if node_ids.is_empty() {
            return Err(structure(format!("lane `{lane}` has zero nodes")));
        }
        let mut lane_deliverables = manifest
            .nodes
            .iter()
            .filter(|node| &node.lane == lane)
            .flat_map(|node| node.seed_deliverables.iter().cloned())
            .collect::<Vec<_>>();
        lane_deliverables.sort();
        lane_deliverables.dedup();
        if lane_deliverables.is_empty() {
            return Err(structure(format!(
                "lane `{lane}` is not vertical because it binds no seed deliverable"
            )));
        }
        topology_lanes.push(PlanLane {
            id: lane.clone(),
            conductor: conductors[lane.as_str()].to_string(),
            cargo_target: cargo_targets[lane.as_str()].to_string(),
            node_ids,
            deliverables: lane_deliverables,
        });
    }
    topology_lanes.sort_by(|left, right| left.id.cmp(&right.id));
    let mut nodes = manifest.nodes.clone();
    nodes.sort_by(|left, right| left.id.cmp(&right.id));
    for node in &mut nodes {
        node.seed_deliverables.sort();
        node.depends_on.sort();
        node.owns.sort();
        node.forbidden.sort();
        node.consumes.sort();
        node.produces.sort();
    }
    let mut projected_deliverables = manifest.deliverables.clone();
    projected_deliverables.sort();
    let mut capacity = manifest.capacity.clone();
    capacity
        .cargo_targets
        .sort_by(|left, right| left.lane.cmp(&right.lane));
    capacity
        .conductors
        .sort_by(|left, right| left.lane.cmp(&right.lane));
    for wave in &mut capacity.schedule {
        wave.lanes.sort();
    }
    capacity
        .schedule
        .sort_by(|left, right| left.lanes.cmp(&right.lanes));

    Ok(PlanTopology {
        schema: TOPOLOGY_SCHEMA.to_string(),
        run: manifest.run.clone(),
        seed: manifest.seed.clone(),
        mesh: manifest.mesh.clone(),
        planning_evidence: manifest.planning_evidence.clone(),
        goal: manifest.goal.clone(),
        deliverables: projected_deliverables,
        lanes: topology_lanes,
        nodes,
        topological_order,
        capacity,
        capacity_policy: capacity_policy(manifest.lanes.len()).to_string(),
    })
}

fn validate_closed_roles(manifest: &super::PlanManifestV2) -> Result<(), PlanError> {
    if manifest.root_roles != ["shepherd", "planter"] {
        return Err(structure(
            "root roles must be exactly `[shepherd, planter]` in that order",
        ));
    }
    if manifest.child_lead_roles != ["engineer", "conductor"] {
        return Err(structure(
            "child lead roles must be exactly `[engineer, conductor]` in that order",
        ));
    }
    if manifest.planning_lead != "engineer" || manifest.engineer_count != 1 {
        return Err(structure(
            "normal planning requires exactly one active Engineer child lead",
        ));
    }
    if manifest.review_rejection_limit != 3 || manifest.fourth_rejection != FOURTH_REJECTION {
        return Err(structure(
            "review custody requires three redos then fourth-rejection malignant revocation, quarantine, evidence preservation, no resume, and root-lineage replacement",
        ));
    }
    if manifest.root_continuation != ROOT_CONTINUATION {
        return Err(structure(
            "root continuation must prefer a fresh root and clear prior child authority under a new run binding before reuse",
        ));
    }
    Ok(())
}

fn validate_node(
    node: &PlanNode,
    lanes: &BTreeSet<String>,
    deliverables: &BTreeSet<String>,
) -> Result<(), PlanError> {
    validate_identifier(&node.id, "node id")?;
    if !lanes.contains(&node.lane) {
        return Err(structure(format!(
            "node `{}` names unknown lane `{}`",
            node.id, node.lane
        )));
    }
    for deliverable in &node.seed_deliverables {
        if !deliverables.contains(deliverable) {
            return Err(structure(format!(
                "node `{}` names unknown seed deliverable `{deliverable}`",
                node.id
            )));
        }
    }
    let expected_work = match node.role.as_str() {
        "coder" => "production",
        "worker" => "artifact",
        "engineer" => "planning",
        "auditor" | "critic" => "review",
        "discovery" => "research",
        "conductor" => "coordination",
        "shepherd" | "planter" => {
            return Err(structure(format!(
                "root role `{}` cannot be assigned a plan node",
                node.role
            )));
        }
        _ => return Err(structure(format!("invalid role `{}`", node.role))),
    };
    if node.work_kind != expected_work {
        let detail = if node.role == "conductor" {
            "Conductor consumes an immutable lane slice and may only coordinate; planning, rescoping, and implementation are forbidden"
        } else {
            "role and work kind are incompatible"
        };
        return Err(structure(format!(
            "node `{}`: {detail}; role `{}` requires work kind `{expected_work}`, found `{}`",
            node.id, node.role, node.work_kind
        )));
    }
    require_text(&node.outcome, &format!("node `{}` outcome", node.id))?;
    if node.owns.is_empty() {
        return Err(structure(format!("node `{}` owns is empty", node.id)));
    }
    let mut owned_folded = BTreeSet::new();
    for path in &node.owns {
        validate_relative_path(path, &format!("node `{}` owned path", node.id))?;
        if path == ".shepherd" || path.starts_with(".shepherd/") {
            return Err(structure(format!(
                "node `{}` cannot own native state or run evidence paths",
                node.id
            )));
        }
        // A case-insensitive filesystem resolves both spellings to one file, so
        // owning both is owning one file twice.
        if !owned_folded.insert(path.to_ascii_lowercase()) {
            return Err(structure(format!(
                "node `{}` owns two paths that differ only by case: `{path}`",
                node.id
            )));
        }
    }
    if node.forbidden.is_empty() {
        return Err(structure(format!("node `{}` forbidden is empty", node.id)));
    }
    for command in [&node.red.command, &node.green.command, &node.eval.command] {
        validate_argv(command, &node.id)?;
    }
    if node.red.expects != "failure" || node.green.expects != "success" {
        return Err(structure(format!(
            "node `{}` RED must expect failure and GREEN must expect success",
            node.id
        )));
    }
    require_text(&node.red.reason, "red reason")?;
    require_text(&node.green.reason, "green reason")?;
    if !matches!(node.eval.threshold, Some(1..=100)) {
        return Err(structure(format!(
            "node `{}` eval threshold must be an integer from 1 through 100",
            node.id
        )));
    }
    validate_relative_path(&node.evidence, "evidence")?;
    if !node.evidence.starts_with(".shepherd/runs/") {
        return Err(structure(format!(
            "node `{}` evidence must be run-relative",
            node.id
        )));
    }
    if !matches!(node.review.role.as_str(), "auditor" | "critic") {
        return Err(structure(format!(
            "node `{}` review role must be auditor or critic",
            node.id
        )));
    }
    require_text(&node.review.predicate, "review predicate")?;
    require_text(&node.failure_route, "failure_route")?;
    require_text(&node.rollback, "rollback")?;
    Ok(())
}

fn validate_capacity(
    plan: &PlanDocument,
    seed: &VerifiedPlanSeed,
    lanes: &BTreeSet<String>,
) -> Result<(), PlanError> {
    let capacity = &plan.manifest.capacity;
    if capacity.logical_lane_limit == 0
        || capacity.host_process_ceiling == 0
        || capacity.project_spawn_max_parallel == 0
        || capacity.plan_process_ceiling == 0
        || capacity.parent_role_cap == 0
        || capacity.run_budget == 0
        || capacity.simultaneous_process_ceiling == 0
        || capacity.per_lane_child_wave_ceiling == 0
        || capacity.model_quota == 0
        || capacity.lifecycle.as_ref().is_some_and(|lifecycle| {
            lifecycle.live_concurrency_ceiling == 0
                || lifecycle.retained_descendant_slots == 0
                || lifecycle.lifetime_descendant_slots == Some(0)
                || lifecycle.persistent_agent_cost == 0
        })
        || capacity.disk_min_mib < 1024
    {
        return Err(structure(
            "capacity values must be nonzero and disk_min_mib at least 1024",
        ));
    }
    if capacity.logical_lane_limit > lanes.len() {
        return Err(structure(
            "capacity logical lane limit cannot exceed the authored lane count",
        ));
    }
    let mut ceilings = Vec::from([
        capacity.host_process_ceiling,
        capacity.project_spawn_max_parallel,
        capacity.plan_process_ceiling,
        capacity.parent_role_cap,
        capacity.run_budget,
    ]);
    if let Some(lifecycle) = &capacity.lifecycle {
        ceilings.push(lifecycle.live_concurrency_ceiling);
    }
    let effective = ceilings
        .into_iter()
        .min()
        .expect("fixed nonempty ceiling set");
    if capacity.simultaneous_process_ceiling != effective {
        return Err(structure(
            "capacity simultaneous process ceiling must equal min(host, project spawn.max_parallel, plan, parent/role cap, run budget, lifecycle live concurrency)",
        ));
    }
    // One logical lane contains its resident Conductor plus bounded children.
    // Live processes obey the six-way minimum above, not the lane count.
    if capacity.model_quota < capacity.simultaneous_process_ceiling {
        return Err(structure(
            "capacity model quota cannot be lower than the simultaneous process ceiling",
        ));
    }
    validate_lifecycle_capacity(plan)?;
    if !matches!(capacity.backpressure.as_str(), "queue" | "queue-fair") {
        return Err(structure(
            "capacity backpressure must be the deterministic `queue` or `queue-fair` policy",
        ));
    }
    validate_bindings(&capacity.cargo_targets, lanes, "cargo target", None)?;
    validate_bindings(&capacity.conductors, lanes, "conductor", Some("conductor"))?;

    if lanes.len() >= 4 && capacity.schedule.is_empty() {
        return Err(structure(
            "capacity schedule is required for four or more lanes",
        ));
    }
    let mut scheduled = BTreeSet::new();
    for wave in &capacity.schedule {
        if wave.lanes.is_empty()
            || wave.lanes.len() > capacity.logical_lane_limit
            || wave.process_slots == 0
            || wave.process_slots > capacity.simultaneous_process_ceiling
            || wave.process_slots
                > wave
                    .lanes
                    .len()
                    .saturating_mul(capacity.per_lane_child_wave_ceiling)
        {
            return Err(structure(
                "capacity schedule contains a zero or unsafe wave",
            ));
        }
        for lane in &wave.lanes {
            if !lanes.contains(lane) {
                return Err(structure(format!(
                    "capacity schedule names unknown lane `{lane}`"
                )));
            }
            if !scheduled.insert(lane.as_str()) {
                return Err(structure(format!(
                    "capacity schedule overlaps lane `{lane}`"
                )));
            }
        }
    }
    if !capacity.schedule.is_empty() && scheduled != lanes.iter().map(String::as_str).collect() {
        return Err(structure(
            "capacity schedule must cover every lane exactly once",
        ));
    }
    if lanes.len() >= 6 {
        let scale = capacity.scale_outcome.as_deref().ok_or_else(|| {
            structure("six or more lanes require an explicit scale outcome binding")
        })?;
        if !seed.outcomes.iter().any(|outcome| outcome == scale) {
            return Err(structure(format!(
                "scale outcome `{scale}` is not bound to a verified seed outcome"
            )));
        }
    }
    Ok(())
}

fn validate_lifecycle_capacity(plan: &PlanDocument) -> Result<(), PlanError> {
    let capacity = &plan.manifest.capacity;
    let Some(lifecycle) = &capacity.lifecycle else {
        return Ok(());
    };
    let turn_strategy = capacity
        .turn_strategy
        .ok_or_else(|| structure("capacity lifecycle evidence has no turn strategy"))?;
    if lifecycle.capability_source.is_empty()
        || lifecycle.capability_source == "unknown"
        || lifecycle
            .lifetime_descendant_slots
            .is_some_and(|limit| limit < lifecycle.retained_descendant_slots)
    {
        return Err(structure(
            "capacity lifecycle facts require a named source and a lifetime ceiling no lower than retained descendant slots",
        ));
    }
    validate_lifecycle_topology(lifecycle, capacity.logical_lane_limit, turn_strategy)?;
    if !lifecycle.evidence_is_valid() {
        return Err(structure(
            "capacity lifecycle facts do not match capability_evidence_sha256",
        ));
    }
    Ok(())
}

/// Prove that one provider-neutral lifecycle profile can reach a worker and an
/// independent reviewer with the plan's persistent lane leads still resident.
pub fn validate_lifecycle_topology(
    lifecycle: &super::LifecycleCapacity,
    logical_lane_limit: usize,
    turn_strategy: TurnStrategy,
) -> Result<(), PlanError> {
    if !lifecycle.nested_dispatch {
        return Err(structure(
            "capacity topology is unreachable: persistent Conductors require nested dispatch to reach workers and an independent Auditor",
        ));
    }
    if !lifecycle.independent_reviewer_reachable {
        return Err(structure(
            "capacity topology is unreachable: adapter evidence says an independent Auditor cannot be reached",
        ));
    }
    for reclamation in [
        lifecycle.completed_session_reclamation,
        lifecycle.interrupted_session_reclamation,
    ] {
        match (reclamation, lifecycle.turn_reset_behavior) {
            (SessionReclamation::TurnBoundary, TurnResetBehavior::PreservesTerminal)
            | (SessionReclamation::Never, TurnResetBehavior::ReclaimsTerminal) => {
                return Err(structure(
                    "capacity lifecycle reclamation contradicts the recorded turn reset behavior",
                ));
            }
            _ => {}
        }
    }

    let persistent = logical_lane_limit
        .checked_mul(lifecycle.persistent_agent_cost)
        .ok_or_else(|| structure("persistent Conductor capacity overflow"))?;
    let live_required = persistent
        .checked_add(1)
        .ok_or_else(|| structure("live descendant capacity overflow"))?;
    if live_required > lifecycle.live_concurrency_ceiling {
        return Err(structure(format!(
            "live descendant capacity {} cannot place {} persistent Conductor slot(s) plus one worker or independent Auditor; reduce concurrent lanes or provide higher adapter evidence",
            lifecycle.live_concurrency_ceiling, persistent
        )));
    }

    let completed_critic = usize::from(
        turn_strategy == TurnStrategy::SameTurn
            && lifecycle.completed_session_reclamation != SessionReclamation::Immediate,
    );
    let completed_worker = completed_critic;
    let interrupted_retry = usize::from(
        turn_strategy == TurnStrategy::SameTurn
            && !lifecycle.reusable_sessions
            && lifecycle.interrupted_session_reclamation != SessionReclamation::Immediate,
    );
    let retained_required = match turn_strategy {
        TurnStrategy::ResetBetweenPhases => {
            if lifecycle.turn_reset_behavior != TurnResetBehavior::ReclaimsTerminal
                || lifecycle.completed_session_reclamation == SessionReclamation::Never
                || lifecycle.interrupted_session_reclamation == SessionReclamation::Never
            {
                return Err(structure(
                    "turn reset strategy requires adapter evidence that a turn reset reclaims completed and interrupted sessions",
                ));
            }
            live_required
        }
        TurnStrategy::FreshRootSessionBetweenPhases => {
            let fresh_root_required = persistent
                .checked_add(2)
                .ok_or_else(|| structure("fresh-root worker and reviewer capacity overflow"))?;
            if fresh_root_required > lifecycle.live_concurrency_ceiling {
                return Err(structure(format!(
                    "fresh-root descendant capacity {} cannot place {persistent} persistent Conductor slot(s), one worker, and one independent Auditor; reduce concurrent lanes below {logical_lane_limit}",
                    lifecycle.live_concurrency_ceiling
                )));
            }
            fresh_root_required
        }
        TurnStrategy::SameTurn => persistent
            .checked_add(completed_critic)
            .and_then(|value| value.checked_add(completed_worker))
            .and_then(|value| value.checked_add(interrupted_retry))
            .and_then(|value| value.checked_add(1))
            .ok_or_else(|| structure("retained descendant capacity overflow"))?,
    };
    if retained_required > lifecycle.retained_descendant_slots {
        return Err(structure(format!(
            "retained descendant capacity {} is unreachable: {persistent} persistent Conductor slot(s) + {completed_critic} completed Critic + {completed_worker} completed worker + {interrupted_retry} interrupted worker retry + 1 independent Auditor require {retained_required}; use turn_strategy `reset-between-phases` with reclaiming adapter evidence, reduce logical_lane_limit below {logical_lane_limit}, or increase retained_descendant_slots to at least {retained_required}",
            lifecycle.retained_descendant_slots
        )));
    }
    if lifecycle
        .lifetime_descendant_slots
        .is_some_and(|limit| retained_required > limit)
    {
        return Err(structure(format!(
            "lifetime descendant capacity {} cannot reach the required worker and independent Auditor topology of {retained_required}",
            lifecycle.lifetime_descendant_slots.unwrap_or_default()
        )));
    }
    Ok(())
}

fn capacity_policy(lane_count: usize) -> &'static str {
    match lane_count {
        0..=1 => "small: minimize lanes; no arbitrary minimum",
        2 => "routine: two complete vertical Conductor subsprints",
        3 => "beefy: three complete vertical Conductor subsprints",
        4 => "beefy-mega boundary: explicit host and quota schedule required",
        5 => "mega: explicit host and quota schedule required",
        6 => "mega-exceptional boundary: seed-backed OS-scale reason and capacity proof required",
        7..=8 => "exceptional OS-scale: seed-backed reason and capacity proof required",
        _ => {
            "outside the 99 percent two-to-six envelope: no global cap; seed-backed OS-scale reason and capacity proof required"
        }
    }
}

fn validate_bindings(
    bindings: &[super::LaneBinding],
    lanes: &BTreeSet<String>,
    name: &str,
    exact_value: Option<&str>,
) -> Result<(), PlanError> {
    let mut bound_lanes = BTreeSet::new();
    let mut values = BTreeSet::new();
    for binding in bindings {
        if !lanes.contains(&binding.lane) || !bound_lanes.insert(binding.lane.as_str()) {
            return Err(structure(format!(
                "{name} bindings must name each lane exactly once"
            )));
        }
        validate_identifier(&binding.value, name)?;
        if let Some(exact) = exact_value {
            if binding.value != exact {
                return Err(structure(format!(
                    "{name} for `{}` must be `{exact}`",
                    binding.lane
                )));
            }
        } else if !values.insert(binding.value.as_str()) {
            return Err(structure(format!(
                "cargo target `{}` overlaps multiple lanes",
                binding.value
            )));
        }
    }
    if bound_lanes != lanes.iter().map(String::as_str).collect() {
        return Err(structure(format!(
            "{name} bindings must cover every lane exactly once"
        )));
    }
    Ok(())
}

fn topological_order(nodes: &BTreeMap<&str, &PlanNode>) -> Result<Vec<String>, PlanError> {
    let mut indegree = nodes
        .iter()
        .map(|(id, node)| (*id, node.depends_on.len()))
        .collect::<BTreeMap<_, _>>();
    let mut dependents: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
    for (id, node) in nodes {
        for dependency in &node.depends_on {
            dependents.entry(dependency).or_default().push(id);
        }
    }
    let mut ready = indegree
        .iter()
        .filter_map(|(id, count)| (*count == 0).then_some(*id))
        .collect::<BTreeSet<_>>();
    let mut order = Vec::new();
    while let Some(id) = ready.pop_first() {
        order.push(id.to_string());
        if let Some(children) = dependents.get(id) {
            for child in children {
                let count = indegree.get_mut(child).expect("known dependent");
                *count -= 1;
                if *count == 0 {
                    ready.insert(child);
                }
            }
        }
    }
    if order.len() != nodes.len() {
        return Err(structure("dependency cycle detected"));
    }
    Ok(order)
}

fn validate_reachability(nodes: &BTreeMap<&str, &PlanNode>) -> Result<(), PlanError> {
    let mut reachable = BTreeSet::new();
    let mut pending = nodes
        .values()
        .filter(|node| !node.seed_deliverables.is_empty())
        .map(|node| node.id.as_str())
        .collect::<Vec<_>>();
    while let Some(id) = pending.pop() {
        if !reachable.insert(id) {
            continue;
        }
        pending.extend(nodes[id].depends_on.iter().map(String::as_str));
    }
    if let Some(id) = nodes.keys().find(|id| !reachable.contains(**id)) {
        return Err(structure(format!(
            "node `{id}` is unreachable from any seed deliverable"
        )));
    }
    Ok(())
}

fn validate_concurrent_ownership(nodes: &BTreeMap<&str, &PlanNode>) -> Result<(), PlanError> {
    let ids = nodes.keys().copied().collect::<Vec<_>>();
    for (index, left_id) in ids.iter().enumerate() {
        for right_id in &ids[index + 1..] {
            if depends_transitively(nodes, left_id, right_id)
                || depends_transitively(nodes, right_id, left_id)
            {
                continue;
            }
            for left in &nodes[left_id].owns {
                for right in &nodes[right_id].owns {
                    if paths_overlap(left, right) {
                        return Err(structure(format!(
                            "concurrently ready nodes `{left_id}` and `{right_id}` overlap owned paths `{left}` and `{right}`"
                        )));
                    }
                }
            }
        }
    }
    Ok(())
}

fn depends_transitively(nodes: &BTreeMap<&str, &PlanNode>, node: &str, target: &str) -> bool {
    let mut pending = nodes[node]
        .depends_on
        .iter()
        .map(String::as_str)
        .collect::<Vec<_>>();
    let mut seen = BTreeSet::new();
    while let Some(id) = pending.pop() {
        if id == target {
            return true;
        }
        if seen.insert(id) {
            pending.extend(nodes[id].depends_on.iter().map(String::as_str));
        }
    }
    false
}

fn paths_overlap(left: &str, right: &str) -> bool {
    // Compared case-insensitively on purpose. Repository names preserve case,
    // but a case-insensitive filesystem resolves `Cargo.toml` and `cargo.toml`
    // to one file, so two concurrently ready nodes owning those spellings do
    // share a mutable file. This is where the ambiguity the per-path grammar
    // used to guess at is actually decidable.
    let left = left.to_ascii_lowercase();
    let right = right.to_ascii_lowercase();
    left == right
        || left
            .strip_prefix(&right)
            .is_some_and(|suffix| suffix.starts_with('/'))
        || right
            .strip_prefix(&left)
            .is_some_and(|suffix| suffix.starts_with('/'))
}

fn validate_argv(argv: &[String], node: &str) -> Result<(), PlanError> {
    if argv.is_empty() {
        return Err(structure(format!("node `{node}` command argv is empty")));
    }
    let program = argv[0].as_str();
    if matches!(
        program,
        "sh" | "bash" | "zsh" | "fish" | "cmd" | "powershell" | "pwsh"
    ) || argv.iter().any(|argument| {
        argument.is_empty()
            || argument.contains('\n')
            || argument.contains("&&")
            || argument.contains(';')
            || argument == "|"
    }) {
        return Err(structure(format!(
            "node `{node}` command must be bounded argv without a shell"
        )));
    }
    Ok(())
}

fn validate_interface(value: &str) -> Result<(), PlanError> {
    let Some((id, version)) = value.rsplit_once('@') else {
        return Err(structure(format!(
            "interface `{value}` must carry `@version`"
        )));
    };
    validate_identifier(id, "interface id")?;
    if version.is_empty()
        || !version
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'.')
    {
        return Err(structure(format!(
            "interface `{value}` has an invalid version"
        )));
    }
    Ok(())
}

fn unique_set(values: &[String], context: &str) -> Result<BTreeSet<String>, PlanError> {
    let mut set = BTreeSet::new();
    for value in values {
        validate_identifier(value, context)?;
        if !set.insert(value.clone()) {
            return Err(structure(format!("duplicate {context} `{value}`")));
        }
    }
    Ok(set)
}

fn validate_identifier(value: &str, context: &str) -> Result<(), PlanError> {
    if value.is_empty()
        || value.starts_with('-')
        || value.ends_with('-')
        || !value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
    {
        return Err(structure(format!("invalid {context} `{value}`")));
    }
    Ok(())
}

fn validate_relative_path(path: &str, context: &str) -> Result<(), PlanError> {
    validate_repository_path(path)
        .map_err(|message| structure(format!("invalid {context} path `{path}`: {message}")))?;
    require_text(path, context)
}

pub fn validate_plan_repository_path(path: &str) -> Result<(), &'static str> {
    if path.is_empty() || path.len() > 4_096 || path.starts_with('/') || path.starts_with("//") {
        return Err("absolute and empty paths are forbidden");
    }
    if path.contains('\\') || path.contains(':') {
        return Err("drive, UNC, backslash, and alternate-stream forms are forbidden");
    }
    if path
        .chars()
        .any(|character| character.is_control() || character == '\0')
    {
        return Err("control characters are forbidden");
    }
    if !path.is_ascii() {
        return Err("non-ASCII path aliases are forbidden");
    }
    // Glob metacharacters only. Case is deliberately NOT rejected here:
    // `shepherd_core::dispatch` is the repository-path authority this contract
    // names, and it preserves case, citing `Cargo.toml` as its own example
    // (`dispatch::scope`). Folding case here invented a second path language --
    // the exact thing that authority exists to prevent -- and made every
    // manifest, README, and doctrine file unownable. A per-path check also
    // cannot detect ambiguity at all: it can only ban one spelling. Ambiguity
    // is a property of a path *set* and is enforced where sets are compared,
    // in the owned-path loop and in `paths_overlap`.
    if path.contains(['*', '?', '[', ']']) {
        return Err("glob path forms are forbidden");
    }
    for part in path.split('/') {
        if part.is_empty() || matches!(part, "." | "..") || part.contains('~') {
            return Err("empty, dot, dotdot, and home-alias components are forbidden");
        }
        if part.ends_with('.') || part.ends_with(' ') {
            return Err("trailing-dot and trailing-space aliases are forbidden");
        }
        let device = part
            .split_once('.')
            .map_or(part, |(stem, _)| stem)
            .to_ascii_uppercase();
        if matches!(device.as_str(), "CON" | "PRN" | "AUX" | "NUL")
            || device.strip_prefix("COM").is_some_and(|suffix| {
                matches!(suffix, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
            })
            || device.strip_prefix("LPT").is_some_and(|suffix| {
                matches!(suffix, "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9")
            })
        {
            return Err("Windows device aliases are forbidden");
        }
    }
    Ok(())
}

pub(super) fn validate_repository_path(path: &str) -> Result<(), &'static str> {
    validate_plan_repository_path(path)
}

fn require_text(value: &str, context: &str) -> Result<(), PlanError> {
    let lower = value.to_ascii_lowercase();
    if value.trim().is_empty()
        || value.contains('<')
        || value.contains('>')
        || lower.contains("todo")
        || lower.contains("tbd")
        || value.contains("???")
    {
        return Err(structure(format!(
            "{context} is empty or contains placeholder text"
        )));
    }
    Ok(())
}

fn structure(message: impl Into<String>) -> PlanError {
    PlanError::Structure(message.into())
}