bcode_session 0.0.1-alpha.0

Session lifecycle and attachment management for bcode
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
//! Bounded canonical observations used to decide whether an invocation can be recovered.

use crate::{SessionError, SessionManager};
use bcode_session_models::{SessionEvent, SessionEventKind, SessionId};

/// Canonical authorization observation, not permission to execute or retry a tool.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InvocationRecoveryObservation {
    /// The complete observed interval ends with an unresolved permission request.
    WaitingForPermission { permission_id: String },
    /// A decision is recorded but no invocation lifecycle is observed. This alone does not
    /// prove absence of side effects and is not a dispatch permit.
    PermissionDecided {
        permission_id: String,
        approved: bool,
    },
    /// A canonical result already exists. Recovery must not invoke the tool again.
    Terminal,
    /// The bounded interval is incomplete, inconsistent, or cannot prove an authorization wait.
    Unverifiable,
}

/// Canonical records needed to reconstruct an authorization wait.
///
/// This is an observation at `generation`, not a dispatch permit. A caller must acquire
/// current execution ownership and revalidate generation, policy, and plugin preparation
/// before registering or resolving a recovered request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct InvocationRecoveryCheckpoint {
    generation: u64,
    turn: SessionEvent,
    request: SessionEvent,
    permission: SessionEvent,
    decision: Option<bool>,
}

impl InvocationRecoveryCheckpoint {
    /// Recorded decision; inspect without granting dispatch authority.
    #[must_use]
    pub const fn is_approved(&self) -> bool {
        matches!(self.decision, Some(true))
    }

    /// Canonical session that owns this checkpoint.
    #[must_use]
    pub const fn session_id(&self) -> SessionId {
        self.request.session_id
    }

    /// Canonical history generation observed during validation.
    #[must_use]
    pub const fn generation(&self) -> u64 {
        self.generation
    }

    /// Original admitted user turn.
    #[must_use]
    pub const fn turn(&self) -> &SessionEvent {
        &self.turn
    }

    /// Original positioned tool request.
    #[must_use]
    pub const fn request(&self) -> &SessionEvent {
        &self.request
    }

    /// Original unresolved permission request.
    #[must_use]
    pub const fn permission(&self) -> &SessionEvent {
        &self.permission
    }
}

impl SessionManager {
    /// Record a recovered permission decision only if canonical history is unchanged.
    ///
    /// The caller must hold current execution authority and authorize the decision. This
    /// method grants neither authority nor dispatch permission. Conflicts must be re-read;
    /// they must not be retried with a silently updated generation.
    ///
    /// # Errors
    /// Returns ownership/storage errors or [`SessionError::AppendGenerationChanged`].
    pub async fn append_recovered_permission_decision(
        &self,
        checkpoint: &InvocationRecoveryCheckpoint,
        approved: bool,
    ) -> Result<SessionEvent, SessionError> {
        let session_id = checkpoint.session_id();
        if checkpoint.decision.is_some() {
            return Err(SessionError::EventSerialization(
                "recovered permission already has a decision".into(),
            ));
        }
        let SessionEventKind::PermissionRequested { permission_id, .. } =
            &checkpoint.permission.kind
        else {
            unreachable!("checkpoints are constructed only from canonical permission requests");
        };
        let handle = self.session_handle(session_id).await?;
        let event = handle
            .append_event_at_generation(
                SessionEventKind::PermissionResolved {
                    permission_id: permission_id.clone(),
                    approved,
                },
                checkpoint.generation,
                self.next_activity_timestamp_ms(),
            )
            .await?;
        let summary = handle.summary().await?;
        self.release_persistent_idle_session_resources(session_id)
            .await;
        self.publish_committed_mutation(event.clone(), summary);
        Ok(event)
    }

