macp-core 0.7.5

MACP coordination vocabulary: error, session model, decision domain types, and the policy evaluation trait. Transport-free.
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
use crate::error::MacpError;
use crate::mode::ModeResponse;
use crate::policy::PolicyDefinition;
use macp_pb::pb::SessionStartPayload;
use prost::Message;
use std::collections::{HashMap, HashSet};

pub const MAX_TTL_MS: i64 = 24 * 60 * 60 * 1000;

/// Default cap on the cumulative time a session may spend `Suspended` before
/// it is force-expired (RFC-MACP-0001 §7.5). Bounds indefinite
/// human-in-the-loop holds. Sessions may bind their own cap via
/// `SessionStartPayload.max_suspend_ms` (0 selects this default); the
/// resolved cap is recorded at SessionStart and used by replay
/// (RFC-MACP-0003 §2) — see [`Session::effective_max_suspend_ms`].
pub const MAX_SUSPEND_MS: i64 = 7 * 24 * 60 * 60 * 1000;

/// Current session-semantics revision. Recorded at SessionStart (on the
/// session and its log entry) and consulted wherever acceptance-time behavior
/// changed across releases, so legacy histories replay under the semantics
/// they were accepted with (RFC-MACP-0003 §1).
///
/// Revisions:
/// - 0 — legacy: Handoff implicit-accept timed against the client-supplied
///   envelope timestamp.
/// - 1 — Handoff implicit-accept times against the runtime acceptance clock
///   (`MessageContext::accepted_at_ms`).
pub const CURRENT_SEMANTICS_REV: u32 = 1;

#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub enum SessionState {
    Open,
    /// Non-terminal pause of an `Open` session (RFC-MACP-0001 §7.5). TTL is
    /// banked while suspended; only `Open`<->`Suspended` and `Suspended`->
    /// `Expired`/`Cancelled` transitions are permitted.
    Suspended,
    Resolved,
    Expired,
    /// Terminal: ended by an accepted `CancelSession` (distinct from `Expired`).
    Cancelled,
}

impl SessionState {
    /// Terminal states accept no further transitions.
    pub fn is_terminal(&self) -> bool {
        matches!(
            self,
            SessionState::Resolved | SessionState::Expired | SessionState::Cancelled
        )
    }
}

/// Session model. Fields are public for reads, but the struct is
/// `#[non_exhaustive]`: construct via [`Session::builder`]. This lets the model
/// gain fields without breaking every constructor in downstream crates
/// (pre-1.0 freeze requirement).
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Session {
    pub session_id: String,
    pub state: SessionState,
    pub ttl_expiry: i64,
    pub ttl_ms: i64,
    pub started_at_unix_ms: i64,
    pub resolution: Option<Vec<u8>>,
    pub mode: String,
    pub mode_state: Vec<u8>,
    pub participants: Vec<String>,
    pub seen_message_ids: HashSet<String>,
    pub intent: String,
    pub mode_version: String,
    pub configuration_version: String,
    pub policy_version: String,
    pub context_id: String,
    pub extensions: HashMap<String, Vec<u8>>,
    pub roots: Vec<macp_pb::pb::Root>,
    pub initiator_sender: String,
    pub participant_message_counts: HashMap<String, u32>,
    pub participant_last_seen: HashMap<String, i64>,
    pub policy_definition: Option<PolicyDefinition>,
    /// Wall-clock (session-timeline) ms at which the session was suspended, or
    /// `None` when not suspended. Used to bank TTL across a suspension (§7.5).
    pub suspended_at_ms: Option<i64>,
    /// Cumulative ms the session has spent suspended across all suspend/resume
    /// cycles. Drives the `MAX_SUSPEND_MS` cap.
    pub accumulated_suspended_ms: i64,
    /// Session-semantics revision this session was accepted under. See
    /// [`CURRENT_SEMANTICS_REV`]. Legacy persisted sessions load as `0`.
    pub semantics_rev: u32,
    /// Maximum-suspension cap bound at SessionStart (RFC-MACP-0001 §7.5,
    /// RFC-MACP-0003 §2). `0` = unbound (legacy sessions and library
    /// defaults) — the [`MAX_SUSPEND_MS`] default applies; see
    /// [`Session::effective_max_suspend_ms`]. The kernel records the
    /// *resolved* value here for new sessions.
    pub max_suspend_ms: i64,
}

