joy-core 0.10.0

Core library for Joy product management - Git-native, terminal-first
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
// Copyright (c) 2026 Joydev GmbH (joydev.com)
// SPDX-License-Identifier: MIT

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use super::config::InteractionLevel;
use super::item::Capability;

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Project {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub acronym: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default = "default_language")]
    pub language: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub forge: Option<String>,
    #[serde(default, skip_serializing_if = "Docs::is_empty")]
    pub docs: Docs,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub members: BTreeMap<String, Member>,
    pub created: DateTime<Utc>,
}

/// Configurable paths to the project's reference documentation, relative to
/// the project root. Used by `joy ai init` to support existing repos with
/// non-default doc layouts and read by AI tools via `joy project get docs.<key>`.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Docs {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub architecture: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub vision: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub contributing: Option<String>,
}

impl Docs {
    pub const DEFAULT_ARCHITECTURE: &'static str = "docs/dev/architecture/README.md";
    pub const DEFAULT_VISION: &'static str = "docs/dev/vision/README.md";
    pub const DEFAULT_CONTRIBUTING: &'static str = "CONTRIBUTING.md";

    pub fn is_empty(&self) -> bool {
        self.architecture.is_none() && self.vision.is_none() && self.contributing.is_none()
    }

    /// Configured architecture path or the default if unset.
    pub fn architecture_or_default(&self) -> &str {
        self.architecture
            .as_deref()
            .unwrap_or(Self::DEFAULT_ARCHITECTURE)
    }

    /// Configured vision path or the default if unset.
    pub fn vision_or_default(&self) -> &str {
        self.vision.as_deref().unwrap_or(Self::DEFAULT_VISION)
    }

    /// Configured contributing path or the default if unset.
    pub fn contributing_or_default(&self) -> &str {
        self.contributing
            .as_deref()
            .unwrap_or(Self::DEFAULT_CONTRIBUTING)
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Member {
    pub capabilities: MemberCapabilities,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub public_key: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub salt: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub otp_hash: Option<String>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub ai_tokens: BTreeMap<String, AiTokenEntry>,
}

/// A registered AI delegation token entry.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AiTokenEntry {
    /// Public key of the one-time token keypair (hex-encoded Ed25519).
    pub token_key: String,
    /// When this token was created.
    pub created: chrono::DateTime<chrono::Utc>,
}

#[derive(Debug, Clone, PartialEq)]
pub enum MemberCapabilities {
    All,
    Specific(BTreeMap<Capability, CapabilityConfig>),
}

#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct CapabilityConfig {
    #[serde(rename = "max-mode", default, skip_serializing_if = "Option::is_none")]
    pub max_mode: Option<InteractionLevel>,
    #[serde(
        rename = "max-cost-per-job",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub max_cost_per_job: Option<f64>,
}

// ---------------------------------------------------------------------------
// Mode defaults (from project.defaults.yaml, overridable in project.yaml)
// ---------------------------------------------------------------------------

/// Interaction mode defaults: a global default plus optional per-capability overrides.
/// Deserializes from flat YAML like: `{ default: collaborative, implement: autonomous }`.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ModeDefaults {
    /// Fallback mode when no per-capability mode is set.
    #[serde(default)]
    pub default: InteractionLevel,
    /// Per-capability mode overrides (flattened into the same map).
    #[serde(flatten, default)]
    pub capabilities: BTreeMap<Capability, InteractionLevel>,
}

/// Default capabilities granted to AI members by joy ai init.
/// Loaded from `ai-defaults.capabilities` in project.defaults.yaml.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct AiDefaults {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub capabilities: Vec<Capability>,
}

/// Source of a resolved interaction mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ModeSource {
    /// From project.defaults.yaml (Joy's recommendation).
    Default,
    /// From project.yaml agents.defaults override.
    Project,
    /// From config.yaml personal preference.
    Personal,
    /// From item-level override (future).
    Item,
    /// Clamped by max-mode from project.yaml member config.
    ProjectMax,
}

impl std::fmt::Display for ModeSource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Default => write!(f, "default"),
            Self::Project => write!(f, "project"),
            Self::Personal => write!(f, "personal"),
            Self::Item => write!(f, "item"),
            Self::ProjectMax => write!(f, "project max"),
        }
    }
}

