macp-runtime 0.8.5

MACP reference runtime: a coordination kernel and gRPC server enforcing session boundaries, message validation, append-only history, modes, and governance policy.
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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
use chrono::Utc;
use macp_runtime::log_store::LogStore;
use macp_runtime::pb::{CommitmentPayload, Envelope, SessionResumePayload, SessionStartPayload};
use macp_runtime::registry::SessionRegistry;
use macp_runtime::runtime::Runtime;
use macp_runtime::session::{Session, SessionState};
use macp_runtime::storage::MemoryBackend;
use prost::Message;
use std::sync::Arc;

fn new_sid() -> String {
    uuid::Uuid::new_v4().as_hyphenated().to_string()
}

fn make_runtime() -> Runtime {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    Runtime::new(storage, registry, log_store)
}

fn session_start(participants: Vec<String>) -> Vec<u8> {
    SessionStartPayload {
        intent: "integration-test".into(),
        participants,
        mode_version: "1.0.0".into(),
        configuration_version: "cfg-1".into(),
        policy_version: String::new(),
        ttl_ms: 60_000,
        context_id: String::new(),
        extensions: std::collections::HashMap::new(),
        roots: vec![],
        max_suspend_ms: 0,
    }
    .encode_to_vec()
}

fn envelope(
    mode: &str,
    message_type: &str,
    message_id: &str,
    session_id: &str,
    sender: &str,
    payload: Vec<u8>,
) -> Envelope {
    Envelope {
        macp_version: "1.0".into(),
        mode: mode.into(),
        message_type: message_type.into(),
        message_id: message_id.into(),
        session_id: session_id.into(),
        sender: sender.into(),
        timestamp_unix_ms: Utc::now().timestamp_millis(),
        payload,
    }
}

fn commitment(action: &str) -> Vec<u8> {
    CommitmentPayload {
        commitment_id: "c1".into(),
        action: action.into(),
        authority_scope: "test".into(),
        reason: "done".into(),
        mode_version: "1.0.0".into(),
        policy_version: "policy.default".into(),
        configuration_version: "cfg-1".into(),
        outcome_positive: true,
        supersedes: None,
    }
    .encode_to_vec()
}

#[tokio::test]
async fn decision_full_lifecycle_through_runtime() {
    use macp_runtime::decision_pb::{ProposalPayload, VotePayload};

    let rt = make_runtime();
    let sid = new_sid();
    let mode = "macp.mode.decision.v1";

    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://orchestrator",
            session_start(vec![
                "agent://orchestrator".into(),
                "agent://a".into(),
                "agent://b".into(),
            ]),
        ),
        None,
    )
    .await
    .unwrap();

    let proposal = ProposalPayload {
        proposal_id: "p1".into(),
        option: "deploy".into(),
        rationale: "ready".into(),
        supporting_data: vec![],
    }
    .encode_to_vec();
    rt.process(
        &envelope(
            mode,
            "Proposal",
            "m2",
            &sid,
            "agent://orchestrator",
            proposal,
        ),
        None,
    )
    .await
    .unwrap();

    let vote = VotePayload {
        proposal_id: "p1".into(),
        vote: "approve".into(),
        reason: "good".into(),
    }
    .encode_to_vec();
    rt.process(&envelope(mode, "Vote", "m3", &sid, "agent://a", vote), None)
        .await
        .unwrap();

    let result = rt
        .process(
            &envelope(
                mode,
                "Commitment",
                "m4",
                &sid,
                "agent://orchestrator",
                commitment("decision.selected"),
            ),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.session_state, SessionState::Resolved);
}

#[tokio::test]
async fn proposal_full_lifecycle_through_runtime() {
    use macp_runtime::proposal_pb::{AcceptPayload, ProposalPayload};

    let rt = make_runtime();
    let sid = new_sid();
    let mode = "macp.mode.proposal.v1";

    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://buyer",
            session_start(vec!["agent://buyer".into(), "agent://seller".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    let proposal = ProposalPayload {
        proposal_id: "p1".into(),
        title: "offer".into(),
        summary: "terms".into(),
        details: vec![],
        tags: vec![],
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "Proposal", "m2", &sid, "agent://seller", proposal),
        None,
    )
    .await
    .unwrap();

    let accept = AcceptPayload {
        proposal_id: "p1".into(),
        reason: String::new(),
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "Accept", "m3", &sid, "agent://buyer", accept.clone()),
        None,
    )
    .await
    .unwrap();
    rt.process(
        &envelope(mode, "Accept", "m4", &sid, "agent://seller", accept),
        None,
    )
    .await
    .unwrap();

    let result = rt
        .process(
            &envelope(
                mode,
                "Commitment",
                "m5",
                &sid,
                "agent://buyer",
                commitment("proposal.accepted"),
            ),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.session_state, SessionState::Resolved);
}

