ta-changeset 0.15.15-alpha.3

ChangeSet and PR Package data model for Trusted Autonomy
Documentation
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
// supervisor.rs — Supervisor agent for dependency graph analysis and validation.
//
// The supervisor validates artifact dispositions against their dependency graph,
// warning about coupled rejections and broken dependencies before apply.

use std::collections::{HashMap, HashSet};

use crate::draft_package::{Artifact, ArtifactDisposition, DependencyKind};

#[cfg(test)]
use crate::draft_package::ChangeDependency;

/// Result of supervisor validation with warnings and errors.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ValidationResult {
    /// Whether the configuration is valid (no hard errors).
    pub valid: bool,
    /// Non-blocking warnings (e.g., rejecting an artifact others depend on).
    pub warnings: Vec<ValidationWarning>,
    /// Blocking errors (e.g., cycles in dependency graph).
    pub errors: Vec<ValidationError>,
}

impl ValidationResult {
    /// Create a valid result with no issues.
    pub fn valid() -> Self {
        Self {
            valid: true,
            warnings: Vec::new(),
            errors: Vec::new(),
        }
    }

    /// Check if there are any warnings.
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }

    /// Check if there are any errors.
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Add a warning to the result.
    pub fn add_warning(&mut self, warning: ValidationWarning) {
        self.warnings.push(warning);
    }

    /// Add an error to the result (sets valid = false).
    pub fn add_error(&mut self, error: ValidationError) {
        self.valid = false;
        self.errors.push(error);
    }
}

/// Warning about potentially problematic dispositions.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationWarning {
    /// Rejecting an artifact that others depend on.
    CoupledRejection {
        artifact: String,
        required_by: Vec<String>,
    },
    /// Approving an artifact that depends on rejected ones.
    BrokenDependency {
        artifact: String,
        depends_on_rejected: Vec<String>,
    },
    /// An artifact marked "discuss" is blocking others.
    DiscussBlockingApproval {
        artifact: String,
        blocking: Vec<String>,
    },
}

/// Hard errors in the dependency graph or configuration.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ValidationError {
    /// Circular dependency detected.
    CyclicDependency { cycle: Vec<String> },
    /// Self-dependency (artifact depends on itself).
    SelfDependency { artifact: String },
}

/// Dependency graph built from artifact dependencies.
#[derive(Debug, Clone)]
pub struct DependencyGraph {
    /// Adjacency list: artifact URI -> set of artifacts it depends on.
    pub depends_on: HashMap<String, HashSet<String>>,
    /// Reverse adjacency list: artifact URI -> set of artifacts that depend on it.
    pub depended_by: HashMap<String, HashSet<String>>,
}

impl DependencyGraph {
    /// Build a dependency graph from a list of artifacts.
    pub fn from_artifacts(artifacts: &[Artifact]) -> Self {
        let mut depends_on: HashMap<String, HashSet<String>> = HashMap::new();
        let mut depended_by: HashMap<String, HashSet<String>> = HashMap::new();

        for artifact in artifacts {
            let uri = artifact.resource_uri.clone();

            // Initialize entries for this artifact
            depends_on.entry(uri.clone()).or_default();
            depended_by.entry(uri.clone()).or_default();

            // Process dependencies
            for dep in &artifact.dependencies {
                match dep.kind {
                    DependencyKind::DependsOn => {
                        depends_on
                            .entry(uri.clone())
                            .or_default()
                            .insert(dep.target_uri.clone());
                        depended_by
                            .entry(dep.target_uri.clone())
                            .or_default()
                            .insert(uri.clone());
                    }
                    DependencyKind::DependedBy => {
                        depended_by
                            .entry(uri.clone())
                            .or_default()
                            .insert(dep.target_uri.clone());
                        depends_on
                            .entry(dep.target_uri.clone())
                            .or_default()
                            .insert(uri.clone());
                    }
                }
            }
        }

        Self {
            depends_on,
            depended_by,
        }
    }

