drove 0.1.1

Versioned, declarative agent workspaces
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
//! Canonical desired-state model (schema version 2) produced by a `Drovefile`.
//!
//! Five resource kinds — workspace, tab, pane, agent, task — share one
//! profile-scoped namespace for `after`, `on_*` and adoption references.
//! See `docs/superpowers/specs/2026-09-06-drove-v2-design.md` §3-4.

use std::{
    collections::{BTreeMap, BTreeSet},
    path::PathBuf,
};

use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};

pub const SCHEMA_VERSION: u32 = 2;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DroveConfig {
    pub schema_version: u32,
    pub profiles: BTreeMap<String, Profile>,
    /// Which backend this project reconciles onto (D32): `backend(...)` in
    /// the Drovefile. `None` when undeclared; the CLI falls back to its own
    /// resolution order (spec §5).
    #[serde(default)]
    pub backend: Option<String>,
    /// The named instance each flavor targets when its Drovefile declares
    /// one (`herdr.session(...)`, `radiator.hub(...)`), D32.
    #[serde(default)]
    pub target: BackendTargets,
}

/// Per-flavor target instance declarations (D32). Only the active backend's
/// declaration is used; a Drovefile may declare both.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct BackendTargets {
    #[serde(default)]
    pub herdr_session: Option<String>,
    #[serde(default)]
    pub radiator_hub: Option<String>,
}

impl DroveConfig {
    pub fn new(
        profiles: Vec<Profile>,
        backend: Option<String>,
        target: BackendTargets,
    ) -> Result<Self> {
        let mut by_name = BTreeMap::new();
        for profile in profiles {
            validate_name("profile", &profile.name)?;
            if by_name.insert(profile.name.clone(), profile).is_some() {
                bail!("duplicate profile name");
            }
        }
        // A `default` profile is no longer required (D42): the CLI falls
        // back to `default` if declared, else the file's only profile, else
        // lists every declared profile and exits 2 (spec §5).
        let config = Self {
            schema_version: SCHEMA_VERSION,
            profiles: by_name,
            backend,
            target,
        };
        for profile in config.profiles.values() {
            profile.validate()?;
        }
        Ok(config)
    }