#[tokio::test]
async fn task_full_lifecycle_through_runtime() {
    use macp_runtime::task_pb::{TaskAcceptPayload, TaskCompletePayload, TaskRequestPayload};

    let rt = make_runtime();
    let sid = new_sid();
    let mode = "macp.mode.task.v1";

    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://planner",
            session_start(vec!["agent://planner".into(), "agent://worker".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    let request = TaskRequestPayload {
        task_id: "t1".into(),
        title: "Build widget".into(),
        instructions: "Do it".into(),
        requested_assignee: "agent://worker".into(),
        input: vec![],
        deadline_unix_ms: 0,
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "TaskRequest", "m2", &sid, "agent://planner", request),
        None,
    )
    .await
    .unwrap();

    let accept = TaskAcceptPayload {
        task_id: "t1".into(),
        assignee: "agent://worker".into(),
        reason: "ready".into(),
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "TaskAccept", "m3", &sid, "agent://worker", accept),
        None,
    )
    .await
    .unwrap();

    let complete = TaskCompletePayload {
        task_id: "t1".into(),
        assignee: "agent://worker".into(),
        output: b"result".to_vec(),
        summary: "done".into(),
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "TaskComplete", "m4", &sid, "agent://worker", complete),
        None,
    )
    .await
    .unwrap();

    let result = rt
        .process(
            &envelope(
                mode,
                "Commitment",
                "m5",
                &sid,
                "agent://planner",
                commitment("task.completed"),
            ),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.session_state, SessionState::Resolved);
}

#[tokio::test]
async fn handoff_full_lifecycle_through_runtime() {
    use macp_runtime::handoff_pb::{HandoffAcceptPayload, HandoffOfferPayload};

    let rt = make_runtime();
    let sid = new_sid();
    let mode = "macp.mode.handoff.v1";

    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://owner",
            session_start(vec!["agent://owner".into(), "agent://target".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    let offer = HandoffOfferPayload {
        handoff_id: "h1".into(),
        target_participant: "agent://target".into(),
        scope: "support".into(),
        reason: "escalate".into(),
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "HandoffOffer", "m2", &sid, "agent://owner", offer),
        None,
    )
    .await
    .unwrap();

    let accept = HandoffAcceptPayload {
        handoff_id: "h1".into(),
        accepted_by: "agent://target".into(),
        reason: "ready".into(),
        implicit: false,
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "HandoffAccept", "m3", &sid, "agent://target", accept),
        None,
    )
    .await
    .unwrap();

    let result = rt
        .process(
            &envelope(
                mode,
                "Commitment",
                "m4",
                &sid,
                "agent://owner",
                commitment("handoff.accepted"),
            ),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.session_state, SessionState::Resolved);
}

#[tokio::test]
async fn quorum_full_lifecycle_through_runtime() {
    use macp_runtime::quorum_pb::{ApprovalRequestPayload, ApprovePayload};

    let rt = make_runtime();
    let sid = new_sid();
    let mode = "macp.mode.quorum.v1";

    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec![
                "agent://alice".into(),
                "agent://bob".into(),
                "agent://carol".into(),
            ]),
        ),
        None,
    )
    .await
    .unwrap();

    let request = ApprovalRequestPayload {
        request_id: "r1".into(),
        action: "deploy.production".into(),
        summary: "Deploy v2".into(),
        details: vec![],
        required_approvals: 2,
    }
    .encode_to_vec();
    rt.process(
        &envelope(
            mode,
            "ApprovalRequest",
            "m2",
            &sid,
            "agent://coordinator",
            request,
        ),
        None,
    )
    .await
    .unwrap();

    let approve1 = ApprovePayload {
        request_id: "r1".into(),
        reason: "lgtm".into(),
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "Approve", "m3", &sid, "agent://alice", approve1),
        None,
    )
    .await
    .unwrap();

    let approve2 = ApprovePayload {
        request_id: "r1".into(),
        reason: "ship it".into(),
    }
    .encode_to_vec();
    rt.process(
        &envelope(mode, "Approve", "m4", &sid, "agent://bob", approve2),
        None,
    )
    .await
    .unwrap();

    let result = rt
        .process(
            &envelope(
                mode,
                "Commitment",
                "m5",
                &sid,
                "agent://coordinator",
                commitment("quorum.approved"),
            ),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.session_state, SessionState::Resolved);
}