/// Resolve the effective interaction mode for a given capability.
///
/// Resolution order (later wins):
/// 1. Effective defaults global mode (project.defaults.yaml merged with project.yaml)
/// 2. Effective defaults per-capability mode
/// 3. Personal config preference
///
/// All clamped by max-mode from the member's CapabilityConfig.
pub fn resolve_mode(
    capability: &Capability,
    raw_defaults: &ModeDefaults,
    effective_defaults: &ModeDefaults,
    personal_mode: Option<InteractionLevel>,
    member_cap_config: Option<&CapabilityConfig>,
) -> (InteractionLevel, ModeSource) {
    // 1. Global fallback from effective defaults
    let mut mode = effective_defaults.default;
    let mut source = if effective_defaults.default != raw_defaults.default {
        ModeSource::Project
    } else {
        ModeSource::Default
    };

    // 2. Per-capability default
    if let Some(&cap_mode) = effective_defaults.capabilities.get(capability) {
        mode = cap_mode;
        let from_raw = raw_defaults.capabilities.get(capability) == Some(&cap_mode);
        source = if from_raw {
            ModeSource::Default
        } else {
            ModeSource::Project
        };
    }

    // 3. Personal preference
    if let Some(personal) = personal_mode {
        mode = personal;
        source = ModeSource::Personal;
    }

    // 4. Clamp by max-mode (minimum interactivity required)
    if let Some(cap_config) = member_cap_config {
        if let Some(max) = cap_config.max_mode {
            if mode < max {
                mode = max;
                source = ModeSource::ProjectMax;
            }
        }
    }

    (mode, source)
}

// Custom serde for MemberCapabilities: "all" string or map of capabilities
impl Serialize for MemberCapabilities {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            MemberCapabilities::All => serializer.serialize_str("all"),
            MemberCapabilities::Specific(map) => map.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for MemberCapabilities {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let value = serde_yaml_ng::Value::deserialize(deserializer)?;
        match &value {
            serde_yaml_ng::Value::String(s) if s == "all" => Ok(MemberCapabilities::All),
            serde_yaml_ng::Value::Mapping(_) => {
                let map: BTreeMap<Capability, CapabilityConfig> =
                    serde_yaml_ng::from_value(value).map_err(serde::de::Error::custom)?;
                Ok(MemberCapabilities::Specific(map))
            }
            _ => Err(serde::de::Error::custom(
                "expected \"all\" or a map of capabilities",
            )),
        }
    }
}

impl Member {
    /// Create a member with the given capabilities and no auth fields.
    pub fn new(capabilities: MemberCapabilities) -> Self {
        Self {
            capabilities,
            public_key: None,
            salt: None,
            otp_hash: None,
            ai_tokens: BTreeMap::new(),
        }
    }

    /// Check whether this member has a specific capability.
    pub fn has_capability(&self, cap: &Capability) -> bool {
        match &self.capabilities {
            MemberCapabilities::All => true,
            MemberCapabilities::Specific(map) => map.contains_key(cap),
        }
    }
}

/// Check whether a member ID represents an AI member.
pub fn is_ai_member(id: &str) -> bool {
    id.starts_with("ai:")
}

fn default_language() -> String {
    "en".to_string()
}

impl Project {
    pub fn new(name: String, acronym: Option<String>) -> Self {
        Self {
            name,
            acronym,
            description: None,
            language: default_language(),
            forge: None,
            docs: Docs::default(),
            members: BTreeMap::new(),
            created: Utc::now(),
        }
    }
}

