bamboo-engine 2026.10.16

Execution engine and orchestration 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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
//! Real live-owner delivery/checkpoint contract tests. No provider is invoked.
//! Public runner/provider wiring is covered separately by the owner.

use super::*;

mod terminal_owner_mechanism_tests;
use crate::runtime::config::PromptMemoryFlags;
use crate::session_activation::{
    SessionActivationReserveOutcome, SessionActivationRouter, SessionActivationSpawner,
    SessionRunRegistration,
};
use crate::session_app::supervisor::SupervisorSessionService;
use crate::{SessionMessenger, SessionMessengerError, SessionRepository};
use async_trait::async_trait;
use bamboo_agent_core::tools::{FunctionCall, ToolCall};
use bamboo_domain::{
    scoped_loop_consumptions, AgentRuntimeState, AgentStatusState, LoopControlAction, Role,
    ScopedLoopControlBinding, ScopedLoopControlConsumption, ScopedLoopControlInput,
    SessionActivationDisposition, SessionActivationError, SessionActivationPort, SessionInboxError,
    SessionInboxLimits, SessionInboxPort, SessionRunConflict, SessionRunDeliveryGuard, Storage,
    SupervisorReference,
};
use bamboo_storage::{FileSessionInbox, LockedSessionStore, SessionStoreV2};
use chrono::{DateTime, Utc};
use serde_json::Value;
use std::sync::atomic::AtomicUsize;

const TARGET: &str = "scoped-loop-target";
const OWNER: &str = "registered-scoped-loop-owner";
const EXECUTION: &str = "scoped-loop-pipeline-execution";
const ORIGINAL_REQUEST: &str = "Preserve this independently owned task and context.";

#[derive(Default)]
struct NoLaunch {
    reservations: AtomicUsize,
}

#[async_trait]
impl SessionActivationSpawner for NoLaunch {
    async fn reserve_activation(
        &self,
        _target_session_id: &str,
        _inbox_generation: u64,
    ) -> Result<SessionActivationReserveOutcome, SessionActivationError> {
        self.reservations.fetch_add(1, Ordering::SeqCst);
        Err(SessionActivationError::Internal(
            "scoped control must never reserve a successor".into(),
        ))
    }
}

struct RecordingActivation {
    router: Arc<SessionActivationRouter>,
    requests: AtomicUsize,
}

#[async_trait]
impl SessionActivationPort for RecordingActivation {
    fn scoped_transport_runtime_instance(&self) -> Option<Arc<()>> {
        self.router.scoped_transport_runtime_instance()
    }

    fn retain_expected_run_blocking(
        &self,
        target: &str,
        birth: DateTime<Utc>,
        expected_run: &str,
    ) -> Result<Arc<dyn SessionRunDeliveryGuard>, SessionRunConflict> {
        self.router
            .retain_expected_run_blocking(target, birth, expected_run)
    }

    async fn observe_supervisor_loop(
        &self,
        supervisor: &SupervisorReference,
        target: &str,
        expected_link_revision: Option<u64>,
        action: LoopControlAction,
    ) -> Result<ScopedLoopControlBinding, SessionInboxError> {
        self.router
            .observe_supervisor_loop(supervisor, target, expected_link_revision, action)
            .await
    }

    fn retain_supervisor_loop_blocking(
        &self,
        binding: &ScopedLoopControlBinding,
    ) -> Result<Arc<dyn SessionRunDeliveryGuard>, SessionRunConflict> {
        self.router.retain_supervisor_loop_blocking(binding)
    }

    async fn notify_active_delivery(&self, target: &str, generation: u64) -> bool {
        self.router.notify_active_delivery(target, generation).await
    }

    async fn request_activation(
        &self,
        target: &str,
        generation: u64,
    ) -> Result<SessionActivationDisposition, SessionActivationError> {
        self.requests.fetch_add(1, Ordering::SeqCst);
        self.router.request_activation(target, generation).await
    }
}

struct Fixture {
    registration: Option<SessionRunRegistration>,
    router: Arc<SessionActivationRouter>,
    activation: Arc<RecordingActivation>,
    spawner: Arc<NoLaunch>,
    storage: Arc<dyn Storage>,
    inbox: Arc<FileSessionInbox>,
    supervisor_service: SupervisorSessionService,
    supervisor: SupervisorReference,
    link_revision: u64,
    session: Session,
    original_messages: Value,
    config: AgentLoopConfig,
    cancel: CancellationToken,
    _dir: tempfile::TempDir,
}