impl Session {
    /// Start building a `Session`. The three arguments are the fields with no
    /// meaningful default; everything else starts from documented defaults
    /// (see [`SessionBuilder`]) and is set with the builder's methods.
    pub fn builder(
        session_id: impl Into<String>,
        mode: impl Into<String>,
        initiator_sender: impl Into<String>,
    ) -> SessionBuilder {
        SessionBuilder {
            inner: Session {
                session_id: session_id.into(),
                state: SessionState::Open,
                // Never-expires by default: every kernel path overrides this
                // from the validated SessionStart payload; library/test
                // consumers get a session that behaves until told otherwise.
                ttl_expiry: i64::MAX,
                ttl_ms: 0,
                started_at_unix_ms: 0,
                resolution: None,
                mode: mode.into(),
                mode_state: vec![],
                participants: vec![],
                seen_message_ids: HashSet::new(),
                intent: String::new(),
                mode_version: String::new(),
                configuration_version: String::new(),
                policy_version: String::new(),
                context_id: String::new(),
                extensions: HashMap::new(),
                roots: vec![],
                initiator_sender: initiator_sender.into(),
                participant_message_counts: HashMap::new(),
                participant_last_seen: HashMap::new(),
                policy_definition: None,
                suspended_at_ms: None,
                accumulated_suspended_ms: 0,
                semantics_rev: CURRENT_SEMANTICS_REV,
                max_suspend_ms: 0,
            },
        }
    }

    pub fn record_participant_activity(&mut self, sender: &str, timestamp_ms: i64) {
        *self
            .participant_message_counts
            .entry(sender.to_string())
            .or_insert(0) += 1;
        self.participant_last_seen
            .insert(sender.to_string(), timestamp_ms);
    }

    /// Suspend an `Open` session (RFC-MACP-0001 §7.5). Records the suspend time
    /// so TTL can be banked on resume. Pure: no clock, no I/O — the caller
    /// injects `now_ms`.
    pub fn suspend(&mut self, now_ms: i64) -> Result<(), MacpError> {
        if self.state != SessionState::Open {
            return Err(MacpError::SessionNotOpen);
        }
        self.state = SessionState::Suspended;
        self.suspended_at_ms = Some(now_ms);
        Ok(())
    }

    /// Resume a `Suspended` session, banking the suspended duration into the
    /// TTL deadline (`ttl_expiry += now - suspended_at`). If the cumulative
    /// suspended time would exceed `MAX_SUSPEND_MS`, the session is force-expired
    /// instead and `MacpError::TtlExpired` is returned.
    /// The suspension cap governing this session: the value bound at
    /// SessionStart, or the [`MAX_SUSPEND_MS`] default when unbound (0).
    pub fn effective_max_suspend_ms(&self) -> i64 {
        if self.max_suspend_ms > 0 {
            self.max_suspend_ms
        } else {
            MAX_SUSPEND_MS
        }
    }

    pub fn resume(&mut self, now_ms: i64) -> Result<(), MacpError> {
        if self.state != SessionState::Suspended {
            return Err(MacpError::SessionNotOpen);
        }
        let suspended_at = self.suspended_at_ms.unwrap_or(now_ms);
        let banked = (now_ms - suspended_at).max(0);
        self.accumulated_suspended_ms = self.accumulated_suspended_ms.saturating_add(banked);
        self.suspended_at_ms = None;
        if self.accumulated_suspended_ms > self.effective_max_suspend_ms() {
            self.state = SessionState::Expired;
            return Err(MacpError::TtlExpired);
        }
        self.ttl_expiry = self.ttl_expiry.saturating_add(banked);
        self.state = SessionState::Open;
        Ok(())
    }

    /// Cancel an `Open` or `Suspended` session into the terminal `Cancelled`
    /// state (RFC-MACP-0001 §7.3). Returns an error if already terminal.
    pub fn cancel(&mut self) -> Result<(), MacpError> {
        if self.state.is_terminal() {
            return Err(MacpError::SessionNotOpen);
        }
        self.state = SessionState::Cancelled;
        self.suspended_at_ms = None;
        Ok(())
    }