/// Derive an acronym from a project name.
/// Takes the first letter of each word, uppercase, max 4 characters.
/// Single words use up to 3 uppercase characters.
pub fn derive_acronym(name: &str) -> String {
    let words: Vec<&str> = name.split_whitespace().collect();
    if words.len() == 1 {
        words[0]
            .chars()
            .filter(|c| c.is_alphanumeric())
            .take(3)
            .collect::<String>()
            .to_uppercase()
    } else {
        words
            .iter()
            .filter_map(|w| w.chars().next())
            .filter(|c| c.is_alphanumeric())
            .take(4)
            .collect::<String>()
            .to_uppercase()
    }
}

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

    #[test]
    fn project_roundtrip() {
        let project = Project::new("Test Project".into(), Some("TP".into()));
        let yaml = serde_yaml_ng::to_string(&project).unwrap();
        let parsed: Project = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(project, parsed);
    }

    // -----------------------------------------------------------------------
    // Docs tests
    // -----------------------------------------------------------------------

    #[test]
    fn docs_defaults_when_unset() {
        let docs = Docs::default();
        assert_eq!(docs.architecture_or_default(), Docs::DEFAULT_ARCHITECTURE);
        assert_eq!(docs.vision_or_default(), Docs::DEFAULT_VISION);
        assert_eq!(docs.contributing_or_default(), Docs::DEFAULT_CONTRIBUTING);
    }

    #[test]
    fn docs_returns_configured_value() {
        let docs = Docs {
            architecture: Some("ARCHITECTURE.md".into()),
            vision: Some("docs/product/vision.md".into()),
            contributing: None,
        };
        assert_eq!(docs.architecture_or_default(), "ARCHITECTURE.md");
        assert_eq!(docs.vision_or_default(), "docs/product/vision.md");
        assert_eq!(docs.contributing_or_default(), Docs::DEFAULT_CONTRIBUTING);
    }

    #[test]
    fn docs_omitted_from_yaml_when_empty() {
        let project = Project::new("X".into(), None);
        let yaml = serde_yaml_ng::to_string(&project).unwrap();
        assert!(
            !yaml.contains("docs:"),
            "empty docs should be skipped, got: {yaml}"
        );
    }

    #[test]
    fn docs_present_in_yaml_when_set() {
        let mut project = Project::new("X".into(), None);
        project.docs.architecture = Some("ARCHITECTURE.md".into());
        let yaml = serde_yaml_ng::to_string(&project).unwrap();
        assert!(yaml.contains("docs:"), "docs block expected: {yaml}");
        assert!(yaml.contains("architecture: ARCHITECTURE.md"));
        assert!(!yaml.contains("vision:"), "unset fields should be skipped");
    }

    #[test]
    fn docs_yaml_roundtrip_with_overrides() {
        let yaml = r#"
name: Existing
language: en
docs:
  architecture: ARCHITECTURE.md
  contributing: docs/CONTRIBUTING.md
created: 2026-01-01T00:00:00Z
"#;
        let parsed: Project = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(parsed.docs.architecture.as_deref(), Some("ARCHITECTURE.md"));
        assert_eq!(parsed.docs.vision, None);
        assert_eq!(
            parsed.docs.contributing.as_deref(),
            Some("docs/CONTRIBUTING.md")
        );
        assert_eq!(parsed.docs.vision_or_default(), Docs::DEFAULT_VISION);
    }

    #[test]
    fn derive_acronym_multi_word() {
        assert_eq!(derive_acronym("My Cool Project"), "MCP");
    }

    #[test]
    fn derive_acronym_single_word() {
        assert_eq!(derive_acronym("Joy"), "JOY");
    }

    #[test]
    fn derive_acronym_long_name() {
        assert_eq!(derive_acronym("A Very Long Project Name"), "AVLP");
    }

    #[test]
    fn derive_acronym_single_long_word() {
        assert_eq!(derive_acronym("Platform"), "PLA");
    }

    // -----------------------------------------------------------------------
    // ModeDefaults deserialization tests
    // -----------------------------------------------------------------------

    #[test]
    fn mode_defaults_flat_yaml_roundtrip() {
        let yaml = r#"
default: interactive
implement: collaborative
review: pairing
"#;
        let parsed: ModeDefaults = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(parsed.default, InteractionLevel::Interactive);
        assert_eq!(
            parsed.capabilities[&Capability::Implement],
            InteractionLevel::Collaborative
        );
        assert_eq!(
            parsed.capabilities[&Capability::Review],
            InteractionLevel::Pairing
        );
    }

    #[test]
    fn mode_defaults_empty_yaml() {
        let yaml = "{}";
        let parsed: ModeDefaults = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(parsed.default, InteractionLevel::Collaborative);
        assert!(parsed.capabilities.is_empty());
    }

    #[test]
    fn mode_defaults_only_default() {
        let yaml = "default: pairing";
        let parsed: ModeDefaults = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(parsed.default, InteractionLevel::Pairing);
        assert!(parsed.capabilities.is_empty());
    }

    #[test]
    fn ai_defaults_yaml_roundtrip() {
        let yaml = r#"
capabilities:
  - implement
  - review
"#;
        let parsed: AiDefaults = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(parsed.capabilities.len(), 2);
        assert_eq!(parsed.capabilities[0], Capability::Implement);
    }

    // -----------------------------------------------------------------------
    // resolve_mode tests
    // -----------------------------------------------------------------------

    fn defaults_with_mode(mode: InteractionLevel) -> ModeDefaults {
        ModeDefaults {
            default: mode,
            ..Default::default()
        }
    }

    fn defaults_with_cap_mode(cap: Capability, mode: InteractionLevel) -> ModeDefaults {
        let mut d = ModeDefaults::default();
        d.capabilities.insert(cap, mode);
        d
    }

    #[test]
    fn resolve_mode_uses_global_default() {
        let raw = defaults_with_mode(InteractionLevel::Collaborative);
        let effective = raw.clone();
        let (mode, source) = resolve_mode(&Capability::Implement, &raw, &effective, None, None);
        assert_eq!(mode, InteractionLevel::Collaborative);
        assert_eq!(source, ModeSource::Default);
    }

    #[test]
    fn resolve_mode_uses_per_capability_default() {
        let raw = defaults_with_cap_mode(Capability::Review, InteractionLevel::Interactive);
        let effective = raw.clone();
        let (mode, source) = resolve_mode(&Capability::Review, &raw, &effective, None, None);
        assert_eq!(mode, InteractionLevel::Interactive);
        assert_eq!(source, ModeSource::Default);
    }

    #[test]
    fn resolve_mode_project_override_detected() {
        let raw = defaults_with_cap_mode(Capability::Implement, InteractionLevel::Collaborative);
        let effective =
            defaults_with_cap_mode(Capability::Implement, InteractionLevel::Interactive);
        let (mode, source) = resolve_mode(&Capability::Implement, &raw, &effective, None, None);
        assert_eq!(mode, InteractionLevel::Interactive);
        assert_eq!(source, ModeSource::Project);
    }

    #[test]
    fn resolve_mode_personal_overrides_default() {
        let raw = defaults_with_mode(InteractionLevel::Collaborative);
        let effective = raw.clone();
        let (mode, source) = resolve_mode(
            &Capability::Implement,
            &raw,
            &effective,
            Some(InteractionLevel::Pairing),
            None,
        );
        assert_eq!(mode, InteractionLevel::Pairing);
        assert_eq!(source, ModeSource::Personal);
    }

    #[test]
    fn resolve_mode_max_mode_clamps_upward() {
        let raw = defaults_with_mode(InteractionLevel::Autonomous);
        let effective = raw.clone();
        let cap_config = CapabilityConfig {
            max_mode: Some(InteractionLevel::Supervised),
            ..Default::default()
        };
        let (mode, source) = resolve_mode(
            &Capability::Implement,
            &raw,
            &effective,
            None,
            Some(&cap_config),
        );
        assert_eq!(mode, InteractionLevel::Supervised);
        assert_eq!(source, ModeSource::ProjectMax);
    }

    #[test]
    fn resolve_mode_max_mode_does_not_lower() {
        let raw = defaults_with_mode(InteractionLevel::Pairing);
        let effective = raw.clone();
        let cap_config = CapabilityConfig {
            max_mode: Some(InteractionLevel::Supervised),
            ..Default::default()
        };
        let (mode, source) = resolve_mode(
            &Capability::Implement,
            &raw,
            &effective,
            None,
            Some(&cap_config),
        );
        // Pairing > Supervised, so no clamping
        assert_eq!(mode, InteractionLevel::Pairing);
        assert_eq!(source, ModeSource::Default);
    }

    #[test]
    fn resolve_mode_personal_clamped_by_max() {
        let raw = defaults_with_mode(InteractionLevel::Collaborative);
        let effective = raw.clone();
        let cap_config = CapabilityConfig {
            max_mode: Some(InteractionLevel::Interactive),
            ..Default::default()
        };
        let (mode, source) = resolve_mode(
            &Capability::Implement,
            &raw,
            &effective,
            Some(InteractionLevel::Autonomous),
            Some(&cap_config),
        );
        // Personal is Autonomous but max is Interactive, clamp up
        assert_eq!(mode, InteractionLevel::Interactive);
        assert_eq!(source, ModeSource::ProjectMax);
    }

    // -----------------------------------------------------------------------
    // Item mode serialization
    // -----------------------------------------------------------------------

    #[test]
    fn item_mode_field_roundtrip() {
        use crate::model::item::{Item, ItemType, Priority};

        let mut item = Item::new(
            "TST-0001".into(),
            "Test".into(),
            ItemType::Task,
            Priority::Medium,
            vec![],
        );
        item.mode = Some(InteractionLevel::Pairing);

        let yaml = serde_yaml_ng::to_string(&item).unwrap();
        assert!(yaml.contains("mode: pairing"), "mode field not serialized");

        let parsed: Item = serde_yaml_ng::from_str(&yaml).unwrap();
        assert_eq!(parsed.mode, Some(InteractionLevel::Pairing));
    }

    #[test]
    fn item_mode_field_absent_when_none() {
        use crate::model::item::{Item, ItemType, Priority};

        let item = Item::new(
            "TST-0002".into(),
            "Test".into(),
            ItemType::Task,
            Priority::Medium,
            vec![],
        );
        assert_eq!(item.mode, None);

        let yaml = serde_yaml_ng::to_string(&item).unwrap();
        assert!(
            !yaml.contains("mode:"),
            "mode field should not appear when None"
        );
    }

    #[test]
    fn item_mode_deserialized_from_existing_yaml() {
        let yaml = r#"
id: TST-0003
title: Test
type: task
status: new
priority: medium
mode: interactive
created: "2026-01-01T00:00:00+00:00"
updated: "2026-01-01T00:00:00+00:00"
"#;
        let item: crate::model::item::Item = serde_yaml_ng::from_str(yaml).unwrap();
        assert_eq!(item.mode, Some(InteractionLevel::Interactive));
    }

    // -----------------------------------------------------------------------
    // Full four-layer resolution scenario
    // -----------------------------------------------------------------------

    #[test]
    fn resolve_mode_full_scenario() {
        // Joy default: implement = collaborative
        let raw = defaults_with_cap_mode(Capability::Implement, InteractionLevel::Collaborative);
        // Project override: implement = interactive
        let effective =
            defaults_with_cap_mode(Capability::Implement, InteractionLevel::Interactive);
        // Personal preference: autonomous
        let personal = Some(InteractionLevel::Autonomous);
        // Project max-mode: supervised (minimum interactivity)
        let cap_config = CapabilityConfig {
            max_mode: Some(InteractionLevel::Supervised),
            ..Default::default()
        };

        let (mode, source) = resolve_mode(
            &Capability::Implement,
            &raw,
            &effective,
            personal,
            Some(&cap_config),
        );

        // Personal (autonomous) < max (supervised), so clamped up to supervised
        assert_eq!(mode, InteractionLevel::Supervised);
        assert_eq!(source, ModeSource::ProjectMax);
    }

    #[test]
    fn resolve_mode_all_layers_no_clamping() {
        // Joy default: implement = collaborative
        let raw = defaults_with_cap_mode(Capability::Implement, InteractionLevel::Collaborative);
        // Project override: implement = interactive
        let effective =
            defaults_with_cap_mode(Capability::Implement, InteractionLevel::Interactive);
        // Personal preference: pairing (more interactive than project)
        let personal = Some(InteractionLevel::Pairing);
        // No max-mode
        let cap_config = CapabilityConfig::default();

        let (mode, source) = resolve_mode(
            &Capability::Implement,
            &raw,
            &effective,
            personal,
            Some(&cap_config),
        );

        // Personal wins, no clamping
        assert_eq!(mode, InteractionLevel::Pairing);
        assert_eq!(source, ModeSource::Personal);
    }
}