macp-modes 0.7.0

MACP coordination mode implementations (decision, proposal, task, handoff, quorum, multi_round) and the mode registry. Policy is injected via macp_core::PolicyEvaluator.
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
use macp_core::error::MacpError;
use macp_core::session::Session;
use macp_pb::pb::CommitmentPayload;
use prost::Message;

pub fn decode_commitment_payload(payload: &[u8]) -> Result<CommitmentPayload, MacpError> {
    CommitmentPayload::decode(payload).map_err(|_| MacpError::InvalidPayload)
}

pub fn validate_commitment_payload_for_session(
    session: &Session,
    payload: &[u8],
) -> Result<CommitmentPayload, MacpError> {
    let commitment = decode_commitment_payload(payload)?;

    if commitment.commitment_id.trim().is_empty()
        || commitment.action.trim().is_empty()
        || commitment.authority_scope.trim().is_empty()
        || commitment.reason.trim().is_empty()
    {
        return Err(MacpError::InvalidPayload);
    }

    if commitment.mode_version != session.mode_version
        || commitment.configuration_version != session.configuration_version
    {
        return Err(MacpError::InvalidPayload);
    }

    // RFC-MACP-0012 §6.1: an empty policy_version at SessionStart resolves to
    // "policy.default", and the runtime rewrites session.policy_version to the
    // resolved id. A client that started with "" must not be forced to echo a
    // value it never set, so an empty commitment.policy_version defers to the
    // session's bound policy. A non-empty value must match the binding exactly.
    // (The echo question is ambiguous upstream — filed as an RFC issue; empty-
    // matches is forward-compatible with either resolution.)
    if !commitment.policy_version.is_empty()
        && !session.policy_version.is_empty()
        && commitment.policy_version != session.policy_version
    {
        return Err(MacpError::InvalidPayload);
    }

    // RFC-MACP-0001 §7.3.1: if this commitment supersedes a prior one, the
    // reference must be structurally well-formed. Supersession is inherently
    // cross-session, so the kernel checks only well-formedness here (and
    // authority, separately) — it does NOT verify the referenced commitment
    // exists, was sealed, or is unforked. Those are consumer governance.
    // RFC-MACP-0013 §9 additionally tightens `commitment_hash` to the
    // canonical shape (`sha256:` + 64 lowercase hex chars) with an immediate
    // hard reject — no dual-read/transitional window is permitted.
    if let Some(ref sup) = commitment.supersedes {
        if sup.session_id.trim().is_empty() {
            tracing::warn!(
                session_id = %sup.session_id,
                "supersedes.session_id must be non-empty"
            );
            return Err(MacpError::InvalidPayload);
        }
        if !is_canonical_commitment_hash(&sup.commitment_hash) {
            tracing::warn!(
                commitment_hash = %sup.commitment_hash,
                "supersedes.commitment_hash must be a canonical RFC-MACP-0013 hash: \
                 'sha256:' followed by 64 lowercase hex characters"
            );
            return Err(MacpError::InvalidPayload);
        }
    }

    // Validate outcome_positive consistency with action (RFC-0001 §7.3)
    validate_outcome_positive(&commitment)?;

    Ok(commitment)
}

/// Check whether `s` is a canonical RFC-MACP-0013 commitment hash: the
/// literal prefix `sha256:` followed by exactly 64 lowercase hex characters.
/// No trimming is performed — leading/trailing whitespace is a rejection,
/// not something to be trimmed away before checking.
fn is_canonical_commitment_hash(s: &str) -> bool {
    match s.strip_prefix("sha256:") {
        Some(rest) => {
            rest.len() == 64
                && rest
                    .bytes()
                    .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
        }
        None => false,
    }
}

/// Validate that `outcome_positive` is consistent with the `action` field.
/// Actions ending in `rejected`, `failed`, or `declined` must have `outcome_positive = false`.
/// Actions ending in `selected`, `accepted`, `completed`, or `approved` must have `outcome_positive = true`.
fn validate_outcome_positive(commitment: &CommitmentPayload) -> Result<(), MacpError> {
    let action = commitment.action.as_str();
    let negative_actions = ["rejected", "failed", "declined"];
    let positive_actions = ["selected", "accepted", "completed", "approved"];

    let is_negative = negative_actions
        .iter()
        .any(|suffix| action.ends_with(suffix));
    let is_positive = positive_actions
        .iter()
        .any(|suffix| action.ends_with(suffix));

    if is_negative && commitment.outcome_positive {
        return Err(MacpError::InvalidPayload);
    }
    if is_positive && !commitment.outcome_positive {
        return Err(MacpError::InvalidPayload);
    }
    Ok(())
}