impl Fixture {
    async fn new(granted: bool) -> Self {
        Self::new_with_limits(granted, SessionInboxLimits::default()).await
    }

    async fn new_with_limits(granted: bool, limits: SessionInboxLimits) -> Self {
        let dir = tempfile::tempdir().unwrap();
        let concrete = Arc::new(
            SessionStoreV2::new(dir.path().join("sessions"))
                .await
                .unwrap(),
        );
        let storage: Arc<dyn Storage> = concrete.clone();
        let supervisor_service = SupervisorSessionService::new(storage.clone());
        let supervisor: SupervisorReference = (&supervisor_service
            .get_or_create_default("synthetic-supervisor")
            .await
            .unwrap())
            .into();
        let mut session = Session::new(TARGET, "synthetic-target");
        session.set_project_id_meta("project-a");
        session.metadata_version = 3;
        session.add_message(Message::system("Original independent Root context."));
        session.add_message(Message::user(ORIGINAL_REQUEST));
        session.add_message(Message::assistant("Original retained fact.", None));
        // Match the actual owner's durable runtime identity before installing
        // its live grant. This seeds no LoopState, receipt or consumption.
        let mut runtime = AgentRuntimeState::new(OWNER);
        runtime.execution_id = Some(EXECUTION.into());
        runtime.status = AgentStatusState::Running;
        runtime.round.max_rounds = Some(30);
        session.agent_runtime_state = Some(runtime);
        storage.save_session(&session).await.unwrap();
        supervisor_service
            .configure_project_scope(
                &supervisor,
                0,
                ["project-a".parse().unwrap()].into_iter().collect(),
            )
            .await
            .unwrap();
        let attached = supervisor_service
            .attach(&supervisor, 1, TARGET)
            .await
            .unwrap();
        let link_revision = attached.link_revision.unwrap();
        let executing_supervisor = storage
            .load_session(&supervisor.session_id)
            .await
            .unwrap()
            .unwrap();

        let inbox = Arc::new(FileSessionInbox::new(concrete, limits));
        let router = SessionActivationRouter::new();
        router.set_inbox(inbox.clone());
        let spawner = Arc::new(NoLaunch::default());
        router.set_spawner(spawner.clone()).await;
        let registration = router.register_session_run(&session, OWNER).await.unwrap();
        let activation = Arc::new(RecordingActivation {
            router: router.clone(),
            requests: AtomicUsize::new(0),
        });

        let mut policy = LoopControlConfig::new(5, 30);
        if granted {
            let grant = SupervisorLoopControlGrant::new(
                supervisor.clone(),
                executing_supervisor.root_tool_authority_revision,
                link_revision,
                [
                    LoopControlAction::Status,
                    LoopControlAction::Start,
                    LoopControlAction::Update,
                    LoopControlAction::Stop,
                ],
                3,
                12,
            )
            .unwrap();
            policy = policy.supervisor_control(grant).unwrap();
        }
        policy.bind_owner(registration.ownership(), &session);
        let cancel = CancellationToken::new();
        policy.bind_execution(EXECUTION, cancel.clone()).unwrap();
        if granted {
            policy
                .register_supervisor_control(&session, &storage)
                .await
                .unwrap();
        }

        let persistence = Arc::new(LockedSessionStore::new(storage.clone()));
        let repository = Arc::new(SessionRepository::new(
            Arc::new(Default::default()),
            storage.clone(),
            persistence,
        ));
        let mut config = AgentLoopConfig {
            loop_control: Some(policy),
            storage: Some(storage.clone()),
            persistence: Some(repository),
            session_inbox: Some(inbox.clone()),
            guidance_active_run_id: Some(OWNER.into()),
            permission_mode: Some(bamboo_config::PermissionMode::Default),
            prompt_memory_flags: PromptMemoryFlags {
                project_prompt_injection: false,
                relevant_recall: false,
                relevant_recall_rerank: false,
                project_first_dream: false,
                ledger_agenda: false,
            },
            ..Default::default()
        };
        config.run_budget.max_rounds = Some(30);
        let original_messages = serde_json::to_value(&session.messages).unwrap();
        Self {
            registration: Some(registration),
            router,
            activation,
            spawner,
            storage,
            inbox,
            supervisor_service,
            supervisor,
            link_revision,
            session,
            original_messages,
            config,
            cancel,
            _dir: dir,
        }
    }

