bamboo-domain 2026.10.21

Domain models and shared types for the Bamboo agent framework
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
//! Durable Root tool authority, separate from prompt or permission suggestions.

use super::{model_context::ModelContextResetReason, Session, SessionKind};

/// Root product policy, independent of a model call's `ReasoningEffort`.
/// Ultra delegates planning/execution and keeps verification at the Root.
/// It is projected from existing durable Root authority, never persisted twice.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RootThinkingMode {
    Standard,
    Ultra,
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
#[error("thinking_mode and root orchestration enabled selection conflict")]
pub struct RootThinkingModeConflict;

impl RootThinkingMode {
    /// Optional DTO field: omission is allowed, explicit null is not a mode.
    pub fn deserialize_selection<'de, D>(deserializer: D) -> Result<Option<Self>, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        <Self as serde::Deserialize>::deserialize(deserializer).map(Some)
    }

    pub fn from_enabled(enabled: bool) -> Self {
        if enabled {
            Self::Ultra
        } else {
            Self::Standard
        }
    }

    pub fn enabled(self) -> bool {
        self == Self::Ultra
    }

    /// Normalize canonical and legacy selectors before existing admission.
    pub fn resolve_selection(
        mode: Option<Self>,
        enabled: Option<bool>,
    ) -> Result<Option<bool>, RootThinkingModeConflict> {
        if let (Some(mode), Some(enabled)) = (mode, enabled) {
            if mode.enabled() != enabled {
                return Err(RootThinkingModeConflict);
            }
        }
        Ok(mode.map(Self::enabled).or(enabled))
    }
}

/// Exact execution identities admitted for an orchestration-only Root.
/// Unknown tools, external providers, and legacy aliases do not enter this
/// list; callers first resolve a registered execution identity.
pub const ROOT_ORCHESTRATION_TOOLS: [&str; 18] = [
    "SubAgent",
    "spawn_session",
    "Plan",
    "Task",
    "session_history_current",
    "session_history",
    "session_message",
    "Read",
    "Grep",
    "Glob",
    "GetFileInfo",
    "ViewImage",
    "work_overview",
    "work_search",
    "work_inspect",
    "work_changes",
    "work_update",
    "work_dispatch",
];

pub fn orchestration_only_allows_execution_name(execution_name: &str) -> bool {
    ROOT_ORCHESTRATION_TOOLS.contains(&execution_name)
}

/// Exact Supervisor surface, independent of an ordinary Root's thinking mode.
/// These are delegation or bounded business views, never raw workspace/file,
/// process, Skill, Workflow or external-provider execution. Concrete Session
/// ports still require their live Host instance proof; names grant nothing.
pub const SUPERVISOR_ORCHESTRATION_TOOLS: [&str; 14] = [
    "SubAgent",
    "spawn_session",
    "Plan",
    "Task",
    "session_history_current",
    "session_history",
    "session_message",
    "session_control",
    "work_overview",
    "work_search",
    "work_inspect",
    "work_changes",
    "work_update",
    "work_dispatch",
];

pub fn orchestration_only_allows_execution_name_for_supervisor(
    execution_name: &str,
    executing_supervisor: bool,
) -> bool {
    if executing_supervisor {
        SUPERVISOR_ORCHESTRATION_TOOLS.contains(&execution_name)
    } else {
        orchestration_only_allows_execution_name(execution_name)
    }
}

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum RootToolAuthorityError {
    #[error("only a Root Session may select orchestration-only tool authority")]
    NotRoot,
    #[error("Root tool authority revision cannot advance")]
    RevisionOverflow,
    #[error("Root tool authority snapshot is stale or inconsistent")]
    StaleSnapshot,
    #[error("orchestration-only Root cannot enter while legacy Plan mode is active")]
    LegacyPlanActive,
    #[error("orchestration-only Root cannot use a selected Skill or Workflow")]
    WorkflowSelected,
}

impl Session {
    /// A trusted Supervisor's delegation-only business authority is independent
    /// of thinking mode. Callers still need Storage's canonical identity proof.
    /// Thinking-mode counters are not business permission epochs. Existing
    /// positive Work binding revisions remain in their canonical Ticket store;
    /// the Host verifies their unchanged Supervisor namespace separately.
    pub fn supervisor_orchestration_revision(&self) -> Option<u64> {
        self.supervisor_incarnation_id().map(|_| 1)
    }