/// Shared commitment policy gate (extracted from five per-mode copies).
/// Fail closed: only an explicit `Allow` proceeds — `PolicyDecision` is
/// `#[non_exhaustive]`, and any unknown decision denies.
pub fn enforce_commitment_policy(
    session: &Session,
    mode: macp_core::policy::CommitmentMode<'_>,
    outcome_positive: bool,
    evaluator: &dyn macp_core::policy::PolicyEvaluator,
) -> Result<(), MacpError> {
    let Some(ref policy) = session.policy_definition else {
        return Ok(());
    };
    let decision = evaluator.evaluate_commitment(&macp_core::policy::CommitmentContext {
        policy,
        participants: &session.participants,
        outcome_positive,
        mode,
    });
    match decision {
        macp_core::policy::PolicyDecision::Allow { .. } => Ok(()),
        macp_core::policy::PolicyDecision::Deny { reasons } => {
            tracing::warn!(
                session_id = %session.session_id,
                policy_id = %policy.policy_id,
                reasons = ?reasons,
                "policy denied commitment"
            );
            Err(MacpError::PolicyDenied { reasons })
        }
        other => {
            tracing::warn!(
                session_id = %session.session_id,
                policy_id = %policy.policy_id,
                decision = ?other,
                "unrecognized policy decision treated as denial"
            );
            Err(MacpError::PolicyDenied {
                reasons: vec!["unrecognized policy decision".into()],
            })
        }
    }
}

/// Shared mode-state JSON codec (extracted from six per-mode copies).
/// Encoding a mode-state struct cannot fail; if it ever does, panic loudly
/// rather than silently persisting an empty state.
pub fn encode_mode_state<T: serde::Serialize>(state: &T) -> Vec<u8> {
    serde_json::to_vec(state).expect("mode state is always serializable")
}

pub fn decode_mode_state<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, MacpError> {
    serde_json::from_slice(bytes).map_err(|_| MacpError::InvalidModeState)
}

pub fn is_declared_participant(participants: &[String], sender: &str) -> bool {
    participants.iter().any(|participant| participant == sender)
}

/// Check whether the sender is authorized to commit per the policy's `commitment.authority` rule.
///
/// RFC-MACP-0012 §4: the `commitment` rule group controls who can emit a Commitment
/// envelope. If no policy is bound, defaults to initiator-only (RFC-MACP-0001 §7.3).
pub fn check_commitment_authority(session: &Session, sender: &str) -> Result<(), MacpError> {
    if let Some(ref policy) = session.policy_definition {
        let rules: macp_core::policy::rules::CommitmentRules =
            extract_commitment_rules(&policy.rules);
        match rules.authority.as_str() {
            "any_participant" => {
                if sender == session.initiator_sender
                    || is_declared_participant(&session.participants, sender)
                {
                    Ok(())
                } else {
                    Err(MacpError::Forbidden)
                }
            }
            "designated_role" => {
                if rules.designated_roles.iter().any(|r| r == sender) {
                    Ok(())
                } else {
                    Err(MacpError::Forbidden)
                }
            }
            _ => {
                // "initiator_only" (default)
                if sender == session.initiator_sender {
                    Ok(())
                } else {
                    Err(MacpError::Forbidden)
                }
            }
        }
    } else {
        // No policy bound — default to initiator-only
        if sender == session.initiator_sender {
            Ok(())
        } else {
            Err(MacpError::Forbidden)
        }
    }
}

fn extract_commitment_rules(
    rules: &serde_json::Value,
) -> macp_core::policy::rules::CommitmentRules {
    // Single implementation lives in macp-core (this was a byte-for-byte copy).
    macp_core::policy::extract_commitment_rules(rules)
}