    fn messenger(&self) -> SessionMessenger {
        SessionMessenger::new(
            self.storage.clone(),
            self.inbox.clone(),
            self.activation.clone(),
        )
    }

    fn policy(&self) -> &LoopControlConfig {
        self.config.loop_control.as_ref().unwrap()
    }

    async fn send(&self, command: &LoopControlRequest) -> Result<Value, SessionMessengerError> {
        self.messenger()
            .supervisor_loop_control(
                &self.supervisor,
                TARGET,
                Some(self.link_revision),
                command,
                None,
            )
            .await
    }

    async fn status(&self, operation: Option<&str>) -> Result<Value, SessionMessengerError> {
        // Bootstrap is a real service read with the entire canonical/live
        // authority path, not a guessed revision or a test-only grant.
        self.messenger()
            .supervisor_loop_control(
                &self.supervisor,
                TARGET,
                None,
                &LoopControlRequest::Status,
                operation,
            )
            .await
    }

    async fn drain(&mut self, spent: u32) -> Result<(), AgentError> {
        scoped::drain(&mut self.session, &self.config, spent).await
    }

    async fn admit(&mut self) -> bool {
        counted_loop::before_round(&mut self.session, &self.config, EXECUTION)
            .await
            .unwrap()
    }

    fn state(&self) -> LoopState {
        counted_loop::read_loop_state(&self.session)
            .unwrap()
            .unwrap()
    }

    async fn durable(&self) -> Session {
        self.storage.load_session(TARGET).await.unwrap().unwrap()
    }

    fn assert_no_activation(&self) {
        assert_eq!(self.activation.requests.load(Ordering::SeqCst), 0);
        assert_eq!(self.spawner.reservations.load(Ordering::SeqCst), 0);
    }

    async fn close(&mut self) {
        if let Some(mut registration) = self.registration.take() {
            registration.begin_finalization().await;
            let generation = self.inbox.inspect(TARGET).await.unwrap().generation;
            assert_eq!(registration.finish(generation).await.unwrap(), None);
        }
        self.assert_no_activation();
    }

    async fn detach(&self) {
        let revision = self
            .supervisor_service
            .inspect_scope(&self.supervisor)
            .await
            .unwrap()
            .state_revision;
        self.supervisor_service
            .detach(&self.supervisor, revision, TARGET)
            .await
            .unwrap();
    }

    async fn revoke_grant(&self) {
        assert!(
            self.router
                .revoke_supervisor_loop_control(
                    TARGET,
                    &self.policy().supervisor_grant_id().unwrap(),
                )
                .await
        );
    }

    async fn start_and_admit(&mut self) -> LoopControlRequest {
        let command = start("Remote A", 3, 12);
        let queued = self.send(&command).await.unwrap();
        assert_eq!(queued["admitted"], true);
        assert_eq!(queued["configured"], false);
        self.drain(0).await.unwrap();
        assert!(self.admit().await);
        command
    }

    async fn local_start(&mut self, objective: &str, iterations: u32, rounds: u32) {
        let command = start(objective, iterations, rounds);
        let arguments = serde_json::to_string(&command).unwrap();
        let command = bamboo_domain::parse_loop_control_request(&arguments).unwrap();
        self.session.add_message(Message::assistant(
            "",
            Some(vec![ToolCall {
                id: "local-host-authorized-start".into(),
                tool_type: "function".into(),
                function: FunctionCall {
                    name: "loop_control".into(),
                    arguments,
                },
            }]),
        ));
        let result = apply_current(
            &mut self.session,
            &self.config,
            &command,
            "local-host-authorized-start",
            0,
            false,
            false,
            0,
        )
        .await
        .unwrap();
        assert!(result.success, "{}", result.result);
    }

    fn update(&self, objective: &str) -> LoopControlRequest {
        let state = self.state();
        LoopControlRequest::Update {
            operation_id: uuid::Uuid::new_v4().to_string(),
            generation: state.generation,
            expected_revision: state.control.unwrap().control_revision,
            objective: Some(objective.into()),
            max_iterations: None,
            max_total_rounds: None,
        }
    }
}