    /// Whether a currently-`Suspended` session has exceeded `MAX_SUSPEND_MS` as
    /// of `now_ms` (cumulative banked plus the in-progress suspension).
    pub fn suspend_cap_exceeded(&self, now_ms: i64) -> bool {
        match self.suspended_at_ms {
            Some(at) => {
                self.accumulated_suspended_ms
                    .saturating_add((now_ms - at).max(0))
                    > self.effective_max_suspend_ms()
            }
            None => self.accumulated_suspended_ms > self.effective_max_suspend_ms(),
        }
    }

    pub fn apply_mode_response(&mut self, response: ModeResponse) {
        match response {
            ModeResponse::NoOp => {}
            ModeResponse::PersistState(state) => self.mode_state = state,
            ModeResponse::Resolve(resolution) => {
                self.state = SessionState::Resolved;
                self.resolution = Some(resolution);
            }
            ModeResponse::PersistAndResolve { state, resolution } => {
                self.mode_state = state;
                self.state = SessionState::Resolved;
                self.resolution = Some(resolution);
            }
        }
    }
}

/// Builder for [`Session`] — the only construction path outside `macp-core`
/// (the struct is `#[non_exhaustive]`).
///
/// Defaults: `state: Open`, `ttl_expiry: i64::MAX` (never expires until set),
/// numeric fields `0`, everything else empty/`None`.
#[derive(Clone, Debug)]
pub struct SessionBuilder {
    inner: Session,
}