    /// Persist a one-time dispatch marker for an approved recovered invocation.
    ///
    /// The caller must first verify current execution authority, plugin preparation, and
    /// applicable policy. This only consumes the checkpoint; it does not execute a tool.
    /// A crash after this marker is an ambiguous execution, never an automatic retry.
    ///
    /// # Errors
    /// Rejects unresolved/denied decisions, stale generations, and ownership/storage failures.
    pub async fn claim_recovered_invocation_dispatch(
        &self,
        checkpoint: &InvocationRecoveryCheckpoint,
    ) -> Result<SessionEvent, SessionError> {
        if checkpoint.decision != Some(true) {
            return Err(SessionError::EventSerialization(
                "recovered invocation is not approved".into(),
            ));
        }
        let SessionEventKind::PositionedToolCallRequested { tool_call_id, .. } =
            &checkpoint.request.kind
        else {
            unreachable!("checkpoints require positioned requests");
        };
        let session_id = checkpoint.session_id();
        let handle = self.session_handle(session_id).await?;
        let event = handle.append_event_at_generation(
            SessionEventKind::ToolInvocationLifecycle { event: bcode_session_models::ToolInvocationLifecycleEvent {
                invocation_id: tool_call_id.clone(), sequence: 0,
                stage: bcode_session_models::ToolInvocationLifecycleStage::Started,
                message: None,
                metadata: serde_json::json!({"dispatch_boundary_version":1,"recovered":true}),
            } },
            checkpoint.generation, self.next_activity_timestamp_ms(),
        ).await?;
        let summary = handle.summary().await?;
        self.release_persistent_idle_session_resources(session_id)
            .await;
        self.publish_committed_mutation(event.clone(), summary);
        Ok(event)
    }

    /// Read the canonical turn and invocation records for an authorization wait or decision.
    ///
    /// Only positioned requests with an exact canonical user-turn identity are accepted.
    /// Unpositioned requests, changed generations, incomplete reads, and request-only context
    /// cannot establish a recoverable continuation and return `None`.
    ///
    /// # Errors
    /// Returns session ownership, storage, and bounded history-read errors.
    pub async fn invocation_recovery_checkpoint(
        &self,
        session_id: SessionId,
        invocation_id: &str,
        request_sequence: u64,
        max_events: usize,
    ) -> Result<Option<InvocationRecoveryCheckpoint>, SessionError> {
        let generation = self.current_session_generation(session_id).await?;
        if max_events == 0 || request_sequence > generation {
            return Ok(None);
        }
        let events = self
            .session_events_range(
                session_id,
                request_sequence,
                generation,
                max_events.min(1024),
            )
            .await?;
        let (permission_id, decision) =
            match observe(&events, invocation_id, request_sequence, generation) {
                InvocationRecoveryObservation::WaitingForPermission { permission_id } => {
                    (permission_id, None)
                }
                InvocationRecoveryObservation::PermissionDecided {
                    permission_id,
                    approved,
                } => (permission_id, Some(approved)),
                _ => return Ok(None),
            };
        let Some(request) = events.first() else {
            return Ok(None);
        };
        let SessionEventKind::PositionedToolCallRequested {
            turn_id,
            producer_plugin_id: Some(producer),
            working_directory: Some(working_directory),
            ..
        } = &request.kind
        else {
            return Ok(None);
        };
        if producer.trim().is_empty()
            || !working_directory.is_absolute()
            || self.session_working_directory(session_id).await? != *working_directory
        {
            return Ok(None);
        }
        let Some(turn) = self
            .recovery_turn_event(session_id, turn_id, request_sequence)
            .await?
        else {
            return Ok(None);
        };
        let (SessionEventKind::UserMessage { admission, .. }
        | SessionEventKind::SubmissionActivated { admission, .. }) = &turn.kind
        else {
            return Ok(None);
        };
        if admission.validate().is_err() || admission.execution.request_context_id.is_some() {
            return Ok(None);
        }
        let permission = events.iter().find(|event| matches!(&event.kind,
            SessionEventKind::PermissionRequested { permission_id: id, .. } if id == &permission_id
        )).cloned();
        if events.iter().any(|event| {
            matches!(&event.kind,
                SessionEventKind::ModelTurnFinished { turn_id: finished, .. } if finished == turn_id
            )
        }) {
            return Ok(None);
        }
        if self.current_session_generation(session_id).await? != generation {
            return Ok(None);
        }
        Ok(permission.map(|permission| InvocationRecoveryCheckpoint {
            generation,
            turn,
            request: request.clone(),
            permission,
            decision,
        }))
    }