pub fn participants_all_accept(
    participants: &[String],
    accepts: &std::collections::BTreeMap<String, String>,
    proposal_id: &str,
) -> bool {
    !participants.is_empty()
        && participants
            .iter()
            .all(|participant| accepts.get(participant).map(String::as_str) == Some(proposal_id))
}

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

    fn make_commitment(action: &str, outcome_positive: bool) -> CommitmentPayload {
        CommitmentPayload {
            commitment_id: "c1".into(),
            action: action.into(),
            authority_scope: "scope".into(),
            reason: "reason".into(),
            mode_version: "1.0.0".into(),
            policy_version: String::new(),
            configuration_version: "cfg-1".into(),
            outcome_positive,
            supersedes: None,
        }
    }

    // --- supersedes structural validation (RFC-MACP-0001 §7.3.1) ---

    fn session_for_commitment() -> Session {
        Session::builder("s1", "macp.mode.decision.v1", "agent://a")
            .ttl_ms(60_000)
            .mode_version("1.0.0")
            .configuration_version("cfg-1")
            .build()
    }

    // Pinned vector hash for `cmt_hash_001_minimal` from the RFC-MACP-0013
    // conformance vectors (see crates/macp-core/src/commitment_hash.rs's test
    // module) — a real canonical commitment hash, not an arbitrary literal.
    const VALID_COMMITMENT_HASH: &str =
        "sha256:9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d41";

    #[test]
    fn well_formed_supersedes_is_accepted() {
        let session = session_for_commitment();
        let mut c = make_commitment("decision.selected", true);
        c.supersedes = Some(macp_pb::pb::CommitmentRef {
            session_id: "prior-session".into(),
            commitment_hash: VALID_COMMITMENT_HASH.into(),
        });
        assert!(validate_commitment_payload_for_session(&session, &c.encode_to_vec()).is_ok());
    }

    #[test]
    fn malformed_supersedes_is_rejected() {
        let session = session_for_commitment();
        for bad in [
            ("", VALID_COMMITMENT_HASH),
            ("prior-session", ""),
            ("  ", VALID_COMMITMENT_HASH),
            // Non-empty but no `sha256:` prefix at all.
            ("prior-session", "not-a-hash"),
            // Correct length, but uppercase hex (RFC requires lowercase).
            (
                "prior-session",
                "sha256:9F58E9D114D11860D48AA2BCB8CDA458B9618B1CC8560595A802B68C4AF85D41",
            ),
            // Right prefix, one hex char short of 64.
            (
                "prior-session",
                "sha256:9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d4",
            ),
        ] {
            let mut c = make_commitment("decision.selected", true);
            c.supersedes = Some(macp_pb::pb::CommitmentRef {
                session_id: bad.0.into(),
                commitment_hash: bad.1.into(),
            });
            assert!(
                validate_commitment_payload_for_session(&session, &c.encode_to_vec()).is_err(),
                "expected rejection for supersedes {bad:?}"
            );
        }
    }

    // --- is_canonical_commitment_hash direct unit tests (RFC-MACP-0013 §9) ---

    #[test]
    fn canonical_hash_valid_is_accepted() {
        assert!(is_canonical_commitment_hash(VALID_COMMITMENT_HASH));
    }

    #[test]
    fn canonical_hash_rejects_uppercase() {
        assert!(!is_canonical_commitment_hash(
            "sha256:9F58E9D114D11860D48AA2BCB8CDA458B9618B1CC8560595A802B68C4AF85D41"
        ));
    }

    #[test]
    fn canonical_hash_rejects_uppercase_prefix() {
        // The "sha256:" prefix itself must be lowercase — case-insensitive
        // prefix matching would silently loosen this guard.
        assert!(!is_canonical_commitment_hash(&format!(
            "SHA256:{}",
            VALID_COMMITMENT_HASH.strip_prefix("sha256:").unwrap()
        )));
    }

    #[test]
    fn canonical_hash_rejects_63_chars() {
        assert!(!is_canonical_commitment_hash(
            "sha256:9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d4"
        ));
    }

    #[test]
    fn canonical_hash_rejects_65_chars() {
        assert!(!is_canonical_commitment_hash(
            "sha256:9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d411"
        ));
    }

    #[test]
    fn canonical_hash_rejects_missing_prefix() {
        assert!(!is_canonical_commitment_hash(
            "9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d41"
        ));
    }

    #[test]
    fn canonical_hash_rejects_wrong_prefix() {
        assert!(!is_canonical_commitment_hash(
            "sha512:9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d41"
        ));
    }

    #[test]
    fn canonical_hash_rejects_empty_string() {
        assert!(!is_canonical_commitment_hash(""));
    }

    #[test]
    fn canonical_hash_rejects_leading_whitespace() {
        assert!(!is_canonical_commitment_hash(&format!(
            " {VALID_COMMITMENT_HASH}"
        )));
    }

    #[test]
    fn canonical_hash_rejects_trailing_whitespace() {
        assert!(!is_canonical_commitment_hash(&format!(
            "{VALID_COMMITMENT_HASH} "
        )));
    }

    #[test]
    fn canonical_hash_rejects_non_hex_characters() {
        // 'g' is not a valid hex digit.
        assert!(!is_canonical_commitment_hash(
            "sha256:gf58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d41"
        ));
        // '!' is not a valid hex digit either.
        assert!(!is_canonical_commitment_hash(
            "sha256:9f58e9d114d11860d48aa2bcb8cda458b9618b1cc8560595a802b68c4af85d4!"
        ));
    }

    // --- policy_version echo (master plan §2.3) ---

    /// A session that started with empty policy_version is rewritten to
    /// "policy.default" by the runtime; the client must not be required to echo
    /// a value it never sent.
    #[test]
    fn empty_commitment_policy_version_matches_bound_policy() {
        let mut session = session_for_commitment();
        session.policy_version = "policy.default".into();
        let c = make_commitment("decision.selected", true); // policy_version: ""
        assert!(validate_commitment_payload_for_session(&session, &c.encode_to_vec()).is_ok());
    }

    #[test]
    fn wrong_commitment_policy_version_rejected() {
        let mut session = session_for_commitment();
        session.policy_version = "policy.default".into();
        let mut c = make_commitment("decision.selected", true);
        c.policy_version = "policy.other.v1".into();
        assert!(validate_commitment_payload_for_session(&session, &c.encode_to_vec()).is_err());
    }

    #[test]
    fn exact_commitment_policy_version_accepted() {
        let mut session = session_for_commitment();
        session.policy_version = "policy.default".into();
        let mut c = make_commitment("decision.selected", true);
        c.policy_version = "policy.default".into();
        assert!(validate_commitment_payload_for_session(&session, &c.encode_to_vec()).is_ok());
    }

    // --- outcome_positive validation: RFC-defined positive actions ---

    #[test]
    fn decision_selected_positive_ok() {
        assert!(validate_outcome_positive(&make_commitment("decision.selected", true)).is_ok());
    }

    #[test]
    fn decision_selected_negative_rejected() {
        assert!(validate_outcome_positive(&make_commitment("decision.selected", false)).is_err());
    }

    #[test]
    fn decision_rejected_negative_ok() {
        assert!(validate_outcome_positive(&make_commitment("decision.rejected", false)).is_ok());
    }

    #[test]
    fn decision_rejected_positive_rejected() {
        assert!(validate_outcome_positive(&make_commitment("decision.rejected", true)).is_err());
    }

    #[test]
    fn proposal_accepted_positive_ok() {
        assert!(validate_outcome_positive(&make_commitment("proposal.accepted", true)).is_ok());
    }

    #[test]
    fn proposal_accepted_negative_rejected() {
        assert!(validate_outcome_positive(&make_commitment("proposal.accepted", false)).is_err());
    }

    #[test]
    fn proposal_rejected_negative_ok() {
        assert!(validate_outcome_positive(&make_commitment("proposal.rejected", false)).is_ok());
    }

    #[test]
    fn proposal_rejected_positive_rejected() {
        assert!(validate_outcome_positive(&make_commitment("proposal.rejected", true)).is_err());
    }

    #[test]
    fn task_completed_positive_ok() {
        assert!(validate_outcome_positive(&make_commitment("task.completed", true)).is_ok());
    }

    #[test]
    fn task_completed_negative_rejected() {
        assert!(validate_outcome_positive(&make_commitment("task.completed", false)).is_err());
    }

    #[test]
    fn task_failed_negative_ok() {
        assert!(validate_outcome_positive(&make_commitment("task.failed", false)).is_ok());
    }

    #[test]
    fn task_failed_positive_rejected() {
        assert!(validate_outcome_positive(&make_commitment("task.failed", true)).is_err());
    }

    #[test]
    fn handoff_accepted_positive_ok() {
        assert!(validate_outcome_positive(&make_commitment("handoff.accepted", true)).is_ok());
    }

    #[test]
    fn handoff_declined_negative_ok() {
        assert!(validate_outcome_positive(&make_commitment("handoff.declined", false)).is_ok());
    }

    #[test]
    fn handoff_declined_positive_rejected() {
        assert!(validate_outcome_positive(&make_commitment("handoff.declined", true)).is_err());
    }

    #[test]
    fn quorum_approved_positive_ok() {
        assert!(validate_outcome_positive(&make_commitment("quorum.approved", true)).is_ok());
    }

    #[test]
    fn quorum_rejected_negative_ok() {
        assert!(validate_outcome_positive(&make_commitment("quorum.rejected", false)).is_ok());
    }

    #[test]
    fn quorum_rejected_positive_rejected() {
        assert!(validate_outcome_positive(&make_commitment("quorum.rejected", true)).is_err());
    }

    #[test]
    fn custom_action_no_known_suffix_any_outcome_ok() {
        // Actions without recognized suffixes pass validation regardless of outcome_positive
        assert!(validate_outcome_positive(&make_commitment("custom.action", true)).is_ok());
        assert!(validate_outcome_positive(&make_commitment("custom.action", false)).is_ok());
    }
}