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
pub mod decision;
pub mod handoff;
pub mod multi_round;
pub mod passthrough;
pub mod proposal;
pub mod quorum;
pub mod task;
pub mod util;
use macp_core::error::MacpError;
use macp_core::session::Session;
use macp_pb::pb::{Envelope, ModeDescriptor};
use std::collections::HashMap;
/// The canonical standards-track modes implemented by this runtime.
pub const STANDARD_MODE_NAMES: &[&str] = &[
"macp.mode.decision.v1",
"macp.mode.proposal.v1",
"macp.mode.task.v1",
"macp.mode.handoff.v1",
"macp.mode.quorum.v1",
];
/// Built-in extension modes shipped with this runtime but not yet standards-track.
pub const EXTENSION_MODE_NAMES: &[&str] = &["ext.multi_round.v1"];
// `ModeResponse` (data) lives in `macp-core` so `Session::apply_mode_response`
// can consume it without a core->modes cycle. The `Mode` trait (behavior) stays
// here. Re-exported so `crate::mode::ModeResponse` keeps resolving.
pub use macp_core::mode::{MessageContext, ModeResponse};
/// Trait that coordination modes implement.
/// Modes receive immutable session references and return a ModeResponse.
/// The runtime kernel is responsible for applying the response.
pub trait Mode: Send + Sync {
fn on_session_start(
&self,
session: &Session,
env: &Envelope,
) -> Result<ModeResponse, MacpError>;
fn on_message(&self, session: &Session, env: &Envelope) -> Result<ModeResponse, MacpError>;
/// Kernel entry point: `on_message` plus the runtime's
/// [`macp_core::mode::MessageContext`] (acceptance clock). Defaulted to plain
/// `on_message` so most modes ignore it; modes that need a trustworthy
/// time source (Handoff) override this instead of reading the forgeable
/// `Envelope.timestamp_unix_ms`. The runtime and replay always call this,
/// with the same clock value that the log entry records.
fn on_message_at(
&self,
session: &Session,
env: &Envelope,
ctx: &macp_core::mode::MessageContext,
) -> Result<ModeResponse, MacpError> {
let _ = ctx;
self.on_message(session, env)
}
/// The client boundary: validate an envelope that a *client* submitted on
/// the live path, before it is dispatched.
///
/// Called on live client-submitted envelopes **only** — never on replay,
/// and never on a runtime-synthesized envelope. Library kernels MUST call
/// it on inbound traffic. Default is `Ok(())`, so a mode with no
/// client-boundary rules needs no override.
///
/// # Why this is a hook and not a check inside `on_message`
///
/// Some envelope shapes are legitimate *as recorded history* but illegal
/// *as client submissions*. The motivating case is the handoff mode's
/// runtime-synthesized implicit `HandoffAccept` (RFC-MACP-0010 §5.1(3),
/// whose prohibition is scoped to submission "via `Send`"): once such an
/// entry is in the append-only log, replay must dispatch it through the
/// ordinary mode path, so the mode cannot refuse the shape outright. Only
/// the live boundary can tell the two apart, because only the live
/// boundary knows the envelope came from a client. Keeping the rejection
/// here — rather than marking the log entry with a discriminator — is what
/// makes the recorded payload itself a trustworthy provenance signal, and
/// it keeps a *stale reader* loud: an old binary replaying a newer log
/// rejects the entry in its own mode and fails replay visibly, instead of
/// silently skipping an entry kind it does not recognise.
///
/// # Hazard: this hook is fail-open by construction
///
/// Nothing forces a caller to invoke it — a kernel that drives the phases
/// by hand and never calls it simply has no client boundary, and still
/// compiles. This runtime is the worked example of why that matters:
/// `crate::step::validate_message` does call the hook, but the runtime
/// does **not** go through `step::validate_message` — `process_message`
/// calls [`Mode::authorize_sender`] and [`Mode::on_message_at`] directly so
/// it can interpose its durable append between validation and commit. So
/// wiring the hook into `step` alone would have left the runtime
/// unprotected; the runtime calls it explicitly at its own two live entry
/// points (`process_message` and `process_session_start`), which together
/// cover every client envelope (`Send` and `StreamSession` both funnel
/// into `Runtime::process`), while replay and crash recovery only re-read
/// entries that already passed the hook when they were first accepted.
/// There is no compile-time forcing function here — only this note.
fn validate_client_envelope(&self, session: &Session, env: &Envelope) -> Result<(), MacpError> {
let _ = (session, env);
Ok(())
}
/// The synthesis seam: given this session and this clock reading, the
/// envelope (if any) that MUST enter accepted history *before* the message
/// currently being processed.
///
/// Default `None` — nothing is ever due, which is the answer for every
/// mode but Handoff. The motivating case is RFC-MACP-0010 §5.1(2): once an
/// outstanding handoff offer's `implicit_accept_timeout_ms` has elapsed,
/// the runtime "MUST append a synthetic `HandoffAccept` envelope to the
/// session's accepted history — before evaluating any subsequent message
/// against the offer's acceptance state, and in particular before any
/// `Commitment` evaluation".
///
/// # The kernel contract
///
/// A kernel that calls this MUST, holding the session's lock and *before*
/// it validates or dispatches the triggering message:
///
/// 1. dispatch the returned envelope through [`Mode::on_message_at`] with
/// `accepted_at_ms` equal to the envelope's own `timestamp_unix_ms`,
/// 2. append it durably as an ordinary accepted (`Incoming`) history entry,
/// stamping `received_at_ms` with the envelope's own
/// `timestamp_unix_ms` — **not** wall-clock. Replay derives its dispatch
/// clock from `received_at_ms` (`src/replay.rs`), so stamping anything
/// else desynchronizes the live and replayed clocks for this entry and
/// breaks byte-identical rebuild of `mode_state`. Harmless for handoff
/// specifically, whose accept arm is time-blind, but the contract is
/// general and the next mode to use this hook may not be.
/// 3. commit the resulting session state and insert the envelope's
/// `message_id` into the dedup set,
/// 4. publish it to the session's subscribers,
///
/// and only then process the triggering message. Appending without
/// dispatching, or dispatching without appending, forks live state from
/// what replay will rebuild from the log.
///
/// # Never called on replay
///
/// The recorded entry *is* the product: replay dispatches it through the
/// ordinary message path like any other accepted entry, so the timer stays
/// outside the replay boundary while its recorded product is inside — the
/// same construction as the runtime-emitted lifecycle envelopes of
/// RFC-MACP-0001 §7.5. An implementation must therefore never read a clock
/// of its own: every field of the returned envelope, `timestamp_unix_ms`
/// included, has to be a pure function of the session state and `now_ms`,
/// because it is baked into permanent history and an observation-dependent
/// value could never be reproduced.
///
/// # Idempotence
///
/// Implementations MUST return `None` once the returned envelope has been
/// applied to the session: a second emission would append a duplicate
/// entry whose deterministic `message_id` already holds a dedup slot.
///
/// Like [`Mode::validate_client_envelope`], this hook is fail-open by
/// construction — a kernel that never calls it simply never synthesizes,
/// and still compiles. There is no compile-time forcing function, only
/// this note.
fn due_synthetic_envelope(&self, session: &Session, now_ms: i64) -> Option<Envelope> {
let _ = (session, now_ms);
None
}
/// Authorize the sender for this message. Modes can override to customize
/// authorization (e.g., allowing orchestrator bypass for Commitment messages).
fn authorize_sender(&self, session: &Session, env: &Envelope) -> Result<(), MacpError> {
if !session.participants.is_empty() && !session.participants.contains(&env.sender) {
return Err(MacpError::Forbidden);
}
Ok(())
}
}
pub fn standard_mode_names() -> &'static [&'static str] {
STANDARD_MODE_NAMES
}
pub fn extension_mode_names() -> &'static [&'static str] {
EXTENSION_MODE_NAMES
}
fn schema_map(path: &str) -> HashMap<String, String> {
HashMap::from([("protobuf".to_string(), path.to_string())])
}
pub fn standard_mode_descriptors() -> Vec<ModeDescriptor> {
vec![
ModeDescriptor {
mode: "macp.mode.decision.v1".into(),
mode_version: "1.0.0".into(),
title: "Decision Mode".into(),
description: "Structured decision making with proposals, evaluations, objections, votes, and a terminal Commitment.".into(),
determinism_class: "semantic-deterministic".into(),
participant_model: "declared".into(),
message_types: vec![
"SessionStart".into(),
"Proposal".into(),
"Evaluation".into(),
"Objection".into(),
"Vote".into(),
"Commitment".into(),
],
terminal_message_types: vec!["Commitment".into()],
schema_uris: schema_map("buf.build/multiagentcoordinationprotocol/macp"),
},
ModeDescriptor {
mode: "macp.mode.proposal.v1".into(),
mode_version: "1.0.0".into(),
title: "Proposal Mode".into(),
description: "Negotiation with proposals, counterproposals, accepts, rejects, withdrawals, and a terminal Commitment.".into(),
determinism_class: "semantic-deterministic".into(),
participant_model: "peer".into(),
message_types: vec![
"SessionStart".into(),
"Proposal".into(),
"CounterProposal".into(),
"Accept".into(),
"Reject".into(),
"Withdraw".into(),
"Commitment".into(),
],
terminal_message_types: vec!["Commitment".into()],
schema_uris: schema_map("buf.build/multiagentcoordinationprotocol/macp"),
},
ModeDescriptor {
mode: "macp.mode.task.v1".into(),
mode_version: "1.0.0".into(),
title: "Task Mode".into(),
description: "One bounded delegated task with assignee responses, progress, completion/failure reports, and a terminal Commitment.".into(),
determinism_class: "structural-only".into(),
participant_model: "orchestrated".into(),
message_types: vec![
"SessionStart".into(),
"TaskRequest".into(),
"TaskAccept".into(),
"TaskReject".into(),
"TaskUpdate".into(),
"TaskComplete".into(),
"TaskFail".into(),
"Commitment".into(),
],
terminal_message_types: vec!["Commitment".into()],
schema_uris: schema_map("buf.build/multiagentcoordinationprotocol/macp"),
},
ModeDescriptor {
mode: "macp.mode.handoff.v1".into(),
mode_version: "1.0.0".into(),
title: "Handoff Mode".into(),
description: "Scoped responsibility transfer with handoff offers, context, target responses, and a terminal Commitment.".into(),
determinism_class: "context-frozen".into(),
participant_model: "delegated".into(),
message_types: vec![
"SessionStart".into(),
"HandoffOffer".into(),
"HandoffContext".into(),
"HandoffAccept".into(),
"HandoffDecline".into(),
"Commitment".into(),
],
terminal_message_types: vec!["Commitment".into()],
schema_uris: schema_map("buf.build/multiagentcoordinationprotocol/macp"),
},
ModeDescriptor {
mode: "macp.mode.quorum.v1".into(),
mode_version: "1.0.0".into(),
title: "Quorum Mode".into(),
description: "Threshold approval with one approval request, participant ballots, and a terminal Commitment.".into(),
determinism_class: "semantic-deterministic".into(),
participant_model: "quorum".into(),
message_types: vec![
"SessionStart".into(),
"ApprovalRequest".into(),
"Approve".into(),
"Reject".into(),
"Abstain".into(),
"Commitment".into(),
],
terminal_message_types: vec!["Commitment".into()],
schema_uris: schema_map("buf.build/multiagentcoordinationprotocol/macp"),
},
]
}
pub fn extension_mode_descriptors() -> Vec<ModeDescriptor> {
vec![ModeDescriptor {
mode: "ext.multi_round.v1".into(),
mode_version: "1.0.0".into(),
title: "Multi-Round Mode".into(),
description: "Iterative convergence through multiple contribution rounds until all participants agree, with a terminal Commitment.".into(),
determinism_class: "semantic-deterministic".into(),
participant_model: "peer".into(),
message_types: vec![
"SessionStart".into(),
"Contribute".into(),
"Commitment".into(),
],
terminal_message_types: vec!["Commitment".into()],
schema_uris: schema_map("buf.build/multiagentcoordinationprotocol/macp"),
}]
}
pub fn all_mode_descriptors() -> Vec<ModeDescriptor> {
let mut all = standard_mode_descriptors();
all.extend(extension_mode_descriptors());
all
}