fn start(objective: &str, iterations: u32, rounds: u32) -> LoopControlRequest {
    LoopControlRequest::Start {
        operation_id: uuid::Uuid::new_v4().to_string(),
        expected_generation: None,
        expected_revision: 0,
        objective: objective.into(),
        max_iterations: iterations,
        max_total_rounds: rounds,
    }
}

fn stored_receipt(state: &LoopState, command: &LoopControlRequest) -> LoopControlReceipt {
    state
        .control
        .as_ref()
        .unwrap()
        .operations
        .iter()
        .find(|stored| Some(stored.receipt.operation_id.as_str()) == operation_id(command))
        .unwrap()
        .receipt
        .clone()
}

fn consumption(session: &Session, command: &LoopControlRequest) -> ScopedLoopControlConsumption {
    let records = scoped_loop_consumptions(session).unwrap();
    let matching: Vec<_> = records
        .into_iter()
        .filter(|record| Some(record.operation_id.as_str()) == operation_id(command))
        .collect();
    assert_eq!(matching.len(), 1, "one durable consumption per operation");
    matching.into_iter().next().unwrap()
}

#[tokio::test]
async fn scoped_start_distinguishes_delivery_checkpoint_and_actual_iteration_including_zero_spent()
{
    for (iterations, rounds) in [(1, 1), (3, 12)] {
        let mut h = Fixture::new(true).await;
        let command = start("Remote objective", iterations, rounds);
        let op = operation_id(&command).unwrap();
        let initial = h.status(None).await.unwrap();
        assert_eq!(initial["configured"], false);
        assert_eq!(initial["objective_applied_actual"], false);
        assert!(initial["operation_receipt"].is_null());
        let queued = h.send(&command).await.unwrap();
        assert_eq!(queued["admitted"], true);
        assert_eq!(queued["configured"], false);
        assert_ne!(queued["applied"], true);
        let binding = h
            .activation
            .observe_supervisor_loop(
                &h.supervisor,
                TARGET,
                Some(h.link_revision),
                LoopControlAction::Start,
            )
            .await
            .unwrap();
        let carrier = ScopedLoopControlInput {
            binding,
            command: command.clone(),
        }
        .envelope()
        .unwrap();
        assert_eq!(queued["receipt_id"], carrier.id.as_str());
        assert!(
            carrier.to_provider_message().is_err(),
            "the typed control is never a User message"
        );
        let durable = h.durable().await;
        assert!(counted_loop::read_loop_state(&durable).unwrap().is_none());
        assert_eq!(
            serde_json::to_value(&durable.messages).unwrap(),
            h.original_messages
        );
        assert_eq!(h.inbox.inspect(TARGET).await.unwrap().pending, 1);
        assert!(!h.inbox.inspect(TARGET).await.unwrap().activation_pending());
        assert_eq!(h.status(Some(op)).await.unwrap()["configured"], false);

        h.drain(0).await.unwrap();
        let configured = h.durable().await;
        let state = counted_loop::read_loop_state(&configured).unwrap().unwrap();
        assert_eq!((state.iterations_started, state.rounds_started), (0, 0));
        assert_eq!(
            serde_json::to_value(&configured.messages).unwrap(),
            h.original_messages
        );
        assert_eq!(h.inbox.inspect(TARGET).await.unwrap().pending, 0);
        let proof = consumption(&configured, &command);
        assert!(proof.configured);
        assert!(proof.rejection.is_none());
        assert_eq!(
            proof.receipt,
            Some(serde_json::to_value(stored_receipt(&state, &command)).unwrap())
        );
        let status = h.status(Some(op)).await.unwrap();
        assert_eq!(status["configured"], true);
        assert_eq!(status["objective_applied_actual"], false);
        assert_eq!(
            status["operation_receipt"],
            serde_json::to_value(&proof).unwrap()
        );

        assert!(
            h.admit().await,
            "the first remote iteration consumes no phantom round"
        );
        assert_eq!(
            (h.state().iterations_started, h.state().rounds_started),
            (1, 1)
        );
        let durable = h.durable().await;
        assert_eq!(
            durable.messages.len(),
            h.original_messages.as_array().unwrap().len() + 1
        );
        let appended = durable.messages.last().unwrap();
        assert_eq!(appended.role, Role::User);
        assert_eq!(appended.content, "Remote objective");
        assert_eq!(
            appended.metadata.as_ref().unwrap()["runtime_kind"],
            "counted_loop_iteration"
        );
        let status = h.status(Some(op)).await.unwrap();
        assert_eq!(status["objective_applied_actual"], true);
        assert_eq!(
            status["operation_receipt"],
            serde_json::to_value(&proof).unwrap(),
            "acceptance receipt is immutable"
        );
        assert!(!h.cancel.is_cancelled());
        h.close().await;
    }
}