    pub fn root_thinking_mode(&self) -> RootThinkingMode {
        RootThinkingMode::from_enabled(self.root_orchestration_only_enabled())
    }

    pub fn root_orchestration_only_enabled(&self) -> bool {
        self.kind == SessionKind::Root
            && self.parent_session_id.is_none()
            && self.root_orchestration_only
    }

    /// Called only by a host-owned selection, never by a model tool.
    pub fn set_root_orchestration_only(
        &mut self,
        enabled: bool,
    ) -> Result<(), RootToolAuthorityError> {
        if self.kind != SessionKind::Root || self.parent_session_id.is_some() {
            return Err(RootToolAuthorityError::NotRoot);
        }
        if enabled {
            self.validate_root_orchestration_compatibility()?;
        }
        if self.root_orchestration_only == enabled {
            return Ok(());
        }
        let next = self
            .root_tool_authority_revision
            .checked_add(1)
            .ok_or(RootToolAuthorityError::RevisionOverflow)?;
        self.root_orchestration_only = enabled;
        self.root_tool_authority_revision = next;
        if self.model_context_state.is_some() {
            self.reset_model_context_epoch(ModelContextResetReason::CacheScopeChanged);
        }
        Ok(())
    }

    /// Keep the narrow tool catalog usable when an old turn or a new request
    /// carries a mode that requires tools outside the Root allowlist.
    pub fn validate_root_orchestration_compatibility(&self) -> Result<(), RootToolAuthorityError> {
        if self
            .agent_runtime_state
            .as_ref()
            .is_some_and(|state| state.plan_mode.is_some())
        {
            return Err(RootToolAuthorityError::LegacyPlanActive);
        }
        if self.selected_skill_ids().is_some_and(|ids| !ids.is_empty()) {
            return Err(RootToolAuthorityError::WorkflowSelected);
        }
        Ok(())
    }

    /// Derived model posture, not a persisted selection or permission grant.
    /// A trusted Supervisor orchestrates in both thinking modes. Children and
    /// ordinary Roots retain their own independent mode and permissions.
    pub fn model_orchestration_only_enabled(&self) -> bool {
        self.root_orchestration_only_enabled() || self.supervisor_incarnation_id().is_some()
    }

    /// Defense in depth at both catalog projection and final dispatch.
    pub fn allows_model_tool_execution(&self, execution_name: &str) -> bool {
        !self.model_orchestration_only_enabled()
            || orchestration_only_allows_execution_name_for_supervisor(
                execution_name,
                self.supervisor_incarnation_id().is_some(),
            )
    }