#[tokio::test]
async fn multi_round_full_lifecycle_through_runtime() {
    let rt = make_runtime();
    let sid = new_sid();
    let mode = "ext.multi_round.v1";

    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec!["agent://alice".into(), "agent://bob".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    rt.process(
        &envelope(
            mode,
            "Contribute",
            "m2",
            &sid,
            "agent://alice",
            br#"{"value":"option_a"}"#.to_vec(),
        ),
        None,
    )
    .await
    .unwrap();

    rt.process(
        &envelope(
            mode,
            "Contribute",
            "m3",
            &sid,
            "agent://bob",
            br#"{"value":"option_b"}"#.to_vec(),
        ),
        None,
    )
    .await
    .unwrap();

    rt.process(
        &envelope(
            mode,
            "Contribute",
            "m4",
            &sid,
            "agent://bob",
            br#"{"value":"option_a"}"#.to_vec(),
        ),
        None,
    )
    .await
    .unwrap();

    // Session still Open — convergence tracked, requires Commitment
    let session = rt.get_session_checked(&sid).await.unwrap();
    assert_eq!(session.state, SessionState::Open);

    let result = rt
        .process(
            &envelope(
                mode,
                "Commitment",
                "m5",
                &sid,
                "agent://coordinator",
                commitment("multi_round.converged"),
            ),
            None,
        )
        .await
        .unwrap();
    assert_eq!(result.session_state, SessionState::Resolved);
}

/// One clock per internal log entry (Phase 11a / follow-on 10).
///
/// `suspend_session` and `resume_session` each read the wall clock exactly
/// once and hand that same instant to both the `Session` mutation and
/// `make_internal_entry`. That makes the live `accumulated_suspended_ms` and
/// the value replay re-derives from the two entry timestamps identical *by
/// construction* — which matters because since Phase 10 that value gates an
/// accept/reject decision, so a sub-millisecond divergence could make a
/// live-`Resolved` session fail replay outright.
///
/// Honest note on what this test can and cannot do: with the clock injected
/// the equality holds deterministically, and before the fix it would only have
/// broken when a millisecond tick happened to land between the two `Utc::now()`
/// reads. So this pins the invariant rather than differentially proving the old
/// bug; the injected-clock signature is the real guarantee.
#[tokio::test]
async fn suspend_resume_entries_share_the_session_mutation_clock() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let rt = Runtime::new(storage, registry, Arc::clone(&log_store));

    let mode = "macp.mode.decision.v1";
    let sid = new_sid();
    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec!["agent://coordinator".into(), "agent://alice".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    rt.suspend_session(&sid, "pause", "agent://coordinator")
        .await
        .unwrap();
    // Let a millisecond boundary pass so the banked duration is non-trivial;
    // the assertion below is an exact equality either way.
    tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    rt.resume_session(&sid, "carry on", "agent://coordinator")
        .await
        .unwrap();

    let entries = log_store.get_log(&sid).await.unwrap();
    let stamp_of = |message_type: &str| -> i64 {
        let matching: Vec<&macp_runtime::log_store::LogEntry> = entries
            .iter()
            .filter(|e| e.message_type == message_type)
            .collect();
        assert_eq!(
            matching.len(),
            1,
            "expected exactly one {message_type} entry, got {}",
            matching.len()
        );
        matching[0].received_at_ms
    };
    let suspended_at = stamp_of("SessionSuspend");
    let resumed_at = stamp_of("SessionResume");

    let session = rt.get_session_checked(&sid).await.unwrap();
    assert_eq!(session.state, SessionState::Open);
    assert_eq!(
        session.accumulated_suspended_ms,
        resumed_at - suspended_at,
        "live accumulated_suspended_ms must equal the span between the two \
         internal log entries, or replay reconstructs a different value"
    );
    assert!(
        session.accumulated_suspended_ms > 0,
        "the suspension must have measured something, else the equality is vacuous"
    );

    // Phase 11b acceptance criterion 4 — live/replay agreement on the new
    // `suspension_intervals` vec. The live session records the pair in
    // `Session::resume`; replay reconstructs it by driving the same method
    // from the two internal entries' recorded timestamps, so the two must be
    // identical, not merely consistent.
    assert_eq!(
        session.suspension_intervals,
        vec![(suspended_at, resumed_at)],
        "the live session's completed-pause record must match the internal \
         log entries it was derived from"
    );
    let replay_registry = macp_runtime::mode_registry::ModeRegistry::build_default(Arc::new(
        macp_runtime::policy::DefaultPolicyEvaluator,
    ));
    let replayed = macp_runtime::replay::replay_session(&sid, &entries, &replay_registry, None)
        .expect("replay must succeed");
    assert_eq!(
        replayed.suspension_intervals, session.suspension_intervals,
        "replay must reconstruct the identical suspension intervals"
    );
    assert_eq!(
        replayed.accumulated_suspended_ms,
        session.accumulated_suspended_ms
    );
}

/// RFC-MACP-0006 §3.2:117 — `SessionSuspend`/`SessionResume` internal entries
/// MUST NOT consume accepted ordinals. Client-visible ordinals stay
/// contiguous across a suspend/resume cycle, and stay stable across a
/// simulated runtime restart too (§3.2:123 — "An ordinal MUST be stable for
/// the life of the session — across runtime restarts").
///
/// Every negative assertion here (the suspend/resume pair inserts no gap) is
/// paired with a positive one (the exact expected ids and ordinals), so the
/// test cannot pass by the feature having disappeared rather than by the
/// invariant holding — see Phase 1 criterion 6 for the mutation proof that
/// this test actually reds if `make_internal_entry` is changed to
/// `EntryKind::Incoming`.
#[tokio::test]
async fn suspend_resume_does_not_consume_accepted_ordinals() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let rt = Runtime::new(storage, registry, Arc::clone(&log_store));

    let mode = "macp.mode.decision.v1";
    let sid = new_sid();
    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec!["agent://coordinator".into(), "agent://alice".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    let proposal_before = macp_runtime::decision_pb::ProposalPayload {
        proposal_id: "p1".into(),
        option: "deploy".into(),
        rationale: "before suspend".into(),
        supporting_data: vec![],
    }
    .encode_to_vec();
    rt.process(
        &envelope(
            mode,
            "Proposal",
            "m2",
            &sid,
            "agent://coordinator",
            proposal_before,
        ),
        None,
    )
    .await
    .unwrap();

    rt.suspend_session(&sid, "pause", "agent://coordinator")
        .await
        .unwrap();
    rt.resume_session(&sid, "carry on", "agent://coordinator")
        .await
        .unwrap();

    let proposal_after = macp_runtime::decision_pb::ProposalPayload {
        proposal_id: "p2".into(),
        option: "hold".into(),
        rationale: "after resume".into(),
        supporting_data: vec![],
    }
    .encode_to_vec();
    rt.process(
        &envelope(
            mode,
            "Proposal",
            "m3",
            &sid,
            "agent://coordinator",
            proposal_after,
        ),
        None,
    )
    .await
    .unwrap();

    let ordinals = rt.log_store.get_incoming_after(&sid, 0).await.unwrap();
    // Projected to (ordinal, message_id): `LogEntry` has no `PartialEq`
    // (only `EntryKind` does), so a direct `assert_eq!` on the returned
    // `Vec<(u64, LogEntry)>` does not compile.
    let projection: Vec<(u64, String)> = ordinals
        .iter()
        .map(|(ordinal, entry)| (*ordinal, entry.message_id.clone()))
        .collect();
    assert_eq!(
        projection,
        vec![
            (1, "m1".to_string()),
            (2, "m2".to_string()),
            (3, "m3".to_string())
        ],
        "SessionSuspend/SessionResume must not consume an accepted ordinal or \
         appear in the ordinal-consuming sequence (RFC-MACP-0006 §3.2:117)"
    );

    let raw_log = log_store.get_log(&sid).await.unwrap();
    assert_eq!(
        raw_log.len(),
        5,
        "the durable log holds the 3 client envelopes plus the SessionSuspend \
         and SessionResume internal annotations — proving the entries were \
         written and excluded, not merely absent"
    );

    // Criterion 2a: the same projection survives a simulated restart.
    // Deliberately NOT checked via `replay_session` on this same `LogStore` —
    // `replay_session` rebuilds a `Session` and never touches the log, so
    // that comparison would be vacuous. Build a fresh store and replay the
    // collected entries into it the way startup does
    // (`create_session_log` then `append` per entry, `src/main.rs:371-374`).
    let restarted_store = LogStore::new();
    restarted_store.create_session_log(&sid).await;
    for entry in &raw_log {
        restarted_store.append(&sid, entry.clone()).await;
    }
    let restarted_ordinals = restarted_store.get_incoming_after(&sid, 0).await.unwrap();
    let restarted_projection: Vec<(u64, String)> = restarted_ordinals
        .iter()
        .map(|(ordinal, entry)| (*ordinal, entry.message_id.clone()))
        .collect();
    assert_eq!(
        restarted_projection, projection,
        "an ordinal must be stable across a runtime restart (RFC-MACP-0006 §3.2:123)"
    );
}

/// RFC-MACP-0006 §3.2:117 — `SessionCancel` MUST NOT consume an accepted
/// ordinal either. Runs on its own session, separately from the
/// suspend/resume test above, because `cancel_session` is terminal and
/// triggers `maybe_compact_log`, whose behavior forks on the storage backend:
///
/// - On `MemoryBackend` (used here), `replace_log` resolves to the trait's
///   default impl, which returns `Err(Unsupported)`, so compaction fails and
///   `force_insert_checkpoint` appends a `Checkpoint` entry with
///   `compacted_incoming_ordinals: 0` instead — the log grows by **two**
///   non-ordinal-consuming entries (`SessionCancel` + `Checkpoint`), and the
///   before/after ordinal projection is unaffected.
/// - On `FileBackend`, compaction succeeds and collapses the log to a single
///   checkpoint with a nonzero `compacted_incoming_ordinals` base, so
///   `get_incoming_after(&sid, 0)` would instead return `Err(base)` — a
///   different, also-correct shape this test does not exercise (see
///   `tests/handoff_implicit_accept_live.rs`'s two harnesses for that case).
///
/// Comparing before against after is stronger than an absolute count here,
/// and is immune to the force-inserted checkpoint (its
/// `compacted_incoming_ordinals: 0` cannot reset a base set by an earlier
/// real compaction — there is none in this test — because the base is a
/// `.max()` over checkpoints).
#[tokio::test]
async fn cancel_session_does_not_consume_accepted_ordinals() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let rt = Runtime::new(storage, registry, Arc::clone(&log_store));

    let mode = "macp.mode.decision.v1";
    let sid = new_sid();
    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec!["agent://coordinator".into(), "agent://alice".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    let before = rt.log_store.get_incoming_after(&sid, 0).await.unwrap();
    let before_projection: Vec<(u64, String)> = before
        .iter()
        .map(|(ordinal, entry)| (*ordinal, entry.message_id.clone()))
        .collect();
    let raw_len_before = log_store.get_log(&sid).await.unwrap().len();

    rt.cancel_session(&sid, "done", "agent://coordinator")
        .await
        .unwrap();

    let after = rt.log_store.get_incoming_after(&sid, 0).await.unwrap();
    let after_projection: Vec<(u64, String)> = after
        .iter()
        .map(|(ordinal, entry)| (*ordinal, entry.message_id.clone()))
        .collect();
    assert_eq!(
        after_projection, before_projection,
        "SessionCancel must not consume an accepted ordinal (RFC-MACP-0006 §3.2:117)"
    );
    assert!(
        !before_projection.is_empty(),
        "the projection must contain the SessionStart entry, else the equality above is vacuous"
    );

    let raw_len_after = log_store.get_log(&sid).await.unwrap().len();
    assert_eq!(
        raw_len_after,
        raw_len_before + 2,
        "on MemoryBackend, cancel appends SessionCancel plus a force-inserted \
         Checkpoint (compaction has no replace_log override on this backend) \
         — both non-ordinal-consuming, proving the entries were written and \
         excluded rather than never written"
    );
}

/// RFC-MACP-0001 §7.5 / RFC-MACP-0003 §2: `SessionResumePayload.banked_ms`
/// records the remaining TTL banked at suspend (`deadline − t_s`), not the
/// pause's duration (`t_r − t_s`). The fixture's suspension is short (tens of
/// ms) against a 60s TTL suspended almost immediately after start, so the two
/// quantities differ by more than an order of magnitude — a `banked_ms` that
/// still recorded the old (wrong) quantity could not pass the exact-equality
/// assertion below by coincidence.
#[tokio::test]
async fn resume_banks_the_remaining_ttl_at_suspend_not_the_pause_duration() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let rt = Runtime::new(storage, registry, Arc::clone(&log_store));

    let mode = "macp.mode.decision.v1";
    let sid = new_sid();
    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec!["agent://coordinator".into(), "agent://alice".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    // `Session::suspend` never touches `ttl_expiry`, so this pre-suspend
    // snapshot is exactly the spec's `deadline` — the value the formula banks
    // from.
    let ttl_expiry_before = rt.get_session_checked(&sid).await.unwrap().ttl_expiry;

    rt.suspend_session(&sid, "pause", "agent://coordinator")
        .await
        .unwrap();
    let suspended_at = log_store
        .get_log(&sid)
        .await
        .unwrap()
        .last()
        .unwrap()
        .received_at_ms;

    tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    rt.resume_session(&sid, "carry on", "agent://coordinator")
        .await
        .unwrap();

    let resume_entry = log_store
        .get_log(&sid)
        .await
        .unwrap()
        .last()
        .unwrap()
        .clone();
    let resumed_at = resume_entry.received_at_ms;
    let payload = SessionResumePayload::decode(&*resume_entry.raw_payload).unwrap();

    let expected_banked_ms = ttl_expiry_before.saturating_sub(suspended_at).max(0);
    assert_eq!(
        payload.banked_ms, expected_banked_ms,
        "banked_ms must be the remaining TTL at suspend (RFC-MACP-0001 §7.5, \
         RFC-MACP-0003 §2), not the pause's duration"
    );

    let pause_duration = resumed_at - suspended_at;
    assert!(
        payload.banked_ms > pause_duration * 10,
        "fixture must distinguish the two quantities by more than an order of \
         magnitude: banked_ms={}, pause_duration={}",
        payload.banked_ms,
        pause_duration
    );

    // Criterion 4: the deadline arithmetic itself is untouched by this phase
    // — only the recorded field's quantity changed, not what the session's
    // actual TTL banks.
    let session_after = rt.get_session_checked(&sid).await.unwrap();
    assert_eq!(
        session_after.ttl_expiry,
        ttl_expiry_before + (resumed_at - suspended_at),
        "the TTL deadline must still bank exactly the pause's duration, \
         unaffected by the banked_ms field's corrected quantity"
    );
}

/// RFC-MACP-0003 §2's per-event formula makes `banked_ms` non-monotonic
/// across suspend/resume cycles by design: each cycle's value is the
/// remaining TTL as of *that* cycle's own suspend, which shrinks as the
/// session ages. A later reader must not "fix" this into a monotonic
/// quantity.
///
/// The clock advance between the first resume and the second suspend is
/// load-bearing, not cosmetic: since a second suspend cannot precede the
/// first resume, banked_2 <= banked_1 always, but the inequality is strict
/// only when the second suspend happens strictly after the first resume.
/// Without this sleep, a fast run could tie the two events at the same
/// millisecond and a strict `<` assertion would flake.
#[tokio::test]
async fn banked_ms_shrinks_across_two_suspend_resume_cycles() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let rt = Runtime::new(storage, registry, Arc::clone(&log_store));

    let mode = "macp.mode.decision.v1";
    let sid = new_sid();
    rt.process(
        &envelope(
            mode,
            "SessionStart",
            "m1",
            &sid,
            "agent://coordinator",
            session_start(vec!["agent://coordinator".into(), "agent://alice".into()]),
        ),
        None,
    )
    .await
    .unwrap();

    rt.suspend_session(&sid, "pause 1", "agent://coordinator")
        .await
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    rt.resume_session(&sid, "carry on 1", "agent://coordinator")
        .await
        .unwrap();
    let banked_ms_1 = SessionResumePayload::decode(
        &*log_store
            .get_log(&sid)
            .await
            .unwrap()
            .last()
            .unwrap()
            .raw_payload,
    )
    .unwrap()
    .banked_ms;

    tokio::time::sleep(std::time::Duration::from_millis(5)).await;

    rt.suspend_session(&sid, "pause 2", "agent://coordinator")
        .await
        .unwrap();
    tokio::time::sleep(std::time::Duration::from_millis(5)).await;
    rt.resume_session(&sid, "carry on 2", "agent://coordinator")
        .await
        .unwrap();
    let banked_ms_2 = SessionResumePayload::decode(
        &*log_store
            .get_log(&sid)
            .await
            .unwrap()
            .last()
            .unwrap()
            .raw_payload,
    )
    .unwrap()
    .banked_ms;

    assert!(
        banked_ms_2 < banked_ms_1,
        "banked_ms must strictly shrink across cycles once the clock has \
         genuinely advanced between them: banked_ms_1={banked_ms_1}, \
         banked_ms_2={banked_ms_2}"
    );
}