#[tokio::test]
async fn scoped_update_retry_is_exact_and_pending_goal_applies_only_after_current_iteration() {
    let mut h = Fixture::new(true).await;
    let original_start = h.start_and_admit().await;
    let command = h.update("Remote B");
    let op = operation_id(&command).unwrap();
    let first = h.send(&command).await.unwrap();
    let retry = h.send(&command).await.unwrap();
    assert_eq!(retry["receipt_id"], first["receipt_id"]);
    assert_eq!(retry["generation"], first["generation"]);
    assert_eq!(h.inbox.inspect(TARGET).await.unwrap().pending, 1);
    let mut conflicting = command.clone();
    if let LoopControlRequest::Update { objective, .. } = &mut conflicting {
        *objective = Some("Conflicting C".into());
    }
    assert!(h.send(&conflicting).await.is_err());
    h.drain(1).await.unwrap();
    let state = h.state();
    assert_eq!(state.objective, "Remote A");
    assert_eq!(
        state
            .control
            .as_ref()
            .unwrap()
            .pending_objective
            .as_ref()
            .unwrap()
            .objective,
        "Remote B"
    );
    assert_eq!(state.control.as_ref().unwrap().control_revision, 2);
    assert_eq!(state.control.as_ref().unwrap().applied_revision, 1);
    let proof = consumption(&h.durable().await, &command);
    assert!(proof.configured);
    assert_eq!(
        proof.receipt,
        Some(serde_json::to_value(stored_receipt(&state, &command)).unwrap())
    );
    let status = h.status(Some(op)).await.unwrap();
    assert_eq!(status["configured"], true);
    assert_eq!(status["objective_applied_actual"], false);
    assert_eq!(
        status["operation_receipt"],
        serde_json::to_value(&proof).unwrap()
    );
    assert_eq!(h.send(&command).await.unwrap()["configured"], true);
    h.drain(1).await.unwrap();
    assert_eq!(
        h.state(),
        state,
        "an ACKed retry cannot advance control or budget"
    );
    assert!(matches!(
        counted_loop::terminal(&mut h.session, &h.config)
            .await
            .unwrap(),
        counted_loop::TerminalDecision::Continue
    ));
    h.drain(1).await.unwrap();
    assert!(h.admit().await);
    let state = h.state();
    assert_eq!(
        (state.objective.as_str(), state.objective_revision),
        ("Remote B", 2)
    );
    assert_eq!(state.control.as_ref().unwrap().applied_revision, 2);
    assert_eq!(
        h.status(Some(op)).await.unwrap()["objective_applied_actual"],
        true
    );
    assert_eq!(consumption(&h.durable().await, &command), proof);
    assert_eq!(stored_receipt(&state, &original_start).accepted_revision, 1);
    assert_eq!(state.control.as_ref().unwrap().operations.len(), 2);
    h.close().await;
}

#[tokio::test]
async fn scoped_stop_preserves_context_and_admits_no_pending_goal_or_successor() {
    let mut h = Fixture::new(true).await;
    h.start_and_admit().await;
    let pending = h.update("Never admit B");
    h.send(&pending).await.unwrap();
    h.drain(1).await.unwrap();
    let before_messages = serde_json::to_value(&h.session.messages).unwrap();
    let state = h.state();
    let command = LoopControlRequest::Stop {
        operation_id: uuid::Uuid::new_v4().to_string(),
        generation: state.generation,
        expected_revision: state.control.unwrap().control_revision,
    };
    assert_eq!(h.send(&command).await.unwrap()["configured"], false);
    let trailing = h.update("Never consume after Stop");
    h.send(&trailing).await.unwrap();
    h.drain(1).await.unwrap();
    assert!(consumption(&h.durable().await, &command).configured);
    assert!(!scoped_loop_consumptions(&h.durable().await)
        .unwrap()
        .iter()
        .any(|record| record.operation_id
            == match &trailing {
                LoopControlRequest::Update { operation_id, .. } => operation_id.as_str(),
                _ => unreachable!(),
            }));
    let operation = operation_id(&command).unwrap();
    let status = h.status(Some(operation)).await.unwrap();
    assert_eq!(status["configured"], true);
    assert_eq!(status["loop"]["stop_requested"], true);
    assert_eq!(
        status["operation_receipt"],
        serde_json::to_value(consumption(&h.durable().await, &command)).unwrap()
    );
    let generation = h.inbox.inspect(TARGET).await.unwrap().generation;
    let retry = h.send(&command).await.unwrap();
    assert_eq!(retry["configured"], true);
    assert_eq!(
        h.inbox.inspect(TARGET).await.unwrap().generation,
        generation
    );
    assert!(!h.admit().await);
    assert_eq!(h.state().status, LoopStatus::Stopped);
    let stopped = h.status(Some(operation)).await.unwrap();
    assert_eq!(stopped["loop"]["status"], "stopped");
    assert_eq!(stopped["operation_receipt"], status["operation_receipt"]);
    assert_eq!(
        serde_json::to_value(&h.durable().await.messages).unwrap(),
        before_messages
    );
    assert!(
        !h.cancel.is_cancelled(),
        "stop is independent from user cancellation"
    );
    h.close().await;
}