    pub fn profile(&self, name: &str) -> Result<&Profile> {
        self.profiles
            .get(name)
            .with_context(|| format!("profile `{name}` is not declared"))
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(deny_unknown_fields)]
pub struct Profile {
    pub name: String,
    #[serde(default)]
    pub workspaces: Vec<Workspace>,
    #[serde(default)]
    pub tasks: Vec<Task>,
    /// The Herdr session (or, for `backend = "radiator"`, the hub) this
    /// profile targets (D41). Unset inherits the file-level
    /// `herdr.session(...)`/`radiator.hub(...)`. `extends` copies the
    /// parent's value unless the child sets its own.
    #[serde(default)]
    pub session: Option<String>,
    /// The backend this profile reconciles onto (D41): `herdr` or
    /// `radiator`. Unset inherits the file-level `backend(...)`.
    #[serde(default)]
    pub backend: Option<String>,
}

impl Profile {
    pub fn validate(&self) -> Result<()> {
        if let Some(backend) = &self.backend
            && backend != crate::backend::select::HERDR_BACKEND
            && backend != crate::backend::select::RADIATOR_BACKEND
        {
            bail!(
                "profile `{}` declares backend = \"{backend}\"; known backends: {}, {}",
                self.name,
                crate::backend::select::HERDR_BACKEND,
                crate::backend::select::RADIATOR_BACKEND
            );
        }

        let mut workspace_names = BTreeSet::new();
        let mut pane_names = BTreeSet::new();
        let mut agent_names = BTreeSet::new();
        let mut adopt_count = 0usize;

        for workspace in &self.workspaces {
            validate_name("workspace", &workspace.name)?;
            if !workspace_names.insert(workspace.name.as_str()) {
                bail!("duplicate workspace name `{}`", workspace.name);
            }

            let mut tab_names = BTreeSet::new();
            for tab in &workspace.tabs {
                // Tabs are a Herdr placement hint, not part of the shared
                // `after`/adoption namespace (spec §3-4), so their name is
                // a free-form label rather than the strict identifier used
                // for workspace/pane/agent/task names.
                if tab.name.is_empty() || tab.name.len() > 64 {
                    bail!("tab name `{}` must be 1-64 characters", tab.name);
                }
                if !tab_names.insert(tab.name.as_str()) {
                    bail!(
                        "duplicate tab name `{}` in workspace `{}`",
                        tab.name,
                        workspace.name
                    );
                }
                tab.validate()?;
                for pane in &tab.panes {
                    validate_name("pane", &pane.name)?;
                    if !pane_names.insert(pane.name.as_str()) {
                        bail!("duplicate pane name `{}` in profile", pane.name);
                    }
                    if let Some(agent) = &pane.agent {
                        agent.validate()?;
                        if let Some(agent_name) = &agent.name
                            && (pane_names.contains(agent_name.as_str())
                                || !agent_names.insert(agent_name.as_str()))
                        {
                            bail!(
                                "agent `{agent_name}` collides with another resource of the same name in the shared `after` namespace"
                            );
                        }
                    }
                    if let Some(adopt) = &pane.adopt {
                        if adopt != "caller" {
                            bail!(
                                "pane `{}` declares adopt = `{adopt}`; only `caller` is supported",
                                pane.name
                            );
                        }
                        adopt_count += 1;
                    }
                }
            }
        }
        if adopt_count > 1 {
            bail!("only one pane per profile may declare `adopt = \"caller\"`");
        }

        let mut task_names = BTreeSet::new();
        for task in &self.tasks {
            validate_name("task", &task.name)?;
            if !task_names.insert(task.name.as_str()) {
                bail!("duplicate task name `{}` in profile", task.name);
            }
            if pane_names.contains(task.name.as_str()) || agent_names.contains(task.name.as_str()) {
                bail!(
                    "task `{}` collides with a pane or agent of the same name in the shared `after` namespace",
                    task.name
                );
            }
            if task.run.is_empty() {
                bail!("task `{}` requires a non-empty `run` argv", task.name);
            }
        }

        self.validate_was(&workspace_names, &pane_names, &agent_names, &task_names)?;
        self.validate_after(&pane_names, &agent_names, &task_names)
    }

    /// D34: `was` must not equal the resource's own name, and must not
    /// collide with any name currently declared in the profile — a `was`
    /// that pointed at a live declared name would be ambiguous with a real
    /// resource rather than a ghost of a rename.
    fn validate_was(
        &self,
        workspace_names: &BTreeSet<&str>,
        pane_names: &BTreeSet<&str>,
        agent_names: &BTreeSet<&str>,
        task_names: &BTreeSet<&str>,
    ) -> Result<()> {
        for workspace in &self.workspaces {
            if let Some(was) = &workspace.was {
                if was == &workspace.name {
                    bail!(
                        "workspace `{}` declares `was` equal to its own name",
                        workspace.name
                    );
                }
                if workspace_names.contains(was.as_str()) {
                    bail!(
                        "workspace `{}` declares `was = \"{was}\"` which is also a declared workspace name",
                        workspace.name
                    );
                }
            }
            for tab in &workspace.tabs {
                for pane in &tab.panes {
                    let Some(was) = &pane.was else { continue };
                    if was == &pane.name {
                        bail!("pane `{}` declares `was` equal to its own name", pane.name);
                    }
                    if pane_names.contains(was.as_str())
                        || agent_names.contains(was.as_str())
                        || task_names.contains(was.as_str())
                    {
                        bail!(
                            "pane `{}` declares `was = \"{was}\"` which is also a declared name",
                            pane.name
                        );
                    }
                }
            }
        }
        Ok(())
    }