/// Edge case: a session suspended exactly at its deadline banks zero
/// remaining TTL — legal, and distinguishable from "field absent" only by
/// context.
#[tokio::test]
async fn banked_ms_is_zero_when_suspended_exactly_at_the_deadline() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let sid = new_sid();
    let mode = "macp.mode.decision.v1";

    let deadline = 1_700_000_060_000;
    let mut session = Session::builder(sid.clone(), mode, "agent://coordinator").build();
    session.state = SessionState::Suspended;
    session.ttl_expiry = deadline;
    session.suspended_at_ms = Some(deadline);
    registry
        .insert_recovered_session(sid.clone(), session)
        .await;

    let rt = Runtime::new(storage, Arc::clone(&registry), Arc::clone(&log_store));
    let _ = rt
        .resume_session(&sid, "edge case", "agent://coordinator")
        .await;

    let entries = log_store.get_log(&sid).await.unwrap();
    let resume_entry = entries
        .iter()
        .find(|e| e.message_type == "SessionResume")
        .expect("SessionResume entry recorded even if resume itself later force-expires");
    let payload = SessionResumePayload::decode(&*resume_entry.raw_payload).unwrap();
    assert_eq!(
        payload.banked_ms, 0,
        "deadline - suspend_time == 0 when suspended exactly at the deadline"
    );
}