    /// Resolve a receipt-backed turn without treating acceptance as execution evidence.
    async fn recovery_turn_event(
        &self,
        session_id: SessionId,
        turn_id: &str,
        request_sequence: u64,
    ) -> Result<Option<SessionEvent>, SessionError> {
        let Some(sequence) = turn_id
            .strip_prefix(&format!("{session_id}-"))
            .and_then(|value| value.parse::<u64>().ok())
        else {
            return Ok(None);
        };
        if sequence >= request_sequence || turn_id != format!("{session_id}-{sequence}") {
            return Ok(None);
        }
        let Some(turn) = self
            .session_events_range(session_id, sequence, sequence, 1)
            .await?
            .pop()
        else {
            return Ok(None);
        };
        let SessionEventKind::SubmissionAccepted { submission } = &turn.kind else {
            return Ok(matches!(turn.kind, SessionEventKind::UserMessage { .. }).then_some(turn));
        };
        if submission.target.turn_id().0 != turn_id {
            return Ok(None);
        }
        let Some(record) = self.submission(session_id, submission.id.clone()).await? else {
            return Ok(None);
        };
        let bcode_session_models::SubmissionStatus::Activated {
            turn_id: bound,
            conversation_sequence,
        } = record.status
        else {
            return Ok(None);
        };
        if bound.0 != turn_id
            || record.receipt.accepted_event_sequence != sequence
            || record.submission != *submission
            || conversation_sequence <= sequence
            || conversation_sequence >= request_sequence
        {
            return Ok(None);
        }
        let activation = self
            .session_events_range(session_id, conversation_sequence, conversation_sequence, 1)
            .await?
            .pop();
        Ok(activation.filter(|event| matches!(&event.kind, SessionEventKind::SubmissionActivated { submission_id, turn_id: bound, client_id, text, admission } if *submission_id == submission.id && bound.0 == turn_id && *client_id == submission.client_id && *text == submission.text && *admission == submission.admission)))
    }

    /// Observe one invocation from its canonical request through a pinned session generation.
    ///
    /// Reads at most `max_events` events. Missing history, concurrent changes, and exhausted
    /// bounds produce `Unverifiable`, never an inferred permission or safe retry.
    ///
    /// # Errors
    /// Returns session ownership, storage, and bounded history-read errors.
    pub async fn invocation_recovery_observation(
        &self,
        session_id: SessionId,
        invocation_id: &str,
        request_sequence: u64,
        max_events: usize,
    ) -> Result<InvocationRecoveryObservation, SessionError> {
        let generation = self.current_session_generation(session_id).await?;
        if max_events == 0 || request_sequence > generation {
            return Ok(InvocationRecoveryObservation::Unverifiable);
        }
        let events = self
            .session_events_range(
                session_id,
                request_sequence,
                generation,
                max_events.min(1024),
            )
            .await?;
        if self.current_session_generation(session_id).await? != generation {
            return Ok(InvocationRecoveryObservation::Unverifiable);
        }
        Ok(observe(
            &events,
            invocation_id,
            request_sequence,
            generation,
        ))
    }
}