    /// Get all artifacts that directly depend on the given artifact.
    pub fn get_dependents(&self, uri: &str) -> Vec<String> {
        self.depended_by
            .get(uri)
            .map(|set| set.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Get all artifacts that the given artifact directly depends on.
    pub fn get_dependencies(&self, uri: &str) -> Vec<String> {
        self.depends_on
            .get(uri)
            .map(|set| set.iter().cloned().collect())
            .unwrap_or_default()
    }

    /// Detect cycles in the dependency graph using DFS.
    pub fn detect_cycles(&self) -> Vec<Vec<String>> {
        let mut visited = HashSet::new();
        let mut rec_stack = HashSet::new();
        let mut cycles = Vec::new();

        for node in self.depends_on.keys() {
            if !visited.contains(node) {
                self.dfs_cycle_detect(
                    node,
                    &mut visited,
                    &mut rec_stack,
                    &mut Vec::new(),
                    &mut cycles,
                );
            }
        }

        cycles
    }

    fn dfs_cycle_detect(
        &self,
        node: &str,
        visited: &mut HashSet<String>,
        rec_stack: &mut HashSet<String>,
        path: &mut Vec<String>,
        cycles: &mut Vec<Vec<String>>,
    ) {
        visited.insert(node.to_string());
        rec_stack.insert(node.to_string());
        path.push(node.to_string());

        if let Some(neighbors) = self.depends_on.get(node) {
            for neighbor in neighbors {
                if !visited.contains(neighbor) {
                    self.dfs_cycle_detect(neighbor, visited, rec_stack, path, cycles);
                } else if rec_stack.contains(neighbor) {
                    // Found a cycle - extract it from path
                    if let Some(start_idx) = path.iter().position(|n| n == neighbor) {
                        let cycle = path[start_idx..].to_vec();
                        cycles.push(cycle);
                    }
                }
            }
        }

        path.pop();
        rec_stack.remove(node);
    }

    /// Check for self-dependencies (artifact depends on itself).
    pub fn detect_self_dependencies(&self) -> Vec<String> {
        let mut self_deps = Vec::new();

        for (uri, deps) in &self.depends_on {
            if deps.contains(uri) {
                self_deps.push(uri.clone());
            }
        }

        self_deps
    }
}

/// Result of plan validation — checking if completed work matches plan expectations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlanValidationResult {
    /// Whether the draft has content (at least one artifact).
    pub has_artifacts: bool,
    /// Number of artifacts in the draft.
    pub artifact_count: usize,
    /// Number of artifacts with descriptions (what/rationale populated).
    pub described_count: usize,
    /// Informational messages about plan alignment.
    pub notes: Vec<String>,
}

impl PlanValidationResult {
    /// Check if the draft has enough described artifacts to be considered complete.
    pub fn is_well_described(&self) -> bool {
        self.has_artifacts && self.described_count > 0
    }
}

/// Validate artifacts against plan expectations.
///
/// Checks that the draft has meaningful content and that artifacts are described.
/// This is called by `ta draft build` when a goal has a plan_phase.
pub fn validate_against_plan(
    artifacts: &[Artifact],
    phase_id: &str,
    phase_title: &str,
) -> PlanValidationResult {
    let artifact_count = artifacts.len();
    let described_count = artifacts
        .iter()
        .filter(|a| {
            a.explanation_tiers
                .as_ref()
                .map(|t| !t.summary.is_empty())
                .unwrap_or(false)
                || a.rationale.is_some()
        })
        .count();

    let mut notes = Vec::new();

    if artifact_count == 0 {
        notes.push(format!(
            "No artifacts found for phase {}{}. Expected code changes.",
            phase_id, phase_title
        ));
    }

    if artifact_count > 0 && described_count == 0 {
        notes.push(format!(
            "None of the {} artifacts for phase {} have descriptions. Consider adding a change_summary.json.",
            artifact_count, phase_id
        ));
    }

    let undescribed = artifact_count.saturating_sub(described_count);
    if undescribed > 0 && described_count > 0 {
        notes.push(format!(
            "{}/{} artifacts for phase {} lack descriptions.",
            undescribed, artifact_count, phase_id
        ));
    }

    PlanValidationResult {
        has_artifacts: artifact_count > 0,
        artifact_count,
        described_count,
        notes,
    }
}

/// Supervisor agent that validates artifact dispositions against dependencies.
pub struct SupervisorAgent {
    graph: DependencyGraph,
}

impl SupervisorAgent {
    /// Create a new supervisor from a list of artifacts.
    pub fn new(artifacts: &[Artifact]) -> Self {
        Self {
            graph: DependencyGraph::from_artifacts(artifacts),
        }
    }