/// Edge case: a builder-constructed session with `suspended_at_ms` set past
/// `ttl_expiry` — unreachable through the ordinary suspend path, since
/// `suspend_session` runs `maybe_expire_session` first, but constructible by
/// a library consumer via `Session::builder` — must clamp `banked_ms` to
/// zero rather than go negative or panic.
#[tokio::test]
async fn banked_ms_clamps_to_zero_when_suspended_at_is_past_the_deadline() {
    let storage: Arc<dyn macp_runtime::storage::StorageBackend> = Arc::new(MemoryBackend);
    let registry = Arc::new(SessionRegistry::new());
    let log_store = Arc::new(LogStore::new());
    let sid = new_sid();
    let mode = "macp.mode.decision.v1";

    let deadline = 1_700_000_000_000;
    let mut session = Session::builder(sid.clone(), mode, "agent://coordinator").build();
    session.state = SessionState::Suspended;
    session.ttl_expiry = deadline;
    session.suspended_at_ms = Some(deadline + 5_000); // inconsistent: past the deadline
    registry
        .insert_recovered_session(sid.clone(), session)
        .await;

    let rt = Runtime::new(storage, Arc::clone(&registry), Arc::clone(&log_store));
    // Deliberately ignore the Result: `suspended_at_ms` here (a fixed point
    // in 2023) is far in the past relative to the real wall clock
    // `resume_session` reads for the *unrelated* MAX_SUSPEND_MS cap check
    // inside `Session::resume`, which will force-expire this session —
    // exactly the "still records banked_ms" case documented on
    // `resume_session`. The value under test is the appended entry's
    // payload, not this call's Result.
    let _ = rt
        .resume_session(&sid, "edge case", "agent://coordinator")
        .await;

    let entries = log_store.get_log(&sid).await.unwrap();
    let resume_entry = entries
        .iter()
        .find(|e| e.message_type == "SessionResume")
        .expect("SessionResume entry recorded even though resume force-expires");
    let payload = SessionResumePayload::decode(&*resume_entry.raw_payload).unwrap();
    assert_eq!(
        payload.banked_ms, 0,
        "ttl_expiry.saturating_sub(suspended_at) must clamp to 0, not go \
         negative or panic, when suspended_at_ms is past ttl_expiry"
    );
}