    fn validate_after(
        &self,
        pane_names: &BTreeSet<&str>,
        agent_names: &BTreeSet<&str>,
        task_names: &BTreeSet<&str>,
    ) -> Result<()> {
        let mut edges: BTreeMap<&str, &[String]> = BTreeMap::new();
        for workspace in &self.workspaces {
            for tab in &workspace.tabs {
                for pane in &tab.panes {
                    edges.insert(pane.name.as_str(), pane.after.as_slice());
                }
            }
        }
        for task in &self.tasks {
            edges.insert(task.name.as_str(), task.after.as_slice());
        }

        let known = || {
            pane_names
                .iter()
                .copied()
                .chain(agent_names.iter().copied())
                .chain(task_names.iter().copied())
        };
        for (id, targets) in &edges {
            for target in *targets {
                if !known().any(|name| name == target) {
                    bail!("`{id}` declares `after = [\"{target}\"]` for an unknown resource");
                }
            }
        }

        fn visit<'a>(
            id: &'a str,
            edges: &BTreeMap<&'a str, &'a [String]>,
            visiting: &mut BTreeSet<&'a str>,
            visited: &mut BTreeSet<&'a str>,
        ) -> Result<()> {
            if visited.contains(id) {
                return Ok(());
            }
            if !visiting.insert(id) {
                bail!("`after` dependency cycle includes `{id}`");
            }
            if let Some(targets) = edges.get(id) {
                for target in *targets {
                    visit(target, edges, visiting, visited)?;
                }
            }
            visiting.remove(id);
            visited.insert(id);
            Ok(())
        }

        let mut visiting = BTreeSet::new();
        let mut visited = BTreeSet::new();
        for id in edges.keys().copied() {
            visit(id, &edges, &mut visiting, &mut visited)?;
        }
        Ok(())
    }

    pub fn digest(&self) -> Result<String> {
        canonical_digest(self)
    }

    pub fn to_ir(&self) -> crate::ir::Ir {
        crate::ir::to_ir(self)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Workspace {
    pub name: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default = "default_cwd")]
    pub cwd: PathBuf,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    #[serde(default)]
    pub tabs: Vec<Tab>,
    /// The name this workspace was previously declared under (D34). When a
    /// live resource is still identified by `was`, the planner migrates its
    /// identity to `name` instead of creating anew and detaching the old one.
    #[serde(default)]
    pub was: Option<String>,
}