macro_rules! builder_setters {
    ($($(#[$doc:meta])* $name:ident: $ty:ty),* $(,)?) => {
        $(
            $(#[$doc])*
            pub fn $name(mut self, value: $ty) -> Self {
                self.inner.$name = value;
                self
            }
        )*
    };
}

impl SessionBuilder {
    builder_setters! {
        state: SessionState,
        ttl_expiry: i64,
        ttl_ms: i64,
        started_at_unix_ms: i64,
        resolution: Option<Vec<u8>>,
        mode_state: Vec<u8>,
        participants: Vec<String>,
        seen_message_ids: HashSet<String>,
        extensions: HashMap<String, Vec<u8>>,
        roots: Vec<macp_pb::pb::Root>,
        participant_message_counts: HashMap<String, u32>,
        participant_last_seen: HashMap<String, i64>,
        policy_definition: Option<crate::policy::PolicyDefinition>,
        suspended_at_ms: Option<i64>,
        accumulated_suspended_ms: i64,
        semantics_rev: u32,
        /// Suspension cap bound at SessionStart; 0 = use the
        /// [`MAX_SUSPEND_MS`] default (legacy sessions, library consumers).
        max_suspend_ms: i64,
    }

    pub fn intent(mut self, value: impl Into<String>) -> Self {
        self.inner.intent = value.into();
        self
    }

    pub fn mode_version(mut self, value: impl Into<String>) -> Self {
        self.inner.mode_version = value.into();
        self
    }

    pub fn configuration_version(mut self, value: impl Into<String>) -> Self {
        self.inner.configuration_version = value.into();
        self
    }

    pub fn policy_version(mut self, value: impl Into<String>) -> Self {
        self.inner.policy_version = value.into();
        self
    }

    pub fn context_id(mut self, value: impl Into<String>) -> Self {
        self.inner.context_id = value.into();
        self
    }

    pub fn build(self) -> Session {
        self.inner
    }
}

pub fn requires_strict_session_start(mode: &str) -> bool {
    matches!(
        mode,
        "macp.mode.decision.v1"
            | "macp.mode.proposal.v1"
            | "macp.mode.task.v1"
            | "macp.mode.handoff.v1"
            | "macp.mode.quorum.v1"
            | "ext.multi_round.v1"
    )
}

/// Parse a protobuf-encoded SessionStartPayload from raw bytes.
pub fn parse_session_start_payload(payload: &[u8]) -> Result<SessionStartPayload, MacpError> {
    if payload.is_empty() {
        return Err(MacpError::InvalidPayload);
    }
    SessionStartPayload::decode(payload).map_err(|_| MacpError::InvalidPayload)
}

/// Extract and validate TTL from a parsed SessionStartPayload.
pub fn extract_ttl_ms(payload: &SessionStartPayload) -> Result<i64, MacpError> {
    if !(1..=MAX_TTL_MS).contains(&payload.ttl_ms) {
        return Err(MacpError::InvalidTtl);
    }
    Ok(payload.ttl_ms)
}

/// Validate the complete canonical SessionStart binding contract.
pub fn validate_canonical_session_start_payload(
    payload: &SessionStartPayload,
) -> Result<(), MacpError> {
    extract_ttl_ms(payload)?;

    if payload.mode_version.trim().is_empty() || payload.configuration_version.trim().is_empty() {
        return Err(MacpError::InvalidPayload);
    }

    if payload.participants.is_empty() {
        return Err(MacpError::InvalidPayload);
    }

    // Safety limit: prevent resource exhaustion from excessively large participant lists.
    const MAX_PARTICIPANTS: usize = 1000;
    if payload.participants.len() > MAX_PARTICIPANTS {
        return Err(MacpError::InvalidPayload);
    }

    let mut seen = HashSet::new();
    for participant in &payload.participants {
        let participant = participant.trim();
        if participant.is_empty() || !seen.insert(participant.to_string()) {
            return Err(MacpError::InvalidPayload);
        }
    }

    // max_suspend_ms: 0 selects the runtime default; a positive value binds a
    // session-specific cap (RFC-MACP-0001 §7.1). Negative is meaningless.
    if payload.max_suspend_ms < 0 {
        return Err(MacpError::InvalidPayload);
    }

    Ok(())
}

/// Enforce the strict SessionStart binding contract for standards-track and qualifying extension modes.
pub fn validate_strict_session_start_payload(
    mode: &str,
    payload: &SessionStartPayload,
) -> Result<(), MacpError> {
    if !requires_strict_session_start(mode) {
        return Ok(());
    }

    validate_canonical_session_start_payload(payload)
}

/// Validate that a session ID meets the acceptance policy.
///
/// Accepts:
/// - UUID v4/v7 in hyphenated lowercase canonical form (36 chars)
/// - base64url tokens of 22+ chars (`[A-Za-z0-9_-]`)
///
/// Rejects everything else (empty, short human-readable, uppercase UUID, etc.).
pub fn validate_session_id_for_acceptance(session_id: &str) -> Result<(), MacpError> {
    if session_id.is_empty() {
        return Err(MacpError::InvalidSessionId);
    }

    // UUID-shaped ids (36 chars, parseable) are held to strict UUID rules with no
    // fall-through: canonical lowercase hyphenated form, version v4 or v7. This
    // keeps non-canonical forms (e.g. uppercase) of the same UUID from being
    // admitted as distinct base64url tokens. Only strings that do not parse as a
    // UUID at all fall through to the base64url rule.
    if session_id.len() == 36 && session_id.contains('-') {
        if let Ok(parsed) = uuid::Uuid::parse_str(session_id) {
            if parsed.as_hyphenated().to_string() == session_id {
                match parsed.get_version() {
                    Some(uuid::Version::Random) | Some(uuid::Version::SortRand) => {
                        return Ok(());
                    }
                    _ => {}
                }
            }
            return Err(MacpError::InvalidSessionId);
        }
    }

    // Try base64url: at least 22 chars, only [A-Za-z0-9_-]
    if session_id.len() >= 22
        && session_id
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
    {
        return Ok(());
    }

    Err(MacpError::InvalidSessionId)
}

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

    fn encode_payload(ttl_ms: i64, participants: Vec<String>) -> Vec<u8> {
        let payload = SessionStartPayload {
            intent: String::new(),
            participants,
            mode_version: "1.0.0".into(),
            configuration_version: "cfg-1".into(),
            policy_version: String::new(),
            ttl_ms,
            context_id: String::new(),
            extensions: std::collections::HashMap::new(),
            roots: vec![],
            max_suspend_ms: 0,
        };
        payload.encode_to_vec()
    }

    #[test]
    fn parse_empty_payload_is_invalid() {
        let err = parse_session_start_payload(b"").unwrap_err();
        assert_eq!(err.to_string(), "InvalidPayload");
    }

    #[test]
    fn parse_valid_protobuf_payload() {
        let bytes = encode_payload(5000, vec!["alice".into(), "bob".into()]);
        let result = parse_session_start_payload(&bytes).unwrap();
        assert_eq!(result.ttl_ms, 5000);
        assert_eq!(result.participants, vec!["alice", "bob"]);
    }

    #[test]
    fn extract_ttl_requires_explicit_positive_value() {
        let payload = SessionStartPayload::default();
        assert_eq!(
            extract_ttl_ms(&payload).unwrap_err().to_string(),
            "InvalidTtl"
        );

        let payload = SessionStartPayload {
            ttl_ms: 5000,
            ..Default::default()
        };
        assert_eq!(extract_ttl_ms(&payload).unwrap(), 5000);
    }

    #[test]
    fn standard_mode_requires_explicit_versions_and_participants() {
        let payload = SessionStartPayload {
            participants: vec!["alice".into()],
            mode_version: String::new(),
            configuration_version: "cfg-1".into(),
            ttl_ms: 1000,
            ..Default::default()
        };
        assert_eq!(
            validate_strict_session_start_payload("macp.mode.decision.v1", &payload)
                .unwrap_err()
                .to_string(),
            "InvalidPayload"
        );

        let payload = SessionStartPayload {
            participants: vec![],
            mode_version: "1.0.0".into(),
            configuration_version: "cfg-1".into(),
            ttl_ms: 1000,
            ..Default::default()
        };
        assert_eq!(
            validate_strict_session_start_payload("macp.mode.decision.v1", &payload)
                .unwrap_err()
                .to_string(),
            "InvalidPayload"
        );
    }

    fn open_session(ttl_expiry: i64) -> Session {
        Session {
            session_id: "s1".into(),
            state: SessionState::Open,
            ttl_expiry,
            ttl_ms: 60_000,
            started_at_unix_ms: 0,
            resolution: None,
            mode: "macp.mode.decision.v1".into(),
            mode_state: vec![],
            participants: vec![],
            seen_message_ids: HashSet::new(),
            intent: String::new(),
            mode_version: "1.0.0".into(),
            configuration_version: "cfg-1".into(),
            policy_version: String::new(),
            context_id: String::new(),
            extensions: HashMap::new(),
            roots: vec![],
            initiator_sender: "agent://a".into(),
            participant_message_counts: HashMap::new(),
            participant_last_seen: HashMap::new(),
            policy_definition: None,
            suspended_at_ms: None,
            accumulated_suspended_ms: 0,
            semantics_rev: CURRENT_SEMANTICS_REV,
            max_suspend_ms: 0,
        }
    }

    #[test]
    fn suspend_then_resume_banks_ttl() {
        let mut s = open_session(10_000);
        s.suspend(2_000).unwrap();
        assert_eq!(s.state, SessionState::Suspended);
        assert_eq!(s.suspended_at_ms, Some(2_000));
        // Resume 3_000ms later: banked 3_000 is added to the deadline.
        s.resume(5_000).unwrap();
        assert_eq!(s.state, SessionState::Open);
        assert_eq!(s.ttl_expiry, 13_000);
        assert_eq!(s.accumulated_suspended_ms, 3_000);
        assert_eq!(s.suspended_at_ms, None);
    }

    #[test]
    fn suspend_requires_open_and_resume_requires_suspended() {
        let mut s = open_session(10_000);
        // resume on an Open session is rejected
        assert!(matches!(
            s.resume(1).unwrap_err(),
            MacpError::SessionNotOpen
        ));
        s.suspend(1).unwrap();
        // double-suspend rejected
        assert!(matches!(
            s.suspend(2).unwrap_err(),
            MacpError::SessionNotOpen
        ));
    }

    #[test]
    fn resume_exceeding_max_suspend_expires() {
        let mut s = open_session(10_000);
        s.suspend(0).unwrap();
        // Resume after more than MAX_SUSPEND_MS: force-expired.
        let err = s.resume(MAX_SUSPEND_MS + 1).unwrap_err();
        assert!(matches!(err, MacpError::TtlExpired));
        assert_eq!(s.state, SessionState::Expired);
    }

    /// A session-bound cap (SessionStartPayload.max_suspend_ms) overrides the
    /// default: resuming past the BOUND cap force-expires even though the
    /// default cap is nowhere near exceeded.
    #[test]
    fn bound_cap_overrides_default_on_resume() {
        let mut s = open_session(10_000);
        s.max_suspend_ms = 500;
        s.suspend(0).unwrap();
        let err = s.resume(501).unwrap_err();
        assert!(matches!(err, MacpError::TtlExpired));
        assert_eq!(s.state, SessionState::Expired);
    }

    #[test]
    fn bound_cap_within_limit_resumes_and_banks_ttl() {
        let mut s = open_session(10_000);
        s.max_suspend_ms = 500;
        s.suspend(0).unwrap();
        s.resume(400).unwrap();
        assert_eq!(s.state, SessionState::Open);
        assert_eq!(s.ttl_expiry, 10_400);
    }

    #[test]
    fn suspend_cap_exceeded_uses_bound_cap() {
        let mut s = open_session(10_000);
        s.max_suspend_ms = 500;
        s.suspend(0).unwrap();
        assert!(!s.suspend_cap_exceeded(400));
        assert!(s.suspend_cap_exceeded(501));
    }

    #[test]
    fn unbound_session_uses_default_cap() {
        let s = open_session(10_000);
        assert_eq!(s.max_suspend_ms, 0);
        assert_eq!(s.effective_max_suspend_ms(), MAX_SUSPEND_MS);
    }

    #[test]
    fn negative_max_suspend_ms_rejected_in_canonical_payload() {
        let payload = SessionStartPayload {
            participants: vec!["a".into()],
            mode_version: "1.0.0".into(),
            configuration_version: "cfg-1".into(),
            ttl_ms: 60_000,
            max_suspend_ms: -1,
            ..Default::default()
        };
        assert_eq!(
            validate_canonical_session_start_payload(&payload)
                .unwrap_err()
                .to_string(),
            "InvalidPayload"
        );
        // 0 (runtime default) and positive values are both valid.
        let ok0 = SessionStartPayload {
            max_suspend_ms: 0,
            ..payload.clone()
        };
        validate_canonical_session_start_payload(&ok0).unwrap();
        let ok_pos = SessionStartPayload {
            max_suspend_ms: 60_000,
            ..payload
        };
        validate_canonical_session_start_payload(&ok_pos).unwrap();
    }

    #[test]
    fn cancel_from_open_or_suspended_then_terminal_is_rejected() {
        let mut s = open_session(10_000);
        s.suspend(1).unwrap();
        s.cancel().unwrap();
        assert_eq!(s.state, SessionState::Cancelled);
        assert_eq!(s.suspended_at_ms, None);
        // Already terminal: further cancel is rejected.
        assert!(matches!(s.cancel().unwrap_err(), MacpError::SessionNotOpen));

        let mut open = open_session(10_000);
        open.cancel().unwrap();
        assert_eq!(open.state, SessionState::Cancelled);
    }

    #[test]
    fn standard_mode_rejects_duplicate_participants() {
        let payload = SessionStartPayload {
            participants: vec!["alice".into(), "alice".into()],
            mode_version: "1.0.0".into(),
            configuration_version: "cfg-1".into(),
            ttl_ms: 1000,
            ..Default::default()
        };
        assert_eq!(
            validate_strict_session_start_payload("macp.mode.proposal.v1", &payload)
                .unwrap_err()
                .to_string(),
            "InvalidPayload"
        );
    }

    #[test]
    fn multi_round_requires_strict_session_start() {
        let payload = SessionStartPayload::default();
        assert!(validate_strict_session_start_payload("ext.multi_round.v1", &payload).is_err());
    }

    #[test]
    fn valid_uuid_v4_accepted() {
        let id = uuid::Uuid::new_v4().as_hyphenated().to_string();
        validate_session_id_for_acceptance(&id).unwrap();
    }

    #[test]
    fn valid_base64url_accepted() {
        // 22-char base64url token
        validate_session_id_for_acceptance("abcdefghijklmnopqrstuv").unwrap();
        // longer base64url with underscore and hyphen
        validate_session_id_for_acceptance("abc-def_ghi-jkl_mno-pqr").unwrap();
    }

    #[test]
    fn empty_id_rejected() {
        assert_eq!(
            validate_session_id_for_acceptance("")
                .unwrap_err()
                .to_string(),
            "InvalidSessionId"
        );
    }

    #[test]
    fn short_weak_id_rejected() {
        assert_eq!(
            validate_session_id_for_acceptance("s1")
                .unwrap_err()
                .to_string(),
            "InvalidSessionId"
        );
        assert_eq!(
            validate_session_id_for_acceptance("decision-demo-1")
                .unwrap_err()
                .to_string(),
            "InvalidSessionId"
        );
    }

    #[test]
    fn uppercase_uuid_rejected() {
        let id = uuid::Uuid::new_v4()
            .as_hyphenated()
            .to_string()
            .to_uppercase();
        assert_eq!(
            validate_session_id_for_acceptance(&id)
                .unwrap_err()
                .to_string(),
            "InvalidSessionId"
        );
    }

    #[test]
    fn base64url_36_chars_with_hyphen_accepted() {
        // 36-char base64url token containing '-' that is NOT UUID-shaped: must be
        // accepted via the base64url rule, not rejected by the UUID branch.
        // (Regression test for the hard-routing bug: len==36 && contains('-')
        // previously returned Err without trying the base64url rule.)
        let id = "Zx-abcdefghijklmnopqrstuvwxyz_ABCDE-";
        assert_eq!(id.len(), 36);
        assert!(uuid::Uuid::parse_str(id).is_err());
        validate_session_id_for_acceptance(id).unwrap();
    }

    #[test]
    fn uuid_shaped_but_wrong_version_does_not_fall_through() {
        // A canonical v1 UUID is also 36 chars of valid base64url charset; it must
        // still be rejected (UUID rules apply, no fall-through to base64url).
        let v4 = uuid::Uuid::new_v4();
        let mut bytes = *v4.as_bytes();
        bytes[6] = (bytes[6] & 0x0F) | 0x10;
        bytes[8] = (bytes[8] & 0x3F) | 0x80;
        let v1_id = uuid::Uuid::from_bytes(bytes).as_hyphenated().to_string();
        assert!(validate_session_id_for_acceptance(&v1_id).is_err());
    }

    #[test]
    fn base64url_too_short_rejected() {
        assert_eq!(
            validate_session_id_for_acceptance("abcdefghij")
                .unwrap_err()
                .to_string(),
            "InvalidSessionId"
        );
    }

    #[test]
    fn valid_uuid_v7_accepted() {
        // Construct a v7 UUID by patching the version nibble of a v4 UUID
        let v4 = uuid::Uuid::new_v4();
        let mut bytes = *v4.as_bytes();
        // Set version nibble (bits 48-51) to 0b0111 (v7)
        bytes[6] = (bytes[6] & 0x0F) | 0x70;
        // Keep variant bits valid (RFC 4122: 0b10xx)
        bytes[8] = (bytes[8] & 0x3F) | 0x80;
        let v7_id = uuid::Uuid::from_bytes(bytes).as_hyphenated().to_string();
        assert!(validate_session_id_for_acceptance(&v7_id).is_ok());
    }

    #[test]
    fn uuid_v1_rejected() {
        // Construct a v1 UUID by patching the version nibble of a v4 UUID
        let v4 = uuid::Uuid::new_v4();
        let mut bytes = *v4.as_bytes();
        // Set version nibble (bits 48-51) to 0b0001 (v1)
        bytes[6] = (bytes[6] & 0x0F) | 0x10;
        // Keep variant bits valid (RFC 4122: 0b10xx)
        bytes[8] = (bytes[8] & 0x3F) | 0x80;
        let v1_id = uuid::Uuid::from_bytes(bytes).as_hyphenated().to_string();
        assert_eq!(
            validate_session_id_for_acceptance(&v1_id)
                .unwrap_err()
                .to_string(),
            "InvalidSessionId"
        );
    }

    #[test]
    fn too_many_participants_rejected() {
        let participants: Vec<String> = (0..1001).map(|i| format!("agent://p{i}")).collect();
        let bytes = encode_payload(5000, participants);
        let payload = parse_session_start_payload(&bytes).unwrap();
        assert_eq!(
            validate_canonical_session_start_payload(&payload)
                .unwrap_err()
                .to_string(),
            "InvalidPayload"
        );
    }

    #[test]
    fn max_participants_accepted() {
        let participants: Vec<String> = (0..1000).map(|i| format!("agent://p{i}")).collect();
        let bytes = encode_payload(5000, participants);
        let payload = parse_session_start_payload(&bytes).unwrap();
        validate_canonical_session_start_payload(&payload).unwrap();
    }
}