fn observe(
    events: &[SessionEvent],
    invocation: &str,
    first: u64,
    last: u64,
) -> InvocationRecoveryObservation {
    use InvocationRecoveryObservation::{Terminal, Unverifiable, WaitingForPermission};
    if events.first().is_none_or(|event| event.sequence != first)
        || events.last().is_none_or(|event| event.sequence != last)
        || events
            .windows(2)
            .any(|pair| pair[0].sequence.checked_add(1) != Some(pair[1].sequence))
    {
        return Unverifiable;
    }
    let request = match &events[0].kind {
        SessionEventKind::ToolCallRequested {
            tool_call_id,
            tool_name,
            arguments_json,
            producer_plugin_id,
            ..
        }
        | SessionEventKind::PositionedToolCallRequested {
            tool_call_id,
            tool_name,
            arguments_json,
            producer_plugin_id,
            ..
        } if tool_call_id == invocation => (tool_name, arguments_json, producer_plugin_id),
        _ => return Unverifiable,
    };
    let mut permission = None;
    let mut resolved = None;
    for event in &events[1..] {
        match &event.kind {
            SessionEventKind::PermissionRequested {
                tool_call_id,
                permission_id,
                tool_name,
                arguments_json,
                producer_plugin_id,
                ..
            } if tool_call_id == invocation => {
                if permission.is_some()
                    || (tool_name, arguments_json, producer_plugin_id) != request
                {
                    return Unverifiable;
                }
                permission = Some(permission_id.clone());
            }
            SessionEventKind::PermissionResolved {
                permission_id,
                approved,
            } if permission.as_ref() == Some(permission_id) => {
                if resolved.is_some_and(|previous| previous != *approved) {
                    return Unverifiable;
                }
                resolved = Some(*approved);
            }
            SessionEventKind::ToolInvocationResultRecorded { record }
                if record.invocation_id == invocation =>
            {
                return Terminal;
            }
            SessionEventKind::ToolInvocationLifecycle { event }
                if event.invocation_id == invocation =>
            {
                return Unverifiable;
            }
            _ => {}
        }
    }
    match (permission, resolved) {
        (Some(permission_id), None) => WaitingForPermission { permission_id },
        (Some(permission_id), Some(approved)) => InvocationRecoveryObservation::PermissionDecided {
            permission_id,
            approved,
        },
        _ => Unverifiable,
    }
}

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

    #[test]
    fn mismatched_permission_producer_is_not_recoverable() {
        let session_id = SessionId::new();
        let event = |sequence, kind| SessionEvent {
            schema_version: bcode_session_models::CURRENT_SESSION_EVENT_SCHEMA_VERSION,
            sequence,
            timestamp_ms: sequence,
            session_id,
            provenance: None,
            kind,
        };
        let events = vec![
            event(
                1,
                SessionEventKind::ToolCallRequested {
                    tool_call_id: "call".into(),
                    producer_plugin_id: Some("original".into()),
                    tool_name: "write".into(),
                    arguments_json: "{}".into(),
                    working_directory: None,
                },
            ),
            event(
                2,
                SessionEventKind::PermissionRequested {
                    permission_id: "permission".into(),
                    tool_call_id: "call".into(),
                    producer_plugin_id: Some("other".into()),
                    tool_name: "write".into(),
                    arguments_json: "{}".into(),
                    batch: None,
                    policy_source: None,
                    policy_reason: None,
                },
            ),
        ];
        assert_eq!(
            observe(&events, "call", 1, 2),
            InvocationRecoveryObservation::Unverifiable
        );
    }

    #[tokio::test]
    async fn positioned_checkpoint_reopens_exact_turn_request_and_permission() {
        verify_positioned_checkpoint(false, false).await;
    }

    #[tokio::test]
    async fn approved_checkpoint_dispatch_is_claimed_once_across_reopen() {
        verify_positioned_checkpoint(true, false).await;
    }

    #[tokio::test]
    async fn activated_checkpoint_preserves_acceptance_turn_id_across_reopen() {
        verify_positioned_checkpoint(true, true).await;
    }

    async fn checkpoint_turn(
        manager: &SessionManager,
        session_id: SessionId,
        queued: bool,
    ) -> (SessionEvent, String) {
        if queued {
            let (admission, _) = manager
                .admit_queued_turn_with_events(
                    session_id,
                    bcode_session_models::ClientId::new(),
                    "implement".into(),
                    bcode_session_models::TurnAdmissionMetadata::default(),
                )
                .await
                .unwrap();
            let bcode_session_models::TurnAdmission::Accepted(receipt) = admission else {
                panic!("receipt")
            };
            let id = receipt.turn_id.to_string();
            assert!(
                manager
                    .recovery_turn_event(session_id, &id, receipt.accepted_event_sequence + 10)
                    .await
                    .unwrap()
                    .is_none()
            );
            let record = manager
                .activate_submission(
                    session_id,
                    bcode_session_models::SubmissionId::for_queued_turn(&receipt.turn_id),
                )
                .await
                .unwrap();
            let bcode_session_models::SubmissionStatus::Activated {
                conversation_sequence,
                ..
            } = record.status
            else {
                panic!("activation")
            };
            assert_ne!(conversation_sequence, receipt.accepted_event_sequence);
            let event = manager
                .session_events_range(session_id, conversation_sequence, conversation_sequence, 1)
                .await
                .unwrap()
                .pop()
                .unwrap();
            assert!(
                manager
                    .recovery_turn_event(
                        session_id,
                        &format!("{session_id}-{conversation_sequence}"),
                        conversation_sequence + 10
                    )
                    .await
                    .unwrap()
                    .is_none()
            );
            return (event, id);
        }
        let turn = manager
            .append_event(
                session_id,
                SessionEventKind::UserMessage {
                    client_id: bcode_session_models::ClientId::new(),
                    text: "implement".into(),
                    admission: bcode_session_models::TurnAdmissionMetadata::default(),
                },
            )
            .await
            .unwrap();
        let id = format!("{session_id}-{}", turn.sequence);
        (turn, id)
    }

    async fn verify_positioned_checkpoint(approved: bool, queued: bool) {
        let root = tempfile::tempdir().unwrap();
        let manager = SessionManager::persistent(root.path()).unwrap();
        let session = manager
            .create_session(None, root.path().to_path_buf())
            .await
            .unwrap();
        let (turn, turn_id) = checkpoint_turn(&manager, session.id, queued).await;
        let request = manager
            .append_event(
                session.id,
                SessionEventKind::PositionedToolCallRequested {
                    turn_id,
                    output_position: bcode_session_models::TurnOutputPosition::new(0),
                    tool_call_id: "call".into(),
                    producer_plugin_id: Some("example.tool".into()),
                    tool_name: "example.write".into(),
                    arguments_json: "{}".into(),
                    working_directory: Some(session.working_directory.clone()),
                },
            )
            .await
            .unwrap();
        let permission = manager
            .append_permission_requested(
                session.id,
                SessionEventKind::PermissionRequested {
                    permission_id: "permission".into(),
                    tool_call_id: "call".into(),
                    producer_plugin_id: Some("example.tool".into()),
                    tool_name: "example.write".into(),
                    arguments_json: "{}".into(),
                    batch: None,
                    policy_source: None,
                    policy_reason: None,
                },
            )
            .await
            .unwrap();
        let checkpoint = manager
            .invocation_recovery_checkpoint(session.id, "call", request.sequence, 16)
            .await
            .unwrap()
            .unwrap();
        assert_eq!(checkpoint.turn, turn);
        assert_eq!(checkpoint.request, request);
        assert_eq!(checkpoint.permission, permission);
        manager.release_session_ownership(session.id).await.unwrap();
        drop(manager);
        let restored = SessionManager::persistent(root.path()).unwrap();
        assert_eq!(
            restored
                .invocation_recovery_checkpoint(session.id, "call", request.sequence, 16)
                .await
                .unwrap(),
            Some(checkpoint.clone())
        );
        restored
            .append_recovered_permission_decision(&checkpoint, approved)
            .await
            .unwrap();
        assert!(matches!(
            restored
                .append_recovered_permission_decision(&checkpoint, true)
                .await,
            Err(SessionError::AppendGenerationChanged { .. })
        ));
        assert_eq!(
            restored
                .current_session_generation(session.id)
                .await
                .unwrap(),
            checkpoint.generation() + 1
        );
        let decided = restored
            .invocation_recovery_checkpoint(session.id, "call", request.sequence, 16)
            .await
            .unwrap()
            .unwrap();
        if approved {
            assert_approved_checkpoint(restored, &decided, root.path()).await;
        } else {
            assert_denied_checkpoint(&restored, &decided).await;
        }
    }

    async fn assert_approved_checkpoint(
        restored: SessionManager,
        decided: &InvocationRecoveryCheckpoint,
        root: &std::path::Path,
    ) {
        assert!(decided.is_approved());
        let event = restored
            .claim_recovered_invocation_dispatch(decided)
            .await
            .unwrap();
        assert_eq!(event.sequence, decided.generation() + 1);
        assert!(matches!(
            restored.claim_recovered_invocation_dispatch(decided).await,
            Err(SessionError::AppendGenerationChanged { .. })
        ));
        let session_id = decided.session_id();
        let request_sequence = decided.request().sequence;
        restored
            .release_session_ownership(session_id)
            .await
            .unwrap();
        drop(restored);
        let reopened = SessionManager::persistent(root).unwrap();
        assert!(
            reopened
                .invocation_recovery_checkpoint(session_id, "call", request_sequence, 32)
                .await
                .unwrap()
                .is_none()
        );
        assert!(matches!(
            reopened.claim_recovered_invocation_dispatch(decided).await,
            Err(SessionError::AppendGenerationChanged { .. })
        ));
        assert_eq!(
            reopened
                .current_session_generation(session_id)
                .await
                .unwrap(),
            event.sequence
        );
    }

    async fn assert_denied_checkpoint(
        restored: &SessionManager,
        decided: &InvocationRecoveryCheckpoint,
    ) {
        assert!(!decided.is_approved());
        assert!(
            restored
                .claim_recovered_invocation_dispatch(decided)
                .await
                .is_err()
        );
        assert!(
            restored
                .append_recovered_permission_decision(decided, true)
                .await
                .is_err()
        );
    }

    #[tokio::test]
    async fn canonical_wait_observation_survives_reopen_and_rejects_incomplete_history() {
        let root = tempfile::tempdir().unwrap();
        let manager = SessionManager::persistent(root.path()).unwrap();
        let session = manager
            .create_session(None, root.path().to_path_buf())
            .await
            .unwrap();
        let request = manager
            .append_tool_call_requested(
                session.id,
                crate::AppendToolCallRequestedInput {
                    tool_call_id: "call".into(),
                    producer_plugin_id: Some("example.tool".into()),
                    tool_name: "example.write".into(),
                    arguments_json: "{}".into(),
                    working_directory: None,
                },
            )
            .await
            .unwrap();
        manager
            .append_permission_requested(
                session.id,
                SessionEventKind::PermissionRequested {
                    permission_id: "permission".into(),
                    tool_call_id: "call".into(),
                    producer_plugin_id: Some("example.tool".into()),
                    tool_name: "example.write".into(),
                    arguments_json: "{}".into(),
                    batch: None,
                    policy_source: None,
                    policy_reason: None,
                },
            )
            .await
            .unwrap();
        assert_eq!(
            manager
                .invocation_recovery_observation(session.id, "call", request.sequence, 1)
                .await
                .unwrap(),
            InvocationRecoveryObservation::Unverifiable
        );
        assert_eq!(
            manager
                .invocation_recovery_observation(session.id, "other", request.sequence, 16)
                .await
                .unwrap(),
            InvocationRecoveryObservation::Unverifiable
        );
        assert_eq!(
            manager
                .invocation_recovery_observation(session.id, "call", request.sequence, 16)
                .await
                .unwrap(),
            InvocationRecoveryObservation::WaitingForPermission {
                permission_id: "permission".into()
            }
        );
        manager.release_session_ownership(session.id).await.unwrap();
        drop(manager);
        let restored = SessionManager::persistent(root.path()).unwrap();
        assert_eq!(
            restored
                .invocation_recovery_observation(session.id, "call", request.sequence, 16)
                .await
                .unwrap(),
            InvocationRecoveryObservation::WaitingForPermission {
                permission_id: "permission".into()
            }
        );
        restored
            .append_permission_resolved(session.id, "permission".into(), true)
            .await
            .unwrap();
        assert_eq!(
            restored
                .invocation_recovery_observation(session.id, "call", request.sequence, 16)
                .await
                .unwrap(),
            InvocationRecoveryObservation::PermissionDecided {
                permission_id: "permission".into(),
                approved: true
            }
        );
        restored
            .release_session_ownership(session.id)
            .await
            .unwrap();
        drop(restored);
        let restored = SessionManager::persistent(root.path()).unwrap();
        assert_decided_and_conflicting_history(&restored, session.id, request.sequence).await;
    }

    async fn assert_decided_and_conflicting_history(
        restored: &SessionManager,
        session_id: SessionId,
        request_sequence: u64,
    ) {
        assert_eq!(
            restored
                .invocation_recovery_observation(session_id, "call", request_sequence, 16)
                .await
                .unwrap(),
            InvocationRecoveryObservation::PermissionDecided {
                permission_id: "permission".into(),
                approved: true
            }
        );
        restored
            .append_permission_resolved(session_id, "permission".into(), false)
            .await
            .unwrap();
        assert_eq!(
            restored
                .invocation_recovery_observation(session_id, "call", request_sequence, 16)
                .await
                .unwrap(),
            InvocationRecoveryObservation::Unverifiable
        );
    }
}