impl Workspace {
    pub fn label(&self) -> &str {
        self.label.as_deref().unwrap_or(&self.name)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Tab {
    pub name: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub split: SplitDirection,
    #[serde(default)]
    pub ratios: Vec<f64>,
    #[serde(default)]
    pub panes: Vec<Pane>,
}

impl Tab {
    pub fn label(&self) -> &str {
        self.label.as_deref().unwrap_or(&self.name)
    }

    fn validate(&self) -> Result<()> {
        let expected = self.panes.len().saturating_sub(1);
        if self.ratios.len() != expected {
            bail!(
                "tab `{}` declares {} ratio(s) for {} pane(s); expected {expected}",
                self.name,
                self.ratios.len(),
                self.panes.len()
            );
        }
        for ratio in &self.ratios {
            if !(0.05..=0.95).contains(ratio) {
                bail!(
                    "tab `{}` ratio {ratio} must be between 0.05 and 0.95",
                    self.name
                );
            }
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
#[serde(rename_all = "snake_case")]
pub enum SplitDirection {
    #[default]
    Right,
    Down,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Pane {
    pub name: String,
    #[serde(default)]
    pub label: Option<String>,
    #[serde(default)]
    pub cwd: Option<PathBuf>,
    #[serde(default)]
    pub env: BTreeMap<String, String>,
    /// `any_of` candidates, tried in order; a plain `serve = [...]` argv is
    /// normalized to a single-candidate list at compile time.
    #[serde(default)]
    pub serve: Vec<Vec<String>>,
    #[serde(default)]
    pub ready: Option<Readiness>,
    #[serde(default)]
    pub after: Vec<String>,
    #[serde(default)]
    pub adopt: Option<String>,
    #[serde(default)]
    pub agent: Option<Agent>,
    #[serde(default)]
    pub on_start: Option<Vec<String>>,
    #[serde(default)]
    pub on_stop: Option<Vec<String>>,
    /// The name this pane was previously declared under (D34). See
    /// [`Workspace::was`].
    #[serde(default)]
    pub was: Option<String>,
}

impl Pane {
    pub fn label(&self) -> &str {
        self.label.as_deref().unwrap_or(&self.name)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum Readiness {
    Output { value: String },
    Port { value: u16 },
    Cmd { value: Vec<String> },
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Agent {
    #[serde(default)]
    pub name: Option<String>,
    pub kind: String,
    #[serde(default)]
    pub args: Vec<String>,
    /// Resolved at compile time: either the literal inline string, or the
    /// contents of a `file("repo/relative/path")` reference (D25).
    #[serde(default)]
    pub prompt: Option<String>,
}

const PROMPT_MAX_BYTES: usize = 2 * 1024;

impl Agent {
    fn validate(&self) -> Result<()> {
        if self.kind.is_empty() {
            bail!("agent declares an empty `kind`");
        }
        if let Some(name) = &self.name {
            validate_name("agent", name)?;
        }
        if let Some(prompt) = &self.prompt
            && prompt.len() > PROMPT_MAX_BYTES
        {
            bail!(
                "agent `{}` prompt exceeds {PROMPT_MAX_BYTES} bytes",
                self.kind
            );
        }
        Ok(())
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct Task {
    pub name: String,
    pub run: Vec<String>,
    #[serde(default)]
    pub check: Option<Vec<String>>,
    #[serde(default)]
    pub inputs: Vec<PathBuf>,
    #[serde(default)]
    pub after: Vec<String>,
    #[serde(default = "default_true")]
    pub auto: bool,
    #[serde(default)]
    pub on_start: Option<Vec<String>>,
    #[serde(default)]
    pub on_stop: Option<Vec<String>>,
}

pub fn canonical_digest<T: Serialize>(value: &T) -> Result<String> {
    let bytes = serde_json::to_vec(value)?;
    Ok(hex::encode(Sha256::digest(bytes)))
}

fn validate_name(kind: &str, name: &str) -> Result<()> {
    let mut bytes = name.bytes();
    let starts_ok = bytes.next().is_some_and(|byte| byte.is_ascii_lowercase());
    let rest_ok = name.len() <= 32
        && bytes.all(|byte| {
            byte.is_ascii_lowercase() || byte.is_ascii_digit() || matches!(byte, b'-' | b'_')
        });
    if !starts_ok || !rest_ok {
        bail!("{kind} name `{name}` must match [a-z][a-z0-9_-]{{0,31}}");
    }
    Ok(())
}

fn default_cwd() -> PathBuf {
    PathBuf::from(".")
}

fn default_true() -> bool {
    true
}

#[cfg(test)]
mod tests {
    use serde_json::json;

    use super::*;

    fn profile_from(value: serde_json::Value) -> Profile {
        serde_json::from_value(value).expect("profile fixture")
    }

    #[test]
    fn rejects_invalid_names() {
        // Name syntax is checked by `DroveConfig::new`, which validates the
        // profile name itself before delegating into `Profile::validate`.
        let profile = profile_from(json!({
            "name": "Default",
            "workspaces": []
        }));
        let error = DroveConfig::new(vec![profile], None, BackendTargets::default())
            .expect_err("invalid name");
        assert!(error.to_string().contains("must match"));
    }

    #[test]
    fn accepts_known_profile_backends() {
        for backend in ["herdr", "radiator"] {
            let profile = profile_from(json!({
                "name": "default",
                "backend": backend,
            }));
            profile.validate().expect("known backend");
        }
    }

    #[test]
    fn rejects_unknown_profile_backend() {
        let profile = profile_from(json!({
            "name": "default",
            "backend": "nope",
        }));
        let error = profile.validate().expect_err("unknown backend");
        assert!(error.to_string().contains("known backends"));
    }

    #[test]
    fn rejects_duplicate_panes_across_profile() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [
                    {"name": "one", "panes": [{"name": "same"}]},
                    {"name": "two", "panes": [{"name": "same"}]}
                ]
            }]
        }));
        let error = profile.validate().expect_err("duplicate should fail");
        assert!(error.to_string().contains("duplicate pane name"));
    }

    #[test]
    fn rejects_duplicate_workspace_names() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [
                {"name": "dev", "tabs": []},
                {"name": "dev", "tabs": []}
            ]
        }));
        let error = profile.validate().expect_err("duplicate workspace");
        assert!(error.to_string().contains("duplicate workspace name"));
    }

    #[test]
    fn rejects_second_adopt_in_profile() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{
                    "name": "main",
                    "ratios": [0.5],
                    "panes": [{"name": "one", "adopt": "caller"}, {"name": "two"}]
                }, {
                    "name": "second",
                    "panes": [{"name": "three", "adopt": "caller"}]
                }]
            }]
        }));
        let error = profile.validate().expect_err("second adopt should fail");
        assert!(error.to_string().contains("only one pane per profile"));
    }

    #[test]
    fn rejects_unsupported_adopt_value() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "panes": [{"name": "one", "adopt": "someone-else"}]}]
            }]
        }));
        let error = profile.validate().expect_err("bad adopt value");
        assert!(error.to_string().contains("only `caller` is supported"));
    }

    #[test]
    fn rejects_wrong_ratio_count() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{
                    "name": "main",
                    "ratios": [0.5, 0.5],
                    "panes": [{"name": "one"}, {"name": "two"}]
                }]
            }]
        }));
        let error = profile.validate().expect_err("wrong ratio count");
        assert!(error.to_string().contains("expected 1"));
    }

    #[test]
    fn rejects_ratio_out_of_range() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{
                    "name": "main",
                    "ratios": [0.99],
                    "panes": [{"name": "one"}, {"name": "two"}]
                }]
            }]
        }));
        let error = profile.validate().expect_err("out of range ratio");
        assert!(error.to_string().contains("between 0.05 and 0.95"));
    }

    #[test]
    fn rejects_after_targeting_unknown_resource() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "panes": [{"name": "one", "after": ["missing"]}]}]
            }]
        }));
        let error = profile.validate().expect_err("unknown after target");
        assert!(error.to_string().contains("unknown resource"));
    }

    #[test]
    fn rejects_after_cycle() {
        let profile = profile_from(json!({
            "name": "default",
            "tasks": [
                {"name": "a", "run": ["true"], "after": ["b"]},
                {"name": "b", "run": ["true"], "after": ["a"]}
            ]
        }));
        let error = profile.validate().expect_err("cycle");
        assert!(error.to_string().contains("dependency cycle"));
    }

    #[test]
    fn accepts_valid_after_dag_across_panes_and_tasks() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "panes": [{"name": "one", "after": ["scaffold"]}]}]
            }],
            "tasks": [{"name": "scaffold", "run": ["true"]}]
        }));
        profile.validate().expect("valid DAG");
    }

    #[test]
    fn rejects_task_missing_run() {
        let profile = profile_from(json!({
            "name": "default",
            "tasks": [{"name": "empty", "run": []}]
        }));
        let error = profile.validate().expect_err("empty run");
        assert!(error.to_string().contains("non-empty `run`"));
    }

    #[test]
    fn rejects_duplicate_task_name() {
        let profile = profile_from(json!({
            "name": "default",
            "tasks": [
                {"name": "scaffold", "run": ["true"]},
                {"name": "scaffold", "run": ["true"]}
            ]
        }));
        let error = profile.validate().expect_err("duplicate task name");
        assert!(error.to_string().contains("duplicate task name"));
    }

    #[test]
    fn rejects_task_name_colliding_with_pane_name() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "panes": [{"name": "scaffold"}]}]
            }],
            "tasks": [{"name": "scaffold", "run": ["true"]}]
        }));
        let error = profile.validate().expect_err("name collision");
        assert!(error.to_string().contains("collides with a pane"));
    }

    #[test]
    fn rejects_agent_name_colliding_with_pane_name() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "ratios": [0.5], "panes": [
                    {"name": "review"},
                    {"name": "worker", "agent": {"name": "review", "kind": "claude"}}
                ]}]
            }]
        }));
        let error = profile.validate().expect_err("agent/pane name collision");
        assert!(error.to_string().contains("collides with another resource"));
    }

    #[test]
    fn agent_name_is_a_valid_after_target() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "ratios": [0.5], "panes": [
                    {"name": "worker", "agent": {"name": "review", "kind": "claude"}},
                    {"name": "follower", "after": ["review"]}
                ]}]
            }]
        }));
        profile
            .validate()
            .expect("agent name is a known after target");
    }

    #[test]
    fn rejects_duplicate_profile_name() {
        let profile = Profile {
            name: "default".into(),
            workspaces: vec![],
            tasks: vec![],
            session: None,
            backend: None,
        };
        let error = DroveConfig::new(
            vec![profile.clone(), profile],
            None,
            BackendTargets::default(),
        )
        .expect_err("duplicate profile name");
        assert!(error.to_string().contains("duplicate profile name"));
    }

    #[test]
    fn a_default_profile_is_not_required() {
        // D42: the CLI, not the model, decides what "no profile given" means
        // when there is no `default` profile (the only profile, or exit 2).
        let profile = Profile {
            name: "other".into(),
            workspaces: vec![],
            tasks: vec![],
            session: None,
            backend: None,
        };
        let config = DroveConfig::new(vec![profile], None, BackendTargets::default())
            .expect("no default profile required");
        assert!(config.profiles.contains_key("other"));
    }

    #[test]
    fn rejects_oversized_inline_prompt() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{
                    "name": "main",
                    "panes": [{
                        "name": "review",
                        "agent": {"kind": "claude", "prompt": "x".repeat(3000)}
                    }]
                }]
            }]
        }));
        let error = profile.validate().expect_err("oversized prompt");
        assert!(error.to_string().contains("exceeds"));
    }

    #[test]
    fn rejects_was_equal_to_own_name() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "panes": [{"name": "review", "was": "review"}]}]
            }]
        }));
        let error = profile.validate().expect_err("was equal to own name");
        assert!(error.to_string().contains("equal to its own name"));
    }

    #[test]
    fn rejects_was_colliding_with_a_declared_name() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "tabs": [{"name": "main", "ratios": [0.5], "panes": [
                    {"name": "review", "was": "shell"},
                    {"name": "shell"}
                ]}]
            }]
        }));
        let error = profile
            .validate()
            .expect_err("was collides with a declared name");
        assert!(error.to_string().contains("also a declared name"));
    }

    #[test]
    fn accepts_a_valid_was_declaration() {
        let profile = profile_from(json!({
            "name": "default",
            "workspaces": [{
                "name": "dev",
                "was": "legacy-dev",
                "tabs": [{"name": "main", "panes": [{"name": "review", "was": "shell"}]}]
            }]
        }));
        profile.validate().expect("valid was declaration");
    }

    #[test]
    fn canonical_digest_is_stable() {
        let one = BTreeMap::from([("a", 1), ("b", 2)]);
        let two = BTreeMap::from([("b", 2), ("a", 1)]);
        assert_eq!(
            canonical_digest(&one).expect("digest"),
            canonical_digest(&two).expect("digest")
        );
    }
}