    /// Refresh a running snapshot from the durable control plane before tool
    /// dispatch. An older snapshot can never loosen a selected Root policy.
    pub fn adopt_root_tool_authority_from(
        &mut self,
        latest: &Session,
    ) -> Result<(), RootToolAuthorityError> {
        // A tool policy revision is meaningful only within the same Session
        // lifetime. A deleted Root ID can be recreated with a fresh birth, so
        // matching the ID and revision alone would authorize an old SDK run.
        fn root_id(session: &Session) -> &str {
            if session.kind == SessionKind::Root && session.root_session_id.is_empty() {
                session.id.as_str()
            } else {
                session.root_session_id.as_str()
            }
        }
        if !super::compatibility::same_session_tool_contract(
            self.session_version,
            latest.session_version,
        ) || self.id != latest.id
            || self.kind != latest.kind
            || self.created_at != latest.created_at
            || self.authority_identity != latest.authority_identity
            || self.parent_session_id != latest.parent_session_id
            || root_id(self) != root_id(latest)
            || self.spawn_depth != latest.spawn_depth
            || (self.root_orchestration_only && self.root_tool_authority_revision == 0)
            || (latest.root_orchestration_only && latest.root_tool_authority_revision == 0)
            || latest.root_tool_authority_revision < self.root_tool_authority_revision
            || (latest.root_tool_authority_revision == self.root_tool_authority_revision
                && latest.root_orchestration_only != self.root_orchestration_only)
            || latest.root_mode_transition_epoch < self.root_mode_transition_epoch
            || (latest.root_mode_transition_epoch == self.root_mode_transition_epoch
                && latest.root_mode_operations != self.root_mode_operations)
        {
            return Err(RootToolAuthorityError::StaleSnapshot);
        }
        let selections = latest.root_tool_authority_revision - self.root_tool_authority_revision;
        self.root_orchestration_only = latest.root_orchestration_only;
        self.root_tool_authority_revision = latest.root_tool_authority_revision;
        self.root_mode_transition_epoch = latest.root_mode_transition_epoch;
        self.root_mode_operations = latest.root_mode_operations.clone();
        if selections > 0 {
            // A running snapshot may miss several selections, including a
            // round trip to the same mode. Adopt the durable invalidation;
            // resetting the local ledger once could retain an older epoch.
            self.model_context_state = latest.model_context_state.clone();
            self.provider_transcript.invalidate_repeated(
                super::provider_transcript::ProviderTranscriptResetReason::CacheScopeChanged,
                selections,
            );
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::session::{AgentRuntimeState, ModelContextState, PlanModeState, PlanModeStatus};

    #[test]
    fn supervisor_direct_files_and_processes_require_delegation_in_both_modes() {
        use crate::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        let mut supervisor = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        supervisor.authority_identity = SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        for ultra in [false, true, false] {
            supervisor.set_root_orchestration_only(ultra).unwrap();
            let restored: Session =
                serde_json::from_value(serde_json::to_value(&supervisor).unwrap()).unwrap();
            for name in [
                "Read",
                "Grep",
                "Glob",
                "GetFileInfo",
                "ViewImage",
                "Write",
                "Edit",
                "NotebookEdit",
                "apply_patch",
                "Bash",
                "exec_command",
                "write_stdin",
                "load_skill",
                "workflow_run",
                "browser",
                "browser_eval",
                "mcp__vendor__Read",
                "default::Read",
                "vendor::Read",
            ] {
                assert!(
                    !restored.allows_model_tool_execution(name),
                    "Supervisor mode={ultra} must delegate {name}"
                );
            }
            for name in [
                "SubAgent",
                "Plan",
                "Task",
                "session_control",
                "session_history",
            ] {
                assert!(restored.allows_model_tool_execution(name), "{name}");
            }
            let child = Session::new_child_of("worker", &restored, "model", "worker");
            assert!(child.authority_identity.is_ordinary());
            assert!(child.allows_model_tool_execution("Read"));
            assert!(child.allows_model_tool_execution("Edit"));
            assert!(child.allows_model_tool_execution("exec_command"));
        }
        let mut ordinary = Session::new("ordinary", "model");
        for ultra in [false, true] {
            ordinary.set_root_orchestration_only(ultra).unwrap();
            assert!(ordinary.allows_model_tool_execution("Read"));
            assert_eq!(ordinary.supervisor_incarnation_id(), None);
            // Standard's coarse tool policy is not the concrete Host port's
            // management authorization. Keep its existing surface unchanged.
            if ultra {
                assert!(!ordinary.allows_model_tool_execution("session_control"));
            }
        }
    }

    #[test]
    fn supervisor_delegation_first_does_not_depend_on_ultra_or_leak_to_children() {
        use crate::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        let mut supervisor = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        supervisor.authority_identity = SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        for ultra in [false, true, false] {
            supervisor.set_root_orchestration_only(ultra).unwrap();
            let restored: Session =
                serde_json::from_value(serde_json::to_value(&supervisor).unwrap()).unwrap();
            for name in SUPERVISOR_ORCHESTRATION_TOOLS {
                assert!(
                    restored.allows_model_tool_execution(name),
                    "{ultra}: {name}"
                );
            }
            for name in [
                "exec_command",
                "write_stdin",
                "Bash",
                "Edit",
                "Write",
                "apply_patch",
                "load_skill",
                "workflow_run",
                "mcp__vendor__read",
                "default::Read",
            ] {
                assert!(
                    !restored.allows_model_tool_execution(name),
                    "Supervisor {ultra}: {name}"
                );
            }
            let child = Session::new_child_of("worker", &restored, "model", "worker");
            assert!(child.authority_identity.is_ordinary());
            assert!(child.allows_model_tool_execution("Edit"));
            assert!(child.allows_model_tool_execution("exec_command"));
        }
        let mut ordinary = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        ordinary.metadata.insert("role".into(), "supervisor".into());
        assert!(ordinary.allows_model_tool_execution("Edit"));
        ordinary.set_root_orchestration_only(true).unwrap();
        assert!(!ordinary.allows_model_tool_execution("session_control"));
        assert!(ordinary.allows_model_tool_execution("session_history"));
    }

    #[test]
    fn trusted_supervisor_session_management_survives_thinking_mode_selection() {
        use crate::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        let mut supervisor = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        supervisor.authority_identity = SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        for ultra in [false, true] {
            supervisor.set_root_orchestration_only(ultra).unwrap();
            let restored: Session =
                serde_json::from_value(serde_json::to_value(&supervisor).unwrap()).unwrap();
            for name in ["session_control", "session_history"] {
                assert!(
                    restored.allows_model_tool_execution(name),
                    "trusted Supervisor lost {name} in {:?}",
                    restored.root_thinking_mode()
                );
            }
        }
    }

    #[test]
    fn ultra_management_exception_requires_canonical_supervisor_and_exact_tool() {
        use crate::{SessionAuthorityIdentity, DEFAULT_SUPERVISOR_SESSION_ID};
        let mut supervisor = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        supervisor.authority_identity = SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        supervisor.set_root_orchestration_only(true).unwrap();
        for mutation in [
            |s: &mut Session| s.authority_identity = SessionAuthorityIdentity::Ordinary,
            |s: &mut Session| s.id = "other".into(),
            |s: &mut Session| s.root_session_id = "other".into(),
            |s: &mut Session| s.spawn_depth = 1,
            |s: &mut Session| {
                s.authority_identity = SessionAuthorityIdentity::Supervisor {
                    incarnation_id: uuid::Uuid::nil(),
                }
            },
        ] {
            let mut invalid = supervisor.clone();
            mutation(&mut invalid);
            invalid.metadata.insert("role".into(), "supervisor".into());
            assert!(!invalid.allows_model_tool_execution("session_control"));
            assert!(invalid.allows_model_tool_execution("session_history"));
        }
        for name in [
            "default::session_control",
            "vendor::session_control",
            "exec_command",
            "Write",
        ] {
            assert!(!supervisor.allows_model_tool_execution(name), "{name}");
        }
        let child = Session::new_child_of("child", &supervisor, "model", "child");
        assert_eq!(child.supervisor_incarnation_id(), None);
        let mut ordinary = Session::new(DEFAULT_SUPERVISOR_SESSION_ID, "model");
        ordinary.set_root_orchestration_only(true).unwrap();
        ordinary.metadata.insert("role".into(), "supervisor".into());
        assert!(!ordinary.allows_model_tool_execution("session_control"));
        assert!(ordinary.allows_model_tool_execution("session_history"));
    }

    #[test]
    fn thinking_mode_is_a_derived_root_policy_independent_of_effort() {
        use crate::ReasoningEffort;
        let mut root = Session::new("ultra-root", "model");
        root.reasoning_effort = Some(ReasoningEffort::Max);
        root.set_root_orchestration_prompt_enabled(true);
        assert_eq!(root.root_thinking_mode(), RootThinkingMode::Standard);
        root.set_root_orchestration_only(true).unwrap();
        let persisted = serde_json::to_value(&root).unwrap();
        assert!(
            persisted.get("thinking_mode").is_none(),
            "no second persisted authority"
        );
        let reloaded: Session = serde_json::from_value(persisted.clone()).unwrap();
        assert_eq!(reloaded.root_thinking_mode(), RootThinkingMode::Ultra);
        assert_eq!(reloaded.reasoning_effort, Some(ReasoningEffort::Max));
        assert_eq!(
            serde_json::to_value(&reloaded).unwrap(),
            persisted,
            "projection never writes"
        );
        let mut child = Session::new_child_of("ultra-child", &reloaded, "model", "child");
        assert_eq!(child.root_thinking_mode(), RootThinkingMode::Standard);
        assert_eq!(child.reasoning_effort, None);
        child.root_orchestration_only = true;
        assert_eq!(
            child.root_thinking_mode(),
            RootThinkingMode::Standard,
            "raw child bool has no authority"
        );
        assert_eq!(
            child.set_root_orchestration_only(true),
            Err(RootToolAuthorityError::NotRoot)
        );
        assert_eq!(
            serde_json::to_string(&RootThinkingMode::Ultra).unwrap(),
            "\"ultra\""
        );
        assert_eq!(
            serde_json::from_str::<RootThinkingMode>("\"standard\"").unwrap(),
            RootThinkingMode::Standard
        );
        assert!(serde_json::from_str::<RootThinkingMode>("\"max\"").is_err());
        assert!(serde_json::from_str::<ReasoningEffort>("\"ultra\"").is_err());
    }

    #[test]
    fn canonical_and_legacy_thinking_selectors_share_one_boolean_request() {
        assert_eq!(RootThinkingMode::resolve_selection(None, None), Ok(None));
        for enabled in [false, true] {
            let mode = RootThinkingMode::from_enabled(enabled);
            assert_eq!(
                RootThinkingMode::resolve_selection(Some(mode), None),
                Ok(Some(enabled))
            );
            assert_eq!(
                RootThinkingMode::resolve_selection(None, Some(enabled)),
                Ok(Some(enabled))
            );
            assert_eq!(
                RootThinkingMode::resolve_selection(Some(mode), Some(enabled)),
                Ok(Some(enabled))
            );
            assert_eq!(
                RootThinkingMode::resolve_selection(Some(mode), Some(!enabled)),
                Err(RootThinkingModeConflict)
            );
        }
    }

    #[test]
    fn root_selection_is_persistent_and_child_does_not_inherit_it() {
        let mut root = Session::new("root", "model");
        root.set_root_orchestration_only(true).unwrap();
        assert_eq!(root.root_tool_authority_revision, 1);
        let reloaded: Session =
            serde_json::from_str(&serde_json::to_string(&root).unwrap()).unwrap();
        assert!(reloaded.root_orchestration_only_enabled());
        let mut child = Session::new_child_of("child", &reloaded, "model", "child");
        assert!(!child.root_orchestration_only_enabled());
        assert_eq!(child.root_tool_authority_revision, 0);
        assert_eq!(
            child.set_root_orchestration_only(false),
            Err(RootToolAuthorityError::NotRoot)
        );
        assert!(child.allows_model_tool_execution("Bash"));
    }

    #[test]
    fn root_allowlist_is_exact_and_denies_unknown_tools() {
        let mut root = Session::new("root", "model");
        root.set_root_orchestration_only(true).unwrap();
        for tool in ROOT_ORCHESTRATION_TOOLS {
            assert!(root.allows_model_tool_execution(tool), "{tool}");
        }
        for tool in [
            "exec_command",
            "write_stdin",
            "Bash",
            "Edit",
            "Write",
            "WebFetch",
            "workflow_run",
            "mcp__x__read",
            "read_file",
            "default::Read",
        ] {
            assert!(!root.allows_model_tool_execution(tool), "{tool}");
        }
        assert_eq!(root.root_tool_authority_revision, 1);
        root.set_root_orchestration_only(true).unwrap();
        assert_eq!(root.root_tool_authority_revision, 1);
        root.set_root_orchestration_only(false).unwrap();
        assert_eq!(root.root_tool_authority_revision, 2);
        assert!(root.allows_model_tool_execution("Bash"));
    }

    #[test]
    fn durable_refresh_adopts_tightening_and_rejects_stale_loosen() {
        let mut running = Session::new("root", "model");
        let mut durable = running.clone();
        durable.set_root_orchestration_only(true).unwrap();
        running.adopt_root_tool_authority_from(&durable).unwrap();
        assert!(!running.allows_model_tool_execution("Bash"));
        assert_eq!(
            durable.adopt_root_tool_authority_from(&Session::new("root", "model")),
            Err(RootToolAuthorityError::StaleSnapshot)
        );
        durable.set_root_orchestration_only(false).unwrap();
        running.adopt_root_tool_authority_from(&durable).unwrap();
        assert!(running.allows_model_tool_execution("Bash"));
    }

    #[test]
    fn durable_refresh_rejects_a_different_birth_identity_or_lineage() {
        let running = Session::new("root", "model");
        let mut other_birth = running.clone();
        other_birth.created_at += chrono::Duration::microseconds(1);
        assert_eq!(
            running.clone().adopt_root_tool_authority_from(&other_birth),
            Err(RootToolAuthorityError::StaleSnapshot)
        );

        let mut other_identity = running.clone();
        other_identity.authority_identity = super::super::SessionAuthorityIdentity::Supervisor {
            incarnation_id: uuid::Uuid::new_v4(),
        };
        assert_eq!(
            running
                .clone()
                .adopt_root_tool_authority_from(&other_identity),
            Err(RootToolAuthorityError::StaleSnapshot)
        );

        let mut other_lineage = running.clone();
        other_lineage.root_session_id = "another-root".into();
        assert_eq!(
            running
                .clone()
                .adopt_root_tool_authority_from(&other_lineage),
            Err(RootToolAuthorityError::StaleSnapshot)
        );
        other_lineage = running.clone();
        other_lineage.spawn_depth = 1;
        assert_eq!(
            running
                .clone()
                .adopt_root_tool_authority_from(&other_lineage),
            Err(RootToolAuthorityError::StaleSnapshot)
        );

        // Legacy Roots can omit this derived field without changing lineage.
        let mut legacy = running.clone();
        legacy.root_session_id.clear();
        legacy.adopt_root_tool_authority_from(&running).unwrap();
    }

    #[test]
    fn root_selection_rejects_legacy_plan_or_workflow_that_needs_other_tools() {
        let mut root = Session::new("root", "model");
        let runtime = AgentRuntimeState {
            plan_mode: Some(PlanModeState {
                entered_at: chrono::Utc::now(),
                pre_permission_mode: "default".to_string(),
                plan_file_path: None,
                status: PlanModeStatus::Exploring,
            }),
            ..AgentRuntimeState::default()
        };
        root.agent_runtime_state = Some(runtime);
        assert_eq!(
            root.set_root_orchestration_only(true),
            Err(RootToolAuthorityError::LegacyPlanActive)
        );
        root.agent_runtime_state = None;
        root.set_selected_skill_ids(vec!["workflow".to_string()]);
        assert_eq!(
            root.set_root_orchestration_only(true),
            Err(RootToolAuthorityError::WorkflowSelected)
        );
        root.clear_selected_skill_ids();
        root.set_root_orchestration_only(true).unwrap();
        root.set_selected_skill_ids(vec!["workflow".to_string()]);
        assert_eq!(
            root.validate_root_orchestration_compatibility(),
            Err(RootToolAuthorityError::WorkflowSelected)
        );
    }

    #[test]
    fn live_authority_adoption_resets_prior_model_context_epoch() {
        for enabled in [false, true] {
            let mut running = Session::new("root", "model");
            if !enabled {
                running.set_root_orchestration_only(true).unwrap();
            }
            running.model_context_state = Some(ModelContextState {
                prefix_epoch: 4,
                cache_scope_sha256: Some("prior-provider-scope".to_string()),
                ..ModelContextState::default()
            });
            let mut durable = running.clone();
            durable.set_root_orchestration_only(enabled).unwrap();
            running.adopt_root_tool_authority_from(&durable).unwrap();
            let context = running.model_context_state.as_ref().unwrap();
            assert_eq!(context.prefix_epoch, 5);
            assert!(context.cache_scope_sha256.is_none());
            assert_eq!(
                context.last_reset_reason,
                Some(ModelContextResetReason::CacheScopeChanged)
            );
        }
    }

    #[test]
    fn live_authority_adoption_preserves_all_missed_mode_resets() {
        let mut running = Session::new("root", "model");
        running.model_context_state = Some(ModelContextState {
            prefix_epoch: 4,
            cache_scope_sha256: Some("old scope".into()),
            ..Default::default()
        });
        running
            .activate_provider_transcript_route(
                super::super::provider_transcript::ProviderFamily::OpenAi,
                super::super::provider_transcript::ProviderProtocol::OpenAiResponsesV1,
                &"a".repeat(64),
            )
            .unwrap();
        let mut durable = running.clone();
        durable.set_root_orchestration_only(true).unwrap();
        // A prepared round between selections makes the second reset a new
        // ledger boundary rather than the existing pending-reset coalescing.
        durable
            .model_context_state
            .as_mut()
            .unwrap()
            .cache_scope_sha256 = Some("new scope".into());
        durable.set_root_orchestration_only(false).unwrap();
        assert_eq!(running.root_thinking_mode(), durable.root_thinking_mode());
        running.adopt_root_tool_authority_from(&durable).unwrap();
        assert_eq!(running.model_context_state, durable.model_context_state);
        assert_eq!(
            running.model_context_state.as_ref().unwrap().prefix_epoch,
            6
        );
        assert_eq!(running.provider_transcript, durable.provider_transcript);
        // A recovery-only epoch advance must preserve current owner work.
        running
            .model_context_state
            .as_mut()
            .unwrap()
            .cache_scope_sha256 = Some("owner scope".into());
        let owner_context = running.model_context_state.clone();
        durable.root_mode_transition_epoch += 1;
        running.adopt_root_tool_authority_from(&durable).unwrap();
        assert_eq!(running.model_context_state, owner_context);
    }
}