#[tokio::test]
async fn scoped_status_and_mutations_require_an_extra_live_host_grant() {
    let mut h = Fixture::new(false).await;
    let command = start("No implicit authority", 1, 1);
    assert!(
        h.status(None).await.is_err(),
        "attachment and self opt-in do not grant remote status"
    );
    assert!(h.send(&command).await.is_err());
    assert!(counted_loop::read_loop_state(&h.durable().await)
        .unwrap()
        .is_none());
    assert_eq!(h.inbox.inspect(TARGET).await.unwrap().generation, 0);
    assert_eq!(
        serde_json::to_value(&h.durable().await.messages).unwrap(),
        h.original_messages
    );
    h.close().await;
}

#[tokio::test]
async fn scoped_queued_command_cannot_migrate_to_a_new_or_missing_owner() {
    for replacement in [false, true] {
        let mut h = Fixture::new(true).await;
        let command = start("Old owner only", 1, 2);
        h.send(&command).await.unwrap();
        h.close().await;
        if replacement {
            h.registration = Some(
                h.router
                    .register_session_run(&h.session, "replacement-owner")
                    .await
                    .unwrap(),
            );
        }
        assert!(h.status(None).await.is_err());
        assert!(h
            .send(&start("No successor permission", 1, 2))
            .await
            .is_err());
        assert!(
            h.drain(0).await.is_err(),
            "the old owner proof must never be reconstructed from target id"
        );
        let durable = h.durable().await;
        assert!(counted_loop::read_loop_state(&durable).unwrap().is_none());
        assert!(scoped_loop_consumptions(&durable).unwrap().is_empty());
        assert_eq!(
            serde_json::to_value(&durable.messages).unwrap(),
            h.original_messages
        );
        h.close().await;
    }
}

#[tokio::test]
async fn scoped_detach_or_grant_revocation_before_drain_cannot_publish_a_configuration_proof() {
    for detach in [false, true] {
        let mut h = Fixture::new(true).await;
        h.send(&start("Must remain unconfigured", 1, 2))
            .await
            .unwrap();
        if detach {
            h.detach().await;
        } else {
            h.revoke_grant().await;
        }
        assert!(h.drain(0).await.is_err());
        let durable = h.durable().await;
        assert!(counted_loop::read_loop_state(&durable).unwrap().is_none());
        assert!(scoped_loop_consumptions(&durable).unwrap().is_empty());
        assert_eq!(
            serde_json::to_value(&durable.messages).unwrap(),
            h.original_messages
        );
        assert!(
            h.status(None).await.is_err(),
            "status bootstrap is not authorization"
        );
        h.close().await;
    }
}