    /// Validate artifact dispositions against the dependency graph.
    ///
    /// Returns a ValidationResult with warnings about:
    /// - Rejecting artifacts that others depend on (coupled rejections)
    /// - Approving artifacts that depend on rejected ones (broken dependencies)
    /// - "Discuss" artifacts blocking approvals
    ///
    /// And errors for:
    /// - Cyclic dependencies
    /// - Self-dependencies
    pub fn validate(&self, artifacts: &[Artifact]) -> ValidationResult {
        let mut result = ValidationResult::valid();

        // Check for structural errors first
        for cycle in self.graph.detect_cycles() {
            result.add_error(ValidationError::CyclicDependency { cycle });
        }

        for self_dep in self.graph.detect_self_dependencies() {
            result.add_error(ValidationError::SelfDependency { artifact: self_dep });
        }

        // Build disposition map for quick lookup
        let dispositions: HashMap<String, ArtifactDisposition> = artifacts
            .iter()
            .map(|a| (a.resource_uri.clone(), a.disposition.clone()))
            .collect();

        // Check for coupled rejections and broken dependencies
        for artifact in artifacts {
            let uri = &artifact.resource_uri;
            let disposition = &artifact.disposition;

            match disposition {
                ArtifactDisposition::Rejected => {
                    // Check if any approved/discuss artifacts depend on this one
                    let dependents = self.graph.get_dependents(uri);
                    let affected: Vec<String> = dependents
                        .into_iter()
                        .filter(|dep_uri| {
                            matches!(
                                dispositions.get(dep_uri),
                                Some(ArtifactDisposition::Approved)
                                    | Some(ArtifactDisposition::Discuss)
                                    | Some(ArtifactDisposition::Pending)
                            )
                        })
                        .collect();

                    if !affected.is_empty() {
                        result.add_warning(ValidationWarning::CoupledRejection {
                            artifact: uri.clone(),
                            required_by: affected,
                        });
                    }
                }
                ArtifactDisposition::Approved => {
                    // Check if this artifact depends on any rejected ones
                    let dependencies = self.graph.get_dependencies(uri);
                    let rejected_deps: Vec<String> = dependencies
                        .into_iter()
                        .filter(|dep_uri| {
                            matches!(
                                dispositions.get(dep_uri),
                                Some(ArtifactDisposition::Rejected)
                            )
                        })
                        .collect();

                    if !rejected_deps.is_empty() {
                        result.add_warning(ValidationWarning::BrokenDependency {
                            artifact: uri.clone(),
                            depends_on_rejected: rejected_deps,
                        });
                    }
                }
                ArtifactDisposition::Discuss => {
                    // Check if any approved artifacts depend on this discuss item
                    let dependents = self.graph.get_dependents(uri);
                    let blocked: Vec<String> = dependents
                        .into_iter()
                        .filter(|dep_uri| {
                            matches!(
                                dispositions.get(dep_uri),
                                Some(ArtifactDisposition::Approved)
                            )
                        })
                        .collect();

                    if !blocked.is_empty() {
                        result.add_warning(ValidationWarning::DiscussBlockingApproval {
                            artifact: uri.clone(),
                            blocking: blocked,
                        });
                    }
                }
                ArtifactDisposition::Pending => {
                    // Pending is neutral - no validation needed
                }
            }
        }

        result
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn make_artifact(
        uri: &str,
        disposition: ArtifactDisposition,
        deps: Vec<(&str, DependencyKind)>,
    ) -> Artifact {
        Artifact {
            resource_uri: uri.to_string(),
            change_type: crate::draft_package::ChangeType::Modify,
            diff_ref: "test".to_string(),
            tests_run: Vec::new(),
            disposition,
            rationale: None,
            dependencies: deps
                .into_iter()
                .map(|(target, kind)| ChangeDependency {
                    target_uri: target.to_string(),
                    kind,
                })
                .collect(),
            explanation_tiers: None,
            comments: None,
            amendment: None,
            kind: None,
        }
    }

    #[test]
    fn test_dependency_graph_simple() {
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Pending,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Pending, vec![]),
        ];

        let graph = DependencyGraph::from_artifacts(&artifacts);

        assert_eq!(
            graph.get_dependencies("fs://workspace/a.rs"),
            vec!["fs://workspace/b.rs"]
        );
        assert_eq!(
            graph.get_dependents("fs://workspace/b.rs"),
            vec!["fs://workspace/a.rs"]
        );
    }