#[tokio::test]
async fn scoped_pending_remote_objective_keeps_its_authority_until_future_admission() {
    for detach in [false, true] {
        let mut h = Fixture::new(true).await;
        h.start_and_admit().await;
        let command = h.update("Future B needs a live grant");
        h.send(&command).await.unwrap();
        h.drain(1).await.unwrap();
        assert!(matches!(
            counted_loop::terminal(&mut h.session, &h.config)
                .await
                .unwrap(),
            counted_loop::TerminalDecision::Continue
        ));
        let before = h.durable().await;
        let state = counted_loop::read_loop_state(&before).unwrap().unwrap();
        if detach {
            h.detach().await;
        } else {
            h.revoke_grant().await;
        }
        let admission = async {
            h.drain(1).await?;
            counted_loop::before_round(&mut h.session, &h.config, EXECUTION).await
        }
        .await;
        assert!(
            admission.is_err(),
            "the complete safe boundary must recheck authority before a new goal is admitted"
        );
        let after = h.durable().await;
        assert_eq!(
            counted_loop::read_loop_state(&after).unwrap().unwrap(),
            state
        );
        assert_eq!(
            serde_json::to_value(&after.messages).unwrap(),
            serde_json::to_value(&before.messages).unwrap()
        );
        assert!(!after
            .messages
            .iter()
            .any(|message| message.role == Role::User
                && message.content == "Future B needs a live grant"));
        assert_eq!(
            consumption(&after, &command),
            consumption(&before, &command)
        );
        h.close().await;
    }
}

#[tokio::test]
async fn scoped_update_checks_effective_omitted_bounds_and_cas_without_consuming_loop_budget() {
    let mut h = Fixture::new(true).await;
    // Self-control is independently host-authorized to wider bounds; it does
    // not transfer those bounds to the stricter remote grant (3 / 12).
    h.local_start("Wider local A", 4, 20).await;
    assert!(h.admit().await);
    let original = h.state();
    assert_eq!(original.rounds_started, 2);
    for stale_cas in [false, true] {
        let mut command = h.update("Remote B");
        if stale_cas {
            if let LoopControlRequest::Update {
                expected_revision,
                max_iterations,
                max_total_rounds,
                ..
            } = &mut command
            {
                *expected_revision = 0;
                *max_iterations = Some(3);
                *max_total_rounds = Some(12);
            }
        }
        assert_eq!(h.send(&command).await.unwrap()["configured"], false);
        h.drain(2).await.unwrap();
        let durable = h.durable().await;
        assert_eq!(
            counted_loop::read_loop_state(&durable).unwrap().unwrap(),
            original
        );
        let proof = consumption(&durable, &command);
        assert!(!proof.configured);
        assert!(proof.receipt.is_none());
        assert!(proof
            .rejection
            .as_deref()
            .is_some_and(|reason| !reason.is_empty()));
        let status = h.status(operation_id(&command)).await.unwrap();
        assert_eq!(status["configured"], false);
        assert_eq!(status["objective_applied_actual"], false);
        assert_eq!(
            status["operation_receipt"],
            serde_json::to_value(&proof).unwrap()
        );
        assert_eq!(h.inbox.inspect(TARGET).await.unwrap().pending, 0);
    }
    let mut bounded = h.update("Remote B");
    if let LoopControlRequest::Update {
        max_iterations,
        max_total_rounds,
        ..
    } = &mut bounded
    {
        *max_iterations = Some(3);
        *max_total_rounds = Some(12);
    }
    h.send(&bounded).await.unwrap();
    h.drain(2).await.unwrap();
    assert!(consumption(&h.durable().await, &bounded).configured);
    let state = h.state();
    assert_eq!((state.max_iterations, state.max_total_rounds), (3, 12));
    assert_eq!(state.rounds_started, original.rounds_started);
    assert_eq!(state.iterations_started, original.iterations_started);
    assert_eq!(state.objective, "Wider local A");
    assert_eq!(
        state
            .control
            .as_ref()
            .unwrap()
            .pending_objective
            .as_ref()
            .unwrap()
            .objective,
        "Remote B"
    );
    assert_eq!(state.control.as_ref().unwrap().control_revision, 2);
    h.close().await;
}

// Only the claim return is parked. All actual queue and checkpoint operations
// delegate to the real persistence already attached to the live-owner Fixture.
struct PauseScopedClaimAfterSuccess {
    inner: Arc<dyn bamboo_domain::RuntimeSessionPersistence>,
    entered: Arc<tokio::sync::Notify>,
    release: Arc<tokio::sync::Notify>,
    claims_observed: Arc<AtomicUsize>,
}

#[async_trait]
impl bamboo_domain::RuntimeSessionPersistence for PauseScopedClaimAfterSuccess {
    async fn save_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
        self.inner.save_runtime_session(session).await
    }

    async fn checkpoint_runtime_session(&self, session: &mut Session) -> std::io::Result<()> {
        self.inner.checkpoint_runtime_session(session).await
    }

    async fn claim_scoped_loop_controls(
        &self,
        session: &Session,
        inbox: Arc<dyn SessionInboxPort>,
        active_run_id: &str,
        limit: usize,
    ) -> std::io::Result<Vec<bamboo_domain::ScopedLoopControlClaim>> {
        let claims = self
            .inner
            .claim_scoped_loop_controls(session, inbox, active_run_id, limit)
            .await?;
        if !claims.is_empty() {
            self.claims_observed
                .fetch_add(claims.len(), Ordering::SeqCst);
            self.entered.notify_one();
            self.release.notified().await;
        }
        Ok(claims)
    }

    async fn checkpoint_scoped_loop_control(
        &self,
        session: &mut Session,
        bindings: &[ScopedLoopControlBinding],
        activation: Arc<dyn SessionActivationPort>,
        input: Option<(
            Arc<dyn SessionInboxPort>,
            bamboo_domain::ScopedLoopControlClaim,
        )>,
    ) -> std::io::Result<()> {
        self.inner
            .checkpoint_scoped_loop_control(session, bindings, activation, input)
            .await
    }

    async fn load_loop_control_checkpoint(
        &self,
        session_id: &str,
    ) -> std::io::Result<Option<Session>> {
        self.inner.load_loop_control_checkpoint(session_id).await
    }
}

#[tokio::test]
async fn scoped_host_stop_during_successful_claim_leaves_update_unconsumed_and_stops_normally() {
    let mut h = Fixture::new(true).await;
    let start = h.start_and_admit().await;
    let before = h.state();
    let before_messages = serde_json::to_value(&h.session.messages).unwrap();
    let update = h.update("Must not apply after host stop");
    let queued = h.send(&update).await.unwrap();
    assert_eq!(queued["admitted"], true);
    assert_eq!(queued["configured"], false);
    let update_id =
        bamboo_domain::SessionMessageId::parse(queued["receipt_id"].as_str().unwrap()).unwrap();
    let update_operation = operation_id(&update).unwrap().to_owned();
    let start_consumption = consumption(&h.durable().await, &start);
    let entered = Arc::new(tokio::sync::Notify::new());
    let release = Arc::new(tokio::sync::Notify::new());
    let claims_observed = Arc::new(AtomicUsize::new(0));
    h.config.persistence = Some(Arc::new(PauseScopedClaimAfterSuccess {
        inner: h.config.persistence.take().unwrap(),
        entered: entered.clone(),
        release: release.clone(),
        claims_observed: claims_observed.clone(),
    }));
    let policy = h.policy().clone();
    let stop_after_claim = async move {
        entered.notified().await;
        policy.stop();
        release.notify_one();
    };
    let (drained, ()) = tokio::time::timeout(std::time::Duration::from_secs(10), async {
        tokio::join!(h.drain(1), stop_after_claim)
    })
    .await
    .expect("real control claim did not reach its deterministic stop gate");
    assert_eq!(claims_observed.load(Ordering::SeqCst), 1);
    assert!(
        drained.is_ok(),
        "host stop after a successful claim must not become an authority failure: {drained:?}"
    );
    assert!(!h.admit().await);
    let durable = h.durable().await;
    let stopped = counted_loop::read_loop_state(&durable).unwrap().unwrap();
    assert_eq!(stopped.status, LoopStatus::Stopped);
    assert_eq!(stopped.objective, before.objective);
    assert_eq!(
        (
            stopped.iterations_started,
            stopped.iterations_completed,
            stopped.rounds_started,
        ),
        (
            before.iterations_started,
            before.iterations_completed,
            before.rounds_started,
        )
    );
    assert!(stopped
        .control
        .as_ref()
        .unwrap()
        .pending_objective
        .is_none());
    assert!(!scoped_loop_consumptions(&durable)
        .unwrap()
        .iter()
        .any(|record| record.operation_id == update_operation));
    assert!(!h.inbox.was_admitted(TARGET, &update_id).await.unwrap());
    assert_eq!(consumption(&durable, &start), start_consumption);
    assert_eq!(
        serde_json::to_value(&durable.messages).unwrap(),
        before_messages
    );
    assert!(
        !h.cancel.is_cancelled(),
        "the real host stop is independent from user cancellation"
    );
    h.close().await;
}

mod stop_backlog_tests;

mod stop_backlog_authority_tests;

mod remote_objective_contract_tests;