    #[test]
    fn test_coupled_rejection_warning() {
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Rejected, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(result.valid);
        assert_eq!(result.warnings.len(), 2);

        // Should warn about both: rejecting B that A depends on, and approving A that depends on rejected B
        assert!(result
            .warnings
            .iter()
            .any(|w| matches!(w, ValidationWarning::CoupledRejection { .. })));
        assert!(result
            .warnings
            .iter()
            .any(|w| matches!(w, ValidationWarning::BrokenDependency { .. })));
    }

    #[test]
    fn test_no_warning_when_consistent() {
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Approved, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(result.valid);
        assert_eq!(result.warnings.len(), 0);
    }

    #[test]
    fn test_self_dependency_error() {
        let artifacts = vec![make_artifact(
            "fs://workspace/a.rs",
            ArtifactDisposition::Pending,
            vec![("fs://workspace/a.rs", DependencyKind::DependsOn)],
        )];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(!result.valid);
        // Self-dependency is detected as both a self-dep and a cycle
        assert!(!result.errors.is_empty());
        assert!(result
            .errors
            .iter()
            .any(|e| matches!(e, ValidationError::SelfDependency { .. })));
    }

    #[test]
    fn test_cycle_detection() {
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Pending,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact(
                "fs://workspace/b.rs",
                ArtifactDisposition::Pending,
                vec![("fs://workspace/c.rs", DependencyKind::DependsOn)],
            ),
            make_artifact(
                "fs://workspace/c.rs",
                ArtifactDisposition::Pending,
                vec![("fs://workspace/a.rs", DependencyKind::DependsOn)],
            ),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(!result.valid);
        assert_eq!(result.errors.len(), 1);
        assert!(matches!(
            result.errors[0],
            ValidationError::CyclicDependency { .. }
        ));
    }

    #[test]
    fn test_discuss_blocking_approval() {
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Discuss, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(result.valid);
        assert_eq!(result.warnings.len(), 1);
        assert!(matches!(
            result.warnings[0],
            ValidationWarning::DiscussBlockingApproval { .. }
        ));
    }

    #[test]
    fn test_depended_by_relationship() {
        let artifacts = vec![
            make_artifact("fs://workspace/a.rs", ArtifactDisposition::Pending, vec![]),
            make_artifact(
                "fs://workspace/b.rs",
                ArtifactDisposition::Pending,
                vec![("fs://workspace/a.rs", DependencyKind::DependedBy)],
            ),
        ];

        let graph = DependencyGraph::from_artifacts(&artifacts);

        // b.rs is depended by a.rs means a.rs depends on b.rs
        assert_eq!(
            graph.get_dependencies("fs://workspace/a.rs"),
            vec!["fs://workspace/b.rs"]
        );
        assert_eq!(
            graph.get_dependents("fs://workspace/b.rs"),
            vec!["fs://workspace/a.rs"]
        );
    }

    #[test]
    fn test_transitive_dependency_chain() {
        // A → B → C: rejecting C should warn about B (direct dependency)
        // A won't be warned because its direct dependency (B) is approved
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact(
                "fs://workspace/b.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/c.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/c.rs", ArtifactDisposition::Rejected, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        // Should have 2 warnings: C coupled rejection (breaks B) + B broken dependency (depends on rejected C)
        assert!(result.valid);
        assert_eq!(result.warnings.len(), 2);
    }

    #[test]
    fn test_disconnected_subgraphs() {
        // Two independent chains: A→B and C→D
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Rejected, vec![]),
            make_artifact(
                "fs://workspace/c.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/d.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/d.rs", ArtifactDisposition::Approved, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        // Should only warn about A→B, not C→D
        assert!(result.valid);
        assert_eq!(result.warnings.len(), 2); // B coupled rejection + A broken dependency
    }

    #[test]
    fn test_mixed_dispositions() {
        // Complex scenario: some approved, some rejected, some pending, some discuss
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/b.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Discuss, vec![]),
            make_artifact(
                "fs://workspace/c.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/d.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/d.rs", ArtifactDisposition::Pending, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        // Should warn about discuss blocking approval
        assert!(result.valid);
        assert_eq!(result.warnings.len(), 1);
        assert!(matches!(
            result.warnings[0],
            ValidationWarning::DiscussBlockingApproval { .. }
        ));
    }

    #[test]
    fn test_empty_artifacts() {
        let artifacts = vec![];
        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(result.valid);
        assert_eq!(result.warnings.len(), 0);
        assert_eq!(result.errors.len(), 0);
    }

    #[test]
    fn test_all_approved_no_dependencies() {
        let artifacts = vec![
            make_artifact("fs://workspace/a.rs", ArtifactDisposition::Approved, vec![]),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Approved, vec![]),
            make_artifact("fs://workspace/c.rs", ArtifactDisposition::Approved, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        assert!(result.valid);
        assert_eq!(result.warnings.len(), 0);
        assert_eq!(result.errors.len(), 0);
    }

    #[test]
    fn test_diamond_dependency() {
        // Diamond pattern: A→B, A→C, B→D, C→D
        let artifacts = vec![
            make_artifact(
                "fs://workspace/a.rs",
                ArtifactDisposition::Approved,
                vec![
                    ("fs://workspace/b.rs", DependencyKind::DependsOn),
                    ("fs://workspace/c.rs", DependencyKind::DependsOn),
                ],
            ),
            make_artifact(
                "fs://workspace/b.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/d.rs", DependencyKind::DependsOn)],
            ),
            make_artifact(
                "fs://workspace/c.rs",
                ArtifactDisposition::Approved,
                vec![("fs://workspace/d.rs", DependencyKind::DependsOn)],
            ),
            make_artifact("fs://workspace/d.rs", ArtifactDisposition::Rejected, vec![]),
        ];

        let supervisor = SupervisorAgent::new(&artifacts);
        let result = supervisor.validate(&artifacts);

        // Should warn about D being rejected but depended on by B and C
        assert!(result.valid);
        assert!(result.warnings.len() >= 3); // At least coupled rejection for D and broken deps for B, C
    }

    // ── Plan validation tests ──

    #[test]
    fn test_plan_validation_empty_artifacts() {
        let result = validate_against_plan(&[], "v0.3.1", "Plan Lifecycle");
        assert!(!result.has_artifacts);
        assert!(!result.is_well_described());
        assert_eq!(result.notes.len(), 1);
        assert!(result.notes[0].contains("No artifacts found"));
    }

    #[test]
    fn test_plan_validation_undescribed_artifacts() {
        let artifacts = vec![
            make_artifact("fs://workspace/a.rs", ArtifactDisposition::Pending, vec![]),
            make_artifact("fs://workspace/b.rs", ArtifactDisposition::Pending, vec![]),
        ];
        let result = validate_against_plan(&artifacts, "v0.3.1", "Plan Lifecycle");
        assert!(result.has_artifacts);
        assert_eq!(result.artifact_count, 2);
        assert_eq!(result.described_count, 0);
        assert!(!result.is_well_described());
    }

    #[test]
    fn test_plan_validation_described_artifacts() {
        let mut a1 = make_artifact("fs://workspace/a.rs", ArtifactDisposition::Pending, vec![]);
        a1.explanation_tiers = Some(crate::draft_package::ExplanationTiers {
            summary: "Added plan validation".to_string(),
            explanation: String::new(),
            tags: vec![],
            related_artifacts: vec![],
        });
        let a2 = make_artifact("fs://workspace/b.rs", ArtifactDisposition::Pending, vec![]);

        let result = validate_against_plan(&[a1, a2], "v0.3.1", "Plan Lifecycle");
        assert!(result.has_artifacts);
        assert_eq!(result.described_count, 1);
        assert!(result.is_well_described());
        // Should note that 1/2 artifacts lack descriptions.
        assert!(result.notes.iter().any(|n| n.contains("1/2")));
    }

    #[test]
    fn test_plan_validation_all_described() {
        let mut a1 = make_artifact("fs://workspace/a.rs", ArtifactDisposition::Pending, vec![]);
        a1.rationale = Some("Reason".to_string());
        let mut a2 = make_artifact("fs://workspace/b.rs", ArtifactDisposition::Pending, vec![]);
        a2.explanation_tiers = Some(crate::draft_package::ExplanationTiers {
            summary: "Summary".to_string(),
            explanation: String::new(),
            tags: vec![],
            related_artifacts: vec![],
        });

        let result = validate_against_plan(&[a1, a2], "v0.3.1", "Plan Lifecycle");
        assert!(result.is_well_described());
        assert!(result.notes.is_empty());
    }
}