mcpmesh_local_api/protocol.rs
1//! mcpmesh-local/1 protocol types. Shared vocabulary between the daemon
2//! and its clients (porcelain, connect proxy, later the host shell). Wire framing
3//! is the family NDJSON codec — carried by the caller, not defined here.
4//!
5//! Request/response asymmetry: requests are one typed, closed enum (`Request`);
6//! responses are per-method typed structs deserialized from the JSON-RPC `result`
7//! Value — `Status` → [`StatusResult`], `RegisterService` → an ack, `OpenSession` →
8//! no JSON-RPC result at all: the socket STOPS being JSON-RPC and becomes a raw
9//! byte pipe.
10//!
11//! Additive-only: new fields (capabilities on `Hello`, groups/user_id on
12//! `PeerInfo`, device on `OpenSession`) MUST land as
13//! `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
14use std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18/// The first exchange on any `*-local/N` socket (the family's hello convention).
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Hello {
21 pub api: String, // "mcpmesh-local/1"
22 pub api_version: String, // "MAJOR.MINOR" of the protocol surface (see API_MINOR)
23 /// The protocol-compatibility MINOR as an integer, for a trivial machine comparison
24 /// (`api_minor >= N`) without string parsing. Distinct from `stack_version` (the crate
25 /// release train). Additive: an older daemon omits it and it defaults to 0.
26 #[serde(default)]
27 pub api_minor: u32,
28 pub stack_version: String,
29}
30
31/// The kind of backend answering a service — the two valid values, enforced at the
32/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
33/// kind only, never the command/path (no transport vocabulary).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum BackendKind {
37 Run,
38 Socket,
39}
40
41/// A registered service as reported by `status` (no transport vocabulary).
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct ServiceInfo {
44 pub name: String,
45 pub allow: Vec<String>, // STABLE principals (b64u:/eid:) or roster names (#38) — never nicknames
46 /// The HUMAN rendering of `allow`, index-aligned: each principal resolved to its peer's
47 /// display nickname by the daemon (which owns the store); an unresolvable stable
48 /// principal renders as a neutral placeholder — porcelain must show THESE, never raw
49 /// ids (surface discipline). Additive: default + skip-if-empty.
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
51 pub allow_display: Vec<String>,
52 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
53 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
54 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
55 /// daemon omits it and it reads as `false` (the persistent default).
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57 pub ephemeral: bool,
58}
59
60/// A known peer as reported by `status` (nickname only — never the EndpointId).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct PeerInfo {
63 pub name: String,
64 pub services: Vec<String>,
65 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
66 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
67 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
68 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub user_id: Option<String>,
71 /// The peer's stable DEVICE principal `eid:<hex>` (#41) — the SAME rendering the socket
72 /// backend injects into `_meta["mcpmesh/peer"]` and that appears in `[services.*].allow`.
73 /// Always present for a real peer (`Option` only for additive round-trip). Distinct from
74 /// `user_id` (the person-level `b64u:`, present only when the peer proved a binding): a
75 /// nickname is not unique, so an embedder keys caller-scoped decisions (dial the caller
76 /// back, "the requester's own data") on THIS, the authenticated endpoint. Machine-surface
77 /// authz vocabulary (like the allow lists) — human porcelain still shows the nickname.
78 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub principal: Option<String>,
81}
82
83/// HOW a peer is reached (#64): a direct/hole-punched QUIC path, or through a relay.
84///
85/// `rtt_ms` is NOT a proxy for this — a fast relay beats a slow direct path — and iroh's own
86/// distinction was being dropped at the mcpmesh boundary. Three things depend on it: a truthful
87/// locality claim ("this traffic never left the building"), honest disclosure that a relayed path
88/// depends on third-party infrastructure, and diagnostics, since "slow" has a different cause and
89/// fix in each case.
90///
91/// **Only `Direct` supports a locality claim.** `Unknown` means "we do not know", NOT "private" —
92/// rendering it as private is the one misuse that turns this field into a false privacy statement.
93/// The daemon errs the same way: when a relay path is active it reports [`Relay`](Self::Relay) even
94/// if a direct path is live too, because overstating privacy is worse than understating it.
95///
96/// `#[non_exhaustive]`: iroh already has a third address kind (a custom transport) that could
97/// warrant a variant, and adding one to a public enum later breaks every downstream exhaustive
98/// `match` — the lesson #58 paid for.
99#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
100#[serde(tag = "kind", rename_all = "snake_case")]
101#[non_exhaustive]
102pub enum PeerPath {
103 /// A direct or hole-punched QUIC path: the bytes did not transit a relay.
104 Direct,
105 /// Through a relay server. `url` is the relay in use when known.
106 Relay {
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 url: Option<String>,
109 },
110 /// Not known: never probed, no selected path, or a transport mcpmesh does not model.
111 ///
112 /// `#[serde(other)]` makes this the landing spot for a `kind` a client has never heard of. That
113 /// is what actually buys wire-additivity: `#[non_exhaustive]` only protects the Rust `match`,
114 /// and without this an older client hits `unknown variant` and fails to deserialize the WHOLE
115 /// `PeerReachability` — one new path kind would break every `status` response it reads.
116 #[default]
117 #[serde(other)]
118 Unknown,
119}
120
121/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean: a nickname, a
122/// bool, latency/age NUMBERS, the stable `eid:` principal (#42), and since #64 the PATH KIND —
123/// direct vs relay, plus the relay URL when relayed. Never a socket address, an IP, or a key: the
124/// path field says WHICH KIND of route is in use, never where the peer is.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PeerReachability {
127 pub name: String, // the peer's nickname
128 pub reachable: bool, // result of the last probe (false if never probed)
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 pub rtt_ms: Option<u64>, // last measured round-trip, if reachable
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
133 /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
134 /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
135 /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
136 /// display data; never an authz input. Near-real-time when `status` is read (the probe
137 /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
138 #[serde(default, skip_serializing_if = "String::is_empty")]
139 pub meta: String,
140 /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
141 /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
142 /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
143 /// for a real row (`Option` only for additive round-trip). Machine-surface authz
144 /// vocabulary — the human `status` reachability line is unchanged. Additive:
145 /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
146 #[serde(default, skip_serializing_if = "Option::is_none")]
147 pub principal: Option<String>,
148 /// HOW this peer is reached (#64) — see [`PeerPath`]. Captured by the same probe that sets
149 /// `reachable`/`rtt_ms`, so it shares their freshness: one TTL, one `age_secs`. `Unknown` for a
150 /// peer never probed. Additive (`#[serde(default)]`), so older rows and clients are unaffected.
151 #[serde(default)]
152 pub path: PeerPath,
153}
154
155/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
156/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
157/// as-transport-vocab. Absent in a pure-pairing daemon.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159pub struct RosterStatus {
160 pub org_id: String,
161 pub serial: u64,
162 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
163 pub org_root_fingerprint: String, // short-word form
164}
165
166/// One reachable roster peer device as reported by `status` (the advisory presence read).
167/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
168/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
169/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
170#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
171pub struct PresencePeer {
172 pub user_id: String,
173 pub device_label: String,
174 pub role: String, // "primary" | "mirror" (roster vocabulary)
175 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
176 pub online: bool,
177 /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
178 /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
179 /// data; never an authz input. Additive: default + skip-if-empty.
180 #[serde(default, skip_serializing_if = "String::is_empty")]
181 pub meta: String,
182}
183
184/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
185/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
186/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
187/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
188/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
189/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
190/// an epoch — never an EndpointId.
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
192pub struct RecentPairing {
193 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
194 pub peer_nickname: String,
195 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
196 /// `PairResult.sas_code` carried. Never checked programmatically.
197 pub sas_code: String,
198 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
199 pub paired_at_epoch: u64,
200}
201
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct StatusResult {
204 pub stack_version: String,
205 pub services: Vec<ServiceInfo>,
206 pub peers: Vec<PeerInfo>,
207 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
208 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
209 #[serde(default, skip_serializing_if = "Option::is_none")]
210 pub roster: Option<RosterStatus>,
211 /// The reachable roster peer devices (the advisory presence read), each with an `online`
212 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
213 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
214 #[serde(default, skip_serializing_if = "Vec::is_empty")]
215 pub presence: Vec<PresencePeer>,
216 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
217 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
218 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
219 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
220 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub self_user_id: Option<String>,
222 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
223 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
224 /// that has accepted no pairing since it started. Additive:
225 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
226 #[serde(default, skip_serializing_if = "Vec::is_empty")]
227 pub recent_pairings: Vec<RecentPairing>,
228 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
229 /// first probe completes. Additive: default + skip-if-empty.
230 #[serde(default, skip_serializing_if = "Vec::is_empty")]
231 pub reachability: Vec<PeerReachability>,
232 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
233 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
234 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
235 /// skip-if-empty so an older payload round-trips.
236 #[serde(default, skip_serializing_if = "String::is_empty")]
237 pub self_nickname: String,
238}
239
240/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(deny_unknown_fields)]
243pub struct RegisterServiceParams {
244 pub name: String,
245 pub backend: BackendSpec,
246 pub allow: Vec<String>,
247 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
248 /// to the on-disk config, and automatically unregistered when the control connection that
249 /// registered it closes (and gone on daemon restart). For an embedder that serves a
250 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
251 /// socket path solely to keep a persisted registration valid, and the stale-registration
252 /// accumulation that comes with no unregister. Default false = the persistent behavior.
253 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
254 pub ephemeral: bool,
255}
256
257/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
258/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
259/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
260/// list (an invite that grants nothing is useless — #34).
261#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
262#[serde(deny_unknown_fields)]
263pub struct InviteParams {
264 #[serde(default)]
265 pub services: Vec<String>,
266 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
267 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
268 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
269 #[serde(default, skip_serializing_if = "Option::is_none")]
270 pub app_label: Option<String>,
271}
272
273/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
274/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
275#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
276#[serde(deny_unknown_fields)]
277pub struct PairParams {
278 #[serde(default)]
279 pub invite_line: String,
280}
281
282/// Params of [`Request::PeerRemove`]: the nickname to unpair.
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
284#[serde(deny_unknown_fields)]
285pub struct PeerRemoveParams {
286 pub nickname: String,
287}
288
289/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
290/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292#[serde(deny_unknown_fields)]
293pub struct PeerRenameParams {
294 #[serde(default)]
295 pub user_id: Option<String>,
296 #[serde(default)]
297 pub nickname: Option<String>,
298 pub to: String,
299}
300
301/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
302/// (iroh base32) plus the nickname and service allow list to install it under.
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct PeerAddParams {
306 pub nickname: String,
307 pub endpoint_id: String,
308 #[serde(default)]
309 pub allow: Vec<String>,
310}
311
312/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
313/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315#[serde(deny_unknown_fields)]
316pub struct OpenSessionParams {
317 #[serde(default)]
318 pub peer: String,
319 #[serde(default)]
320 pub service: String,
321}
322
323/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
324/// on FIRST install (`b64u:`; omit once pinned — config carries it).
325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
326#[serde(deny_unknown_fields)]
327pub struct RosterInstallParams {
328 pub path: String,
329 #[serde(default, skip_serializing_if = "Option::is_none")]
330 pub org_root_pk: Option<String>,
331}
332
333/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
334/// never crosses the API.
335#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
336#[serde(deny_unknown_fields)]
337pub struct OrgJoinParams {
338 pub org_id: String,
339 pub org_root_pk: String,
340 pub user_id: String,
341 pub user_key: String,
342}
343
344/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
345/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
346/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
347/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
348#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
349#[serde(deny_unknown_fields)]
350pub struct SetAppMetadataParams {
351 pub metadata: String,
352}
353
354/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
355/// principal, or a `b64u:` user_id.
356#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(deny_unknown_fields)]
358pub struct PeerServicesParams {
359 pub peer: String,
360}
361
362/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
363/// caller — computed authoritatively on the peer (which owns the truth), always current, only
364/// the caller's own admitted services (never the peer's full registry).
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366pub struct PeerServicesResult {
367 pub services: Vec<String>,
368}
369
370/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
371/// to remove — the deregistration mirror of `register_service`.
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[serde(deny_unknown_fields)]
374pub struct UnregisterServiceParams {
375 pub name: String,
376}
377
378/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
379/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
380/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
381#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
382#[serde(deny_unknown_fields)]
383pub struct ServiceAllowParams {
384 pub service: String,
385 pub principal: String,
386}
387
388/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
389/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
390/// they stored at pairing time until a re-invite.
391#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
392#[serde(deny_unknown_fields)]
393pub struct SetNicknameParams {
394 pub nickname: String,
395}
396
397/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399#[serde(deny_unknown_fields)]
400pub struct SetRosterUrlParams {
401 pub url: String,
402}
403
404/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
405/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
406/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
407/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
408/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
409/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
410/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
411/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
413#[serde(deny_unknown_fields)]
414pub struct SetRelaysParams {
415 pub relay_urls: Vec<String>,
416}
417
418/// Result of [`Request::SetRelays`] (#53).
419#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
420pub struct SetRelaysResult {
421 /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
422 pub changed: bool,
423 /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
424 /// but NOT applied live — a node restart is required for it to take effect. `false` on the
425 /// live custom→custom path (already applied to the running endpoint).
426 pub restart_required: bool,
427}
428
429/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
430#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
431#[serde(deny_unknown_fields)]
432pub struct BlobPublishParams {
433 pub scope: String,
434 pub path: String,
435}
436
437/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(deny_unknown_fields)]
440pub struct BlobGrantParams {
441 pub scope: String,
442 pub principal: String,
443}
444
445/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
446///
447/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
448/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
449/// access to everything else.
450#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
451#[serde(deny_unknown_fields)]
452pub struct BlobRevokeParams {
453 pub scope: String,
454 pub principals: Vec<String>,
455}
456
457/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
458///
459/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
460/// this takes effect immediately for authorization — but the bytes stay in the local store, and
461/// there is no reclaim verb yet. Do not surface this to a user as deletion.
462#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
463#[serde(deny_unknown_fields)]
464pub struct BlobUnpublishParams {
465 pub scope: String,
466 pub hash: String,
467}
468
469/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
470///
471/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
472/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
473/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
474/// turn the original publisher going offline into a hang at every fetcher.
475///
476/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
477/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
478#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
479#[serde(deny_unknown_fields)]
480pub struct BlobRepublishParams {
481 pub scope: String,
482 pub hash: String,
483}
484
485/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
486#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(deny_unknown_fields)]
488pub struct BlobFetchParams {
489 pub ticket: String,
490 pub dest_path: String,
491}
492
493/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
494/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
495///
496/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
497/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
498/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
499/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
500/// identical to inline variant bodies.
501///
502/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
503/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
504/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
505/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
506/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
507#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
508#[serde(tag = "method", content = "params", rename_all = "snake_case")]
509pub enum Request {
510 /// Register/update a `[services.*]` entry idempotently.
511 RegisterService(RegisterServiceParams),
512 Status,
513 /// Mint a one-time pairing invite granting `services`. The daemon
514 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
515 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
516 /// `method` string generically; the tag comes from `rename_all`.
517 Invite(InviteParams),
518 /// Redeem a pairing invite. The daemon dials the inviter named by
519 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
520 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
521 /// (snake_case); `method_of` reads the `method` string generically.
522 ///
523 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
524 Pair(PairParams),
525 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
526 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
527 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
528 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
529 /// NOT severed here: existing sessions run to completion; the peer only loses the
530 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
531 /// `method_of` reads the `method` string generically (no per-variant arm).
532 ///
533 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
534 PeerRemove(PeerRemoveParams),
535 /// Rename a contact's nickname (nickname) authoritatively. Renames the
536 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
537 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
538 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
539 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
540 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
541 /// host-privileged like the other pair ops.
542 PeerRename(PeerRenameParams),
543 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
544 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
545 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
546 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
547 /// vocabulary — do not build on it. Tag `"peer_add"`.
548 PeerAdd(PeerAddParams),
549 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
550 /// Distinct from the proxy's job: this returns a session the client streams.
551 /// Named `open_session` rather than `connect` to avoid colliding
552 /// with the `connect` porcelain.
553 OpenSession(OpenSessionParams),
554 /// Install a signed roster from a local file (the manual `internal roster install` path).
555 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
556 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
557 /// pins the org root on FIRST install (`b64u:`); omit it
558 /// once pinned (config carries it). Tag `"roster_install"`.
559 RosterInstall(RosterInstallParams),
560 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
561 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
562 /// `user_key` is a LOCAL path
563 /// (the key never crosses the API). Tag `"org_join"`.
564 OrgJoin(OrgJoinParams),
565 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
566 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
567 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
568 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
569 /// `"set_roster_url"`.
570 SetRosterUrl(SetRosterUrlParams),
571 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
572 /// daemon's own serialized config-write path (no lost-update window against a
573 /// concurrent grant/registration) and update the in-memory name future invites
574 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
575 SetNickname(SetNicknameParams),
576 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
577 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
578 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
579 /// on restart; the embedder re-sets on startup).
580 SetAppMetadata(SetAppMetadataParams),
581 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
582 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
583 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
584 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
585 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
586 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
587 /// [`SetRelaysResult`]. Tag `"set_relays"`.
588 SetRelays(SetRelaysParams),
589 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
590 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
591 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
592 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
593 /// hot-reloads. Idempotent. Ack result.
594 UnregisterService(UnregisterServiceParams),
595 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
596 /// and returns the service names whose allow admits the caller's principal. Answers
597 /// [`PeerServicesResult`].
598 PeerServices(PeerServicesParams),
599 ServiceAllowGrant(ServiceAllowParams),
600 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
601 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
602 /// Idempotent. Ack result.
603 ServiceAllowRevoke(ServiceAllowParams),
604 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
605 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
606 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
607 /// Tag `"blob_publish"`.
608 BlobPublish(BlobPublishParams),
609 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
610 /// nickname (the shared `principal_set` expansion). Tag
611 /// `"blob_grant"`.
612 BlobGrant(BlobGrantParams),
613 /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
614 BlobRevoke(BlobRevokeParams),
615 /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
616 /// bytes.
617 BlobUnpublish(BlobUnpublishParams),
618 /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
619 /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
620 /// two interchangeably after a fetch.
621 BlobRepublish(BlobRepublishParams),
622 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
623 BlobList,
624 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
625 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
626 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
627 BlobFetch(BlobFetchParams),
628 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
629 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
630 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
631 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
632 /// `method_of` reads the `method` string generically (no per-variant arm).
633 AuditSummary,
634 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
635 /// connection STOPS being request/response after this call and becomes a one-way push stream
636 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
637 Subscribe,
638}
639
640/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
641/// computed porcelain-side from the invite's org_root_pk). Additive-only.
642#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
643pub struct OrgJoinResult {
644 pub org_id: String,
645}
646
647/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
648/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
649/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
650///
651/// Additive-only: any future field MUST land as
652/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
653#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
654pub struct RosterInstallResult {
655 pub org_id: String,
656 pub serial: u64,
657 /// How many live sessions were severed, for the porcelain's confirmation line.
658 #[serde(default)]
659 pub severed: u32,
660}
661
662/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
663/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
664/// carve-out as the pairing invite line). Additive-only.
665#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
666pub struct BlobPublishResult {
667 pub ticket: String,
668 pub hash: String, // bare blake3 hex
669}
670
671/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
672/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
674pub struct ScopeInfo {
675 pub name: String,
676 pub hashes: Vec<String>,
677 pub grants: Vec<String>,
678}
679
680/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
681#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
682pub struct BlobScopeList {
683 pub scopes: Vec<ScopeInfo>,
684}
685
686/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
687/// Additive-only.
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
689pub struct BlobFetchResult {
690 pub hash: String,
691 pub bytes_len: u64,
692}
693
694/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
695/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
696/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
697/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
698/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
699/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
700///
701/// Additive-only: any future field MUST land as
702/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
703#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
704pub struct AuditSummaryResult {
705 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
706 /// peer to attribute) but IS in `total_sessions`.
707 pub per_peer: Vec<(String, u64)>,
708 /// Sessions opened per registered service name.
709 pub per_service: Vec<(String, u64)>,
710 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
711 #[serde(default)]
712 pub total_sessions: u64,
713}
714
715/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
716/// (the ONE pairing artifact deliberately carved out of the
717/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
718/// absolute expiry in epoch seconds (≤ now + 24h).
719///
720/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
721/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
722/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
723/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
724/// ceremony" note in `docs/local-protocol.md` (#35).
725///
726/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
727/// so older payloads still deserialize.
728#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
729pub struct InviteResult {
730 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
731 pub invite_line: String,
732 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
733 pub expires_at_epoch: u64,
734}
735
736/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
737/// redeemer's local name for the new peer) plus the display-only short authentication
738/// code (SAS) — a few words the human reads aloud to a second channel to
739/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
740/// artifact (like the invite line), NOT a transport-vocabulary leak.
741///
742/// Additive-only: any future field MUST land as
743/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
744#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
745pub struct PairResult {
746 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
747 pub peer_nickname: String,
748 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
749 /// sides for the out-of-band human check. Never sent on the wire, never checked
750 /// programmatically.
751 pub sas_code: String,
752 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
753 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
754 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
755 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
756 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
757 #[serde(default, skip_serializing_if = "Vec::is_empty")]
758 pub services: Vec<String>,
759 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
760 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
761 #[serde(default, skip_serializing_if = "Option::is_none")]
762 pub app_label: Option<String>,
763 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
764 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
765 /// can align with its own — and the same value it may later pass to `open_session` to dial
766 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
767 /// binding (a legacy/keyless peer). Additive.
768 #[serde(default, skip_serializing_if = "Option::is_none")]
769 pub peer_user_id: Option<String>,
770}
771
772/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
773/// top of the base record schema: it removes no field and makes the JSONL self-describing so
774/// a consumer can filter by class without guessing from which optional fields are present.
775#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
776#[serde(rename_all = "snake_case")]
777pub enum AuditKind {
778 /// A mesh session opened (a backend was selected for an authenticated peer).
779 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
780 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
781 SessionOpen,
782 /// A mesh session closed (the backend returned / the session tore down).
783 SessionClose,
784 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
785 Request,
786 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
787 BlobFetch,
788 /// A trust mutation (pair, unpair, roster install/swap, revoke).
789 Trust,
790}
791
792/// One audit record — the union of the event classes, and the `record` payload of a
793/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
794/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
795/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
796/// `bytes_out`).
797///
798/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
799/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
800/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
801#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
802pub struct AuditRecord {
803 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
804 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
805 pub ts: String,
806 pub kind: AuditKind,
807 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
808 /// local-only events with no remote peer (a manual roster install).
809 #[serde(skip_serializing_if = "Option::is_none")]
810 pub peer: Option<String>,
811 #[serde(skip_serializing_if = "Option::is_none")]
812 pub service: Option<String>,
813 #[serde(skip_serializing_if = "Option::is_none")]
814 pub method: Option<String>,
815 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
816 #[serde(skip_serializing_if = "Option::is_none")]
817 pub tool: Option<String>,
818 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
819 #[serde(skip_serializing_if = "Option::is_none")]
820 pub args_hash: Option<String>,
821 /// Byte COUNT of the response sent back to the peer — a count, never the content.
822 #[serde(skip_serializing_if = "Option::is_none")]
823 pub bytes_out: Option<u64>,
824 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
825 #[serde(skip_serializing_if = "Option::is_none")]
826 pub status: Option<String>,
827 #[serde(skip_serializing_if = "Option::is_none")]
828 pub latency_ms: Option<u64>,
829 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
830 #[serde(skip_serializing_if = "Option::is_none")]
831 pub event: Option<String>,
832 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
833 /// nickname or `org/serial` (`Trust`).
834 #[serde(skip_serializing_if = "Option::is_none")]
835 pub target: Option<String>,
836}
837
838impl AuditRecord {
839 fn base(ts: String, kind: AuditKind) -> Self {
840 Self {
841 ts,
842 kind,
843 peer: None,
844 service: None,
845 method: None,
846 tool: None,
847 args_hash: None,
848 bytes_out: None,
849 status: None,
850 latency_ms: None,
851 event: None,
852 target: None,
853 }
854 }
855
856 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
857 let mut r = Self::base(ts, AuditKind::SessionOpen);
858 r.peer = peer;
859 r.service = Some(service);
860 r
861 }
862
863 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
864 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
865 /// reaches no backend and so is never audited by the far side's session guard — without a
866 /// dedicated constructor. DRY: reuses the existing optional `status` field.
867 pub fn with_status(mut self, status: &str) -> Self {
868 self.status = Some(status.into());
869 self
870 }
871
872 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
873 let mut r = Self::base(ts, AuditKind::SessionClose);
874 r.peer = peer;
875 r.service = Some(service);
876 r
877 }
878
879 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
880 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
881 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
882 #[allow(clippy::too_many_arguments)]
883 pub fn proxied_request(
884 ts: String,
885 peer: Option<String>,
886 service: String,
887 method: String,
888 tool: Option<String>,
889 args_hash: String,
890 bytes_out: u64,
891 status: String,
892 latency_ms: u64,
893 ) -> Self {
894 let mut r = Self::base(ts, AuditKind::Request);
895 r.peer = peer;
896 r.service = Some(service);
897 r.method = Some(method);
898 r.tool = tool;
899 r.args_hash = Some(args_hash);
900 r.bytes_out = Some(bytes_out);
901 r.status = Some(status);
902 r.latency_ms = Some(latency_ms);
903 r
904 }
905
906 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
907 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
908 pub fn proxied_notification(
909 ts: String,
910 peer: Option<String>,
911 service: String,
912 method: String,
913 tool: Option<String>,
914 args_hash: String,
915 ) -> Self {
916 let mut r = Self::base(ts, AuditKind::Request);
917 r.peer = peer;
918 r.service = Some(service);
919 r.method = Some(method);
920 r.tool = tool;
921 r.args_hash = Some(args_hash);
922 r
923 }
924
925 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
926 let mut r = Self::base(ts, AuditKind::BlobFetch);
927 r.peer = peer;
928 r.target = Some(hash);
929 r.status = Some(status);
930 r
931 }
932
933 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
934 let mut r = Self::base(ts, AuditKind::Trust);
935 r.event = Some(event);
936 r.target = target;
937 r
938 }
939}
940
941/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
942/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
943#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
944pub struct ActiveSession {
945 pub peer: String,
946 pub service: String,
947 pub opened_at: i64,
948}
949
950/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
951/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
952/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
953/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
954/// them (see `docs/local-protocol.md` "Live event stream").
955/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
956/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
957/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
958/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
959#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
960#[serde(tag = "type", rename_all = "snake_case")]
961#[non_exhaustive]
962pub enum StreamFrame {
963 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
964 /// reachability) so a fresh subscriber renders immediately without replaying history.
965 Snapshot {
966 active_sessions: Vec<ActiveSession>,
967 reachability: Vec<PeerReachability>,
968 },
969 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
970 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
971 /// `Box`, so the wire shape is the record's fields verbatim.
972 Event { record: Box<AuditRecord> },
973 /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
974 /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
975 /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
976 /// it returns, rather than on the next poll tick.
977 ///
978 /// Emitted on a CHANGE of `reachable` only. A refreshed probe with the same verdict emits
979 /// nothing, so a peer that stays up does not produce a frame per TTL refresh; `rtt_ms`/`meta`/
980 /// `services` drift is advisory detail and is not a transition. `age_secs` is `0` — the probe
981 /// just completed.
982 Reachability { peer: PeerReachability },
983 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
984 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
985 Lagged { dropped: u64 },
986}
987
988/// Extract the `method` tag from a raw request value without deserializing the whole
989/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
990/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
991/// methods (adjacent tagging rejects `params:{}` on unit variants).
992pub fn method_of(v: &serde_json::Value) -> Option<&str> {
993 v.get("method").and_then(serde_json::Value::as_str)
994}
995
996/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
997/// Config→BackendSpec is a hand-written match, not a serde passthrough.
998#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
999#[serde(rename_all = "snake_case")]
1000pub enum BackendSpec {
1001 Run {
1002 cmd: Vec<String>,
1003 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
1004 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
1005 /// these (identity is not spoofable by a service definition). Default empty.
1006 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1007 env: BTreeMap<String, String>,
1008 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
1009 #[serde(default, skip_serializing_if = "Option::is_none")]
1010 cwd: Option<String>,
1011 },
1012 Socket {
1013 path: String,
1014 },
1015}
1016
1017/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
1018/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
1019/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
1020/// `{}` (success) for an unknown name, which silently included every ephemeral service.
1021pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
1022/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
1023/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
1024pub const ERR_NO_SUCH_BLOB: i64 = -32041;
1025
1026pub const API_NAME: &str = "mcpmesh-local/1";
1027/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
1028///
1029/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
1030/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
1031/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
1032/// new methods, or a strictness change like params validation — bumped in the same change that
1033/// makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
1034/// older than a minor it requires. It never resets except on a MAJOR bump.
1035pub const API_VERSION: &str = "1.18";
1036/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
1037/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
1038/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
1039/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
1040/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
1041/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
1042/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
1043/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
1044/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
1045/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
1046/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
1047/// observable contract did: a revoked principal's next session is refused even on a connection it
1048/// already holds, and its live connections are severed. Previously both waited for the peer to
1049/// disconnect on its own, which is unbounded (#54). A consumer can guard on
1050/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
1051/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
1052/// about an unknown service name — a name in neither the config nor the ephemeral registry now
1053/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
1054/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
1055/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
1056/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
1057/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
1058/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
1059/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
1060/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
1061/// errored on any daemon without an org root key, though their scope gate never needed one (#61).
1062pub const API_MINOR: u32 = 18;
1063
1064#[cfg(test)]
1065mod tests {
1066 use super::*;
1067
1068 /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
1069 /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
1070 /// privacy guarantee that daemon never made.
1071 #[test]
1072 fn peer_path_tags_and_defaults_to_unknown() {
1073 let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
1074 assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
1075 assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
1076 let relay = tagged(PeerPath::Relay {
1077 url: Some("https://relay.example/".into()),
1078 });
1079 assert_eq!(relay["kind"], "relay");
1080 assert_eq!(relay["url"], "https://relay.example/");
1081 // A relay whose URL we do not know still tags as relay, with the key elided.
1082 let bare = tagged(PeerPath::Relay { url: None });
1083 assert_eq!(bare["kind"], "relay");
1084 assert!(bare.get("url").is_none(), "elided, not null: {bare}");
1085
1086 // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
1087 // row. Without `#[serde(other)]` an unknown `kind` errors out of
1088 // `PeerReachability` entirely, so one new variant would break every `status` read an
1089 // older pinned client does.
1090 let future: PeerPath =
1091 serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
1092 assert_eq!(future, PeerPath::Unknown);
1093 let row: PeerReachability = serde_json::from_value(serde_json::json!({
1094 "name": "bob", "reachable": true, "path": {"kind": "quantum"}
1095 }))
1096 .expect("an unknown path kind must not fail the whole row");
1097 assert_eq!(row.path, PeerPath::Unknown);
1098 assert!(row.reachable, "the rest of the row survives");
1099
1100 // A pre-#64 row: no `path` key.
1101 let old = serde_json::json!({"name": "bob", "reachable": true});
1102 let parsed: PeerReachability = serde_json::from_value(old).unwrap();
1103 assert_eq!(
1104 parsed.path,
1105 PeerPath::Unknown,
1106 "an older daemon's row must never imply a direct path"
1107 );
1108 }
1109
1110 /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
1111 /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
1112 /// consumer projects both through one code path.
1113 #[test]
1114 fn reachability_frame_tags_and_round_trips() {
1115 let frame = StreamFrame::Reachability {
1116 peer: PeerReachability {
1117 name: "bob".into(),
1118 reachable: true,
1119 rtt_ms: Some(12),
1120 age_secs: Some(0),
1121 meta: String::new(),
1122 principal: Some("eid:beef".into()),
1123 path: Default::default(),
1124 },
1125 };
1126 let v = serde_json::to_value(&frame).unwrap();
1127 assert_eq!(v["type"], "reachability");
1128 assert_eq!(v["peer"]["name"], "bob");
1129 assert_eq!(v["peer"]["reachable"], true);
1130 assert_eq!(
1131 v["peer"]["age_secs"], 0,
1132 "a transition frame is fresh by construction: {v}"
1133 );
1134 let back: StreamFrame = serde_json::from_value(v).unwrap();
1135 assert_eq!(back, frame);
1136 }
1137
1138 #[test]
1139 fn peer_reachability_serde_is_additive() {
1140 let r = PeerReachability {
1141 name: "bob".into(),
1142 reachable: true,
1143 rtt_ms: Some(42),
1144 age_secs: Some(3),
1145 meta: String::new(),
1146 principal: None,
1147 path: Default::default(),
1148 };
1149 let v = serde_json::to_value(&r).unwrap();
1150 assert_eq!(v["name"], "bob");
1151 assert_eq!(v["reachable"], true);
1152 assert_eq!(v["rtt_ms"], 42);
1153 assert_eq!(v["age_secs"], 3);
1154 // Never-probed peer: optionals elided, not null.
1155 let unknown = PeerReachability {
1156 name: "carol".into(),
1157 reachable: false,
1158 rtt_ms: None,
1159 age_secs: None,
1160 meta: String::new(),
1161 principal: None,
1162 path: Default::default(),
1163 };
1164 let uv = serde_json::to_value(&unknown).unwrap();
1165 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
1166 // An older StatusResult (no reachability field) still deserializes.
1167 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
1168 let s: StatusResult = serde_json::from_value(old).unwrap();
1169 assert!(s.reachability.is_empty());
1170 }
1171
1172 #[test]
1173 fn subscribe_method_tag_resolves() {
1174 let req = serde_json::to_value(Request::Subscribe).unwrap();
1175 assert_eq!(method_of(&req), Some("subscribe"));
1176 }
1177
1178 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
1179
1180 #[test]
1181 fn invite_params_reject_singular_service_typo() {
1182 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
1183 // InviteParams { services: [] } and mint a grants-nothing invite that looked
1184 // successful. With deny_unknown_fields the typo is a loud parse error instead.
1185 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
1186 assert!(
1187 err.is_err(),
1188 "an unknown `service` key must be rejected, not silently ignored"
1189 );
1190 // The correct plural shape still parses.
1191 let ok: InviteParams =
1192 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
1193 assert_eq!(ok.services, vec!["kb".to_string()]);
1194 }
1195
1196 #[test]
1197 fn open_session_params_reject_unknown_field() {
1198 let err = serde_json::from_value::<OpenSessionParams>(
1199 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
1200 );
1201 assert!(err.is_err(), "unknown params keys must be rejected");
1202 }
1203
1204 #[test]
1205 fn set_app_metadata_request_carries_the_method_tag() {
1206 let r = Request::SetAppMetadata(SetAppMetadataParams {
1207 metadata: "v=1.2.3".into(),
1208 });
1209 let v = serde_json::to_value(&r).unwrap();
1210 assert_eq!(v["method"], "set_app_metadata");
1211 assert_eq!(v["params"]["metadata"], "v=1.2.3");
1212 assert_eq!(method_of(&v), Some("set_app_metadata"));
1213 }
1214
1215 #[test]
1216 fn set_app_metadata_params_reject_unknown_field() {
1217 let err = serde_json::from_value::<SetAppMetadataParams>(
1218 serde_json::json!({"metadata": "x", "nonsense": 1}),
1219 );
1220 assert!(err.is_err(), "unknown params keys must be rejected");
1221 }
1222
1223 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1224 /// empty meta does not serialize.
1225 #[test]
1226 fn peer_info_principal_is_additive() {
1227 // An older payload (no principal) still deserializes; empty does not serialize.
1228 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1229 let p: PeerInfo = serde_json::from_value(old).unwrap();
1230 assert_eq!(p.principal, None);
1231 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1232 // A bound peer carries BOTH the person user_id AND the device principal (#41).
1233 let full = PeerInfo {
1234 name: "bob".into(),
1235 services: vec!["notes".into()],
1236 user_id: Some("b64u:BOB".into()),
1237 principal: Some("eid:0707".into()),
1238 };
1239 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1240 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1241 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1242 }
1243
1244 #[test]
1245 fn peer_reachability_principal_is_additive() {
1246 // Older payload (no principal) still deserializes; empty does not serialize; a set
1247 // value round-trips alongside the #40 meta so an embedder joins on the principal.
1248 let old = serde_json::json!({"name": "bob", "reachable": true});
1249 let r: PeerReachability = serde_json::from_value(old).unwrap();
1250 assert_eq!(r.principal, None);
1251 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1252 let full = PeerReachability {
1253 name: "bob".into(),
1254 reachable: true,
1255 rtt_ms: Some(12),
1256 age_secs: Some(3),
1257 meta: "v=1.2.3".into(),
1258 principal: Some("eid:0707".into()),
1259 path: Default::default(),
1260 };
1261 let back: PeerReachability =
1262 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1263 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1264 assert_eq!(back.meta, "v=1.2.3");
1265 }
1266
1267 #[test]
1268 fn peer_reachability_meta_is_additive() {
1269 // An older payload (no meta) still deserializes; an empty meta does not serialize.
1270 let old = serde_json::json!({"name": "bob", "reachable": true});
1271 let r: PeerReachability = serde_json::from_value(old).unwrap();
1272 assert_eq!(r.meta, "");
1273 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1274 // A set value round-trips.
1275 let with = PeerReachability {
1276 name: "bob".into(),
1277 reachable: true,
1278 rtt_ms: Some(12),
1279 age_secs: Some(3),
1280 meta: "v=1.2.3".into(),
1281 principal: None,
1282 path: Default::default(),
1283 };
1284 let back: PeerReachability =
1285 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1286 assert_eq!(back.meta, "v=1.2.3");
1287 }
1288
1289 #[test]
1290 fn presence_peer_meta_is_additive() {
1291 let old = serde_json::json!({
1292 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1293 });
1294 let p: PresencePeer = serde_json::from_value(old).unwrap();
1295 assert_eq!(p.meta, "");
1296 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1297 }
1298
1299 #[test]
1300 fn set_nickname_request_carries_the_method_tag() {
1301 let r = Request::SetNickname(SetNicknameParams {
1302 nickname: "workbench".into(),
1303 });
1304 let v = serde_json::to_value(&r).unwrap();
1305 assert_eq!(v["method"], "set_nickname");
1306 assert_eq!(v["params"]["nickname"], "workbench");
1307 assert_eq!(method_of(&v), Some("set_nickname"));
1308 }
1309
1310 #[test]
1311 fn set_nickname_params_reject_unknown_field() {
1312 let err = serde_json::from_value::<SetNicknameParams>(
1313 serde_json::json!({"nickname": "x", "nonsense": 1}),
1314 );
1315 assert!(err.is_err(), "unknown params keys must be rejected");
1316 }
1317
1318 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1319 /// the additive-only contract — and an empty name must not serialize at all.
1320 #[test]
1321 fn status_self_nickname_is_additive() {
1322 let old = serde_json::json!({
1323 "stack_version": "0.7.0", "services": [], "peers": []
1324 });
1325 let s: StatusResult = serde_json::from_value(old).unwrap();
1326 assert_eq!(s.self_nickname, "");
1327 let v = serde_json::to_value(&s).unwrap();
1328 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1329 }
1330
1331 #[test]
1332 fn api_minor_is_present_and_monotonic_from_hello() {
1333 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1334 // crate/stack version, additive on the Hello frame.
1335 let h = Hello {
1336 api: API_NAME.into(),
1337 api_version: API_VERSION.into(),
1338 api_minor: API_MINOR,
1339 stack_version: "9.9.9".into(),
1340 };
1341 let v = serde_json::to_value(&h).unwrap();
1342 assert_eq!(v["api_minor"], API_MINOR);
1343 // An OLD Hello without api_minor still deserializes (additive contract).
1344 let old = serde_json::json!({
1345 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1346 });
1347 let back: Hello = serde_json::from_value(old).unwrap();
1348 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1349 }
1350
1351 #[test]
1352 fn hello_result_roundtrips() {
1353 let h = Hello {
1354 api: "mcpmesh-local/1".into(),
1355 api_version: "1.0".into(),
1356 api_minor: 0,
1357 stack_version: "0.1.0".into(),
1358 };
1359 let v = serde_json::to_value(&h).unwrap();
1360 assert_eq!(v["api"], "mcpmesh-local/1");
1361 let back: Hello = serde_json::from_value(v).unwrap();
1362 assert_eq!(back, h);
1363 }
1364
1365 #[test]
1366 fn request_tagged_by_method() {
1367 let r = Request::Status;
1368 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1369 let r = Request::OpenSession(OpenSessionParams {
1370 peer: "alice".into(),
1371 service: "notes".into(),
1372 });
1373 let v = serde_json::to_value(&r).unwrap();
1374 assert_eq!(v["method"], "open_session");
1375 assert_eq!(v["params"]["peer"], "alice");
1376 }
1377
1378 #[test]
1379 fn parameterless_method_tolerates_params_forms() {
1380 // Omitted and null params deserialize straight into the unit variant.
1381 let omitted: Request =
1382 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1383 assert_eq!(omitted, Request::Status);
1384 let null: Request =
1385 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1386 .unwrap();
1387 assert_eq!(null, Request::Status);
1388
1389 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1390 // the server MUST dispatch on the method string rather than deserialize the whole
1391 // message into `Request`. This is the pattern the daemon's dispatcher uses.
1392 let empty = serde_json::json!({"method": "status", "params": {}});
1393 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1394 match method_of(&empty) {
1395 Some("status") => {} // dispatcher resolves Status via the method string
1396 other => panic!("method_of failed to resolve status: {other:?}"),
1397 }
1398 }
1399
1400 #[test]
1401 fn backend_spec_roundtrips() {
1402 let run = BackendSpec::Run {
1403 cmd: vec!["notes-mcp".into(), "--stdio".into()],
1404 env: Default::default(),
1405 cwd: None,
1406 };
1407 let v = serde_json::to_value(&run).unwrap();
1408 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1409 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1410
1411 let sock = BackendSpec::Socket {
1412 path: "/run/notes.sock".into(),
1413 };
1414 let v = serde_json::to_value(&sock).unwrap();
1415 assert_eq!(v["socket"]["path"], "/run/notes.sock");
1416 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1417 }
1418
1419 #[test]
1420 fn register_service_wire_shape() {
1421 let r = Request::RegisterService(RegisterServiceParams {
1422 name: "notes".into(),
1423 backend: BackendSpec::Run {
1424 cmd: vec!["notes-mcp".into()],
1425 env: Default::default(),
1426 cwd: None,
1427 },
1428 allow: vec!["alice".into()],
1429 ephemeral: false,
1430 });
1431 let v = serde_json::to_value(&r).unwrap();
1432 assert_eq!(
1433 v,
1434 serde_json::json!({
1435 "method": "register_service",
1436 "params": {
1437 "name": "notes",
1438 "backend": {"run": {"cmd": ["notes-mcp"]}},
1439 "allow": ["alice"],
1440 }
1441 })
1442 );
1443 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1444 }
1445
1446 #[test]
1447 fn invite_request_and_result_roundtrip() {
1448 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1449 let r = Request::Invite(InviteParams {
1450 services: vec!["notes".into(), "kb".into()],
1451 app_label: None,
1452 });
1453 let v = serde_json::to_value(&r).unwrap();
1454 assert_eq!(v["method"], "invite");
1455 assert_eq!(v["params"]["services"][0], "notes");
1456 assert_eq!(v["params"]["services"][1], "kb");
1457 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1458 // method_of resolves the tag generically (no per-variant arm).
1459 assert_eq!(
1460 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1461 Some("invite")
1462 );
1463
1464 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1465 let res = InviteResult {
1466 invite_line: "mcpmesh-invite:ABCDEF".into(),
1467 expires_at_epoch: 1_800_000_000,
1468 };
1469 let v = serde_json::to_value(&res).unwrap();
1470 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1471 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1472 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1473 }
1474
1475 #[test]
1476 fn pair_request_and_result_roundtrip() {
1477 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1478 let r = Request::Pair(PairParams {
1479 invite_line: "mcpmesh-invite:ABCDEF".into(),
1480 });
1481 let v = serde_json::to_value(&r).unwrap();
1482 assert_eq!(v["method"], "pair");
1483 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1484 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1485 // method_of resolves the tag generically (no per-variant arm).
1486 assert_eq!(
1487 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1488 Some("pair")
1489 );
1490
1491 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1492 // the granted services (the porcelain renders each as `<peer>/<service>`).
1493 let res = PairResult {
1494 peer_nickname: "alice".into(),
1495 sas_code: "tango-fig-cabbage".into(),
1496 services: vec!["notes".into(), "kb".into()],
1497 app_label: None,
1498 peer_user_id: None,
1499 };
1500 let v = serde_json::to_value(&res).unwrap();
1501 assert_eq!(v["peer_nickname"], "alice");
1502 assert_eq!(v["sas_code"], "tango-fig-cabbage");
1503 assert_eq!(v["services"][0], "notes");
1504 assert_eq!(v["services"][1], "kb");
1505 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1506
1507 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1508 // deserializes — the `#[serde(default)]` fills it with an empty list.
1509 let old_shape = serde_json::json!({
1510 "peer_nickname": "alice",
1511 "sas_code": "tango-fig-cabbage",
1512 });
1513 let back: PairResult = serde_json::from_value(old_shape).unwrap();
1514 assert_eq!(back.peer_nickname, "alice");
1515 assert!(back.services.is_empty());
1516 }
1517
1518 #[test]
1519 fn roster_install_request_and_result_roundtrip() {
1520 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1521 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1522 let r = Request::RosterInstall(RosterInstallParams {
1523 path: "/tmp/roster.json".into(),
1524 org_root_pk: Some("b64u:AAAA".into()),
1525 });
1526 let v = serde_json::to_value(&r).unwrap();
1527 assert_eq!(v["method"], "roster_install");
1528 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1529 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1530 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1531 // method_of resolves the tag generically (no per-variant arm).
1532 assert_eq!(
1533 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1534 Some("roster_install")
1535 );
1536
1537 // When the pk is omitted (a subsequent install using the pinned value), it is
1538 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1539 let omit = Request::RosterInstall(RosterInstallParams {
1540 path: "/tmp/roster.json".into(),
1541 org_root_pk: None,
1542 });
1543 let v = serde_json::to_value(&omit).unwrap();
1544 assert!(
1545 v["params"].get("org_root_pk").is_none(),
1546 "an omitted org_root_pk must not appear on the wire: {v}"
1547 );
1548 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1549
1550 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1551 let res = RosterInstallResult {
1552 org_id: "acme".into(),
1553 serial: 42,
1554 severed: 1,
1555 };
1556 let v = serde_json::to_value(&res).unwrap();
1557 assert_eq!(v["org_id"], "acme");
1558 assert_eq!(v["serial"], 42u64);
1559 assert_eq!(v["severed"], 1u32);
1560 assert_eq!(
1561 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1562 res
1563 );
1564
1565 // Additive-only: a result minted by an older daemon (no `severed` key) still
1566 // deserializes — the `#[serde(default)]` fills it with 0.
1567 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1568 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1569 assert_eq!(back.serial, 7);
1570 assert_eq!(back.severed, 0);
1571 }
1572
1573 #[test]
1574 fn org_join_request_and_result_roundtrip() {
1575 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1576 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1577 let r = Request::OrgJoin(OrgJoinParams {
1578 org_id: "acme".into(),
1579 org_root_pk: "b64u:AAAA".into(),
1580 user_id: "alice".into(),
1581 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1582 });
1583 let v = serde_json::to_value(&r).unwrap();
1584 assert_eq!(v["method"], "org_join");
1585 assert_eq!(v["params"]["org_id"], "acme");
1586 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1587 assert_eq!(v["params"]["user_id"], "alice");
1588 assert_eq!(
1589 v["params"]["user_key"],
1590 "/home/alice/.config/mcpmesh/user.key"
1591 );
1592 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1593 // method_of resolves the tag generically (no per-variant arm).
1594 assert_eq!(
1595 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1596 Some("org_join")
1597 );
1598
1599 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1600 let res = OrgJoinResult {
1601 org_id: "acme".into(),
1602 };
1603 let v = serde_json::to_value(&res).unwrap();
1604 assert_eq!(v["org_id"], "acme");
1605 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1606 }
1607
1608 #[test]
1609 fn set_roster_url_request_roundtrip() {
1610 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1611 let r = Request::SetRosterUrl(SetRosterUrlParams {
1612 url: "https://intranet.acme.com/roster.json".into(),
1613 });
1614 let v = serde_json::to_value(&r).unwrap();
1615 assert_eq!(v["method"], "set_roster_url");
1616 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1617 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1618 assert_eq!(
1619 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1620 Some("set_roster_url")
1621 );
1622 }
1623
1624 #[test]
1625 fn peer_remove_request_roundtrip() {
1626 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1627 let r = Request::PeerRemove(PeerRemoveParams {
1628 nickname: "bob".into(),
1629 });
1630 let v = serde_json::to_value(&r).unwrap();
1631 assert_eq!(v["method"], "peer_remove");
1632 assert_eq!(v["params"]["nickname"], "bob");
1633 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1634 // method_of resolves the tag generically (no per-variant arm).
1635 assert_eq!(
1636 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1637 Some("peer_remove")
1638 );
1639 }
1640
1641 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1642 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1643 /// defaulting to empty when absent.
1644 #[test]
1645 fn peer_add_request_roundtrip() {
1646 let r = Request::PeerAdd(PeerAddParams {
1647 nickname: "bob".into(),
1648 endpoint_id: "96246d3f".into(),
1649 allow: vec!["notes".into()],
1650 });
1651 let v = serde_json::to_value(&r).unwrap();
1652 assert_eq!(v["method"], "peer_add");
1653 assert_eq!(v["params"]["nickname"], "bob");
1654 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1655 assert_eq!(v["params"]["allow"][0], "notes");
1656 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1657 // An absent allow list deserializes to empty (the server-side tolerance).
1658 let p: PeerAddParams =
1659 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1660 .unwrap();
1661 assert!(p.allow.is_empty());
1662 }
1663
1664 #[test]
1665 fn peer_rename_request_roundtrip() {
1666 // By user_id (renames all of a person's devices in one op).
1667 let r = Request::PeerRename(PeerRenameParams {
1668 user_id: Some("b64u:BOB".into()),
1669 nickname: None,
1670 to: "Bobby".into(),
1671 });
1672 let v = serde_json::to_value(&r).unwrap();
1673 assert_eq!(v["method"], "peer_rename");
1674 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1675 assert_eq!(v["params"]["to"], "Bobby");
1676 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1677 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1678 assert_eq!(
1679 method_of(
1680 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1681 ),
1682 Some("peer_rename")
1683 );
1684 }
1685
1686 #[test]
1687 fn status_result_roundtrips() {
1688 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1689 // older payload with no `roster` key still deserializes to None (serde default).
1690 let s = StatusResult {
1691 stack_version: "0.1.0".into(),
1692 services: vec![ServiceInfo {
1693 name: "notes".into(),
1694 allow: vec!["alice".into()],
1695 allow_display: vec![],
1696 backend: BackendKind::Run,
1697 ephemeral: false,
1698 }],
1699 peers: vec![PeerInfo {
1700 name: "alice".into(),
1701 services: vec!["notes".into()],
1702 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1703 user_id: Some("b64u:alicepk".into()),
1704 principal: None,
1705 }],
1706 roster: None,
1707 presence: vec![],
1708 self_user_id: Some("b64u:selfpk".into()),
1709 recent_pairings: vec![],
1710 reachability: vec![],
1711 self_nickname: String::new(),
1712 };
1713 let v = serde_json::to_value(&s).unwrap();
1714 assert_eq!(v["services"][0]["backend"], "run");
1715 // The additive identity fields ride the wire when present.
1716 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1717 assert_eq!(v["self_user_id"], "b64u:selfpk");
1718 assert!(
1719 v.get("roster").is_none(),
1720 "an absent roster must not appear on the wire: {v}"
1721 );
1722 assert!(
1723 v.get("presence").is_none(),
1724 "an empty presence must not appear on the wire: {v}"
1725 );
1726 assert!(
1727 v.get("recent_pairings").is_none(),
1728 "an empty recent_pairings must not appear on the wire: {v}"
1729 );
1730 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1731
1732 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1733 // deserializes — the identity fields default to None / a nickname-only peer.
1734 let old_shape = serde_json::json!({
1735 "stack_version": "0.1.0",
1736 "services": [],
1737 "peers": [{ "name": "bob", "services": [] }],
1738 });
1739 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1740 assert!(back.roster.is_none());
1741 assert!(back.presence.is_empty());
1742 assert!(back.self_user_id.is_none());
1743 assert!(back.peers[0].user_id.is_none());
1744 assert!(back.recent_pairings.is_empty());
1745
1746 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1747 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1748 let s = StatusResult {
1749 stack_version: "0.1.0".into(),
1750 services: vec![],
1751 peers: vec![],
1752 roster: Some(RosterStatus {
1753 org_id: "acme".into(),
1754 serial: 42,
1755 state: "approved".into(),
1756 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1757 }),
1758 presence: vec![
1759 PresencePeer {
1760 user_id: "alice".into(),
1761 device_label: "laptop".into(),
1762 role: "primary".into(),
1763 online: true,
1764 meta: String::new(),
1765 },
1766 PresencePeer {
1767 user_id: "alice".into(),
1768 device_label: "desktop".into(),
1769 role: "mirror".into(),
1770 online: false,
1771 meta: String::new(),
1772 },
1773 ],
1774 self_user_id: None,
1775 recent_pairings: vec![],
1776 reachability: vec![],
1777 self_nickname: String::new(),
1778 };
1779 let v = serde_json::to_value(&s).unwrap();
1780 assert_eq!(v["roster"]["org_id"], "acme");
1781 assert_eq!(v["roster"]["serial"], 42u64);
1782 assert_eq!(v["roster"]["state"], "approved");
1783 assert_eq!(
1784 v["roster"]["org_root_fingerprint"],
1785 "tango-fig-cabbage-anchor"
1786 );
1787 assert_eq!(v["presence"][0]["user_id"], "alice");
1788 assert_eq!(v["presence"][0]["device_label"], "laptop");
1789 assert_eq!(v["presence"][0]["role"], "primary");
1790 assert_eq!(v["presence"][0]["online"], true);
1791 assert_eq!(v["presence"][1]["online"], false);
1792 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1793 }
1794
1795 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1796 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1797 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1798 /// older daemon (no key at all) still deserializes to empty.
1799 #[test]
1800 fn recent_pairings_are_additive_on_status() {
1801 let s = StatusResult {
1802 stack_version: "0.1.0".into(),
1803 services: vec![],
1804 peers: vec![],
1805 roster: None,
1806 presence: vec![],
1807 self_user_id: None,
1808 recent_pairings: vec![RecentPairing {
1809 peer_nickname: "bob".into(),
1810 sas_code: "tango-fig-cabbage".into(),
1811 paired_at_epoch: 1_800_000_000,
1812 }],
1813 reachability: vec![],
1814 self_nickname: String::new(),
1815 };
1816 let v = serde_json::to_value(&s).unwrap();
1817 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1818 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1819 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1820 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1821
1822 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1823 // the `#[serde(default)]` fills it with an empty list.
1824 let old_shape = serde_json::json!({
1825 "stack_version": "0.1.0",
1826 "services": [],
1827 "peers": [],
1828 });
1829 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1830 assert!(back.recent_pairings.is_empty());
1831 }
1832
1833 #[test]
1834 fn blob_requests_and_results_roundtrip() {
1835 // BlobPublish → { method, params: { scope, path } }.
1836 let r = Request::BlobPublish(BlobPublishParams {
1837 scope: "docs".into(),
1838 path: "/tmp/a.bin".into(),
1839 });
1840 let v = serde_json::to_value(&r).unwrap();
1841 assert_eq!(v["method"], "blob_publish");
1842 assert_eq!(v["params"]["scope"], "docs");
1843 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1844 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1845
1846 // BlobGrant → { method, params: { scope, principal } }.
1847 // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
1848 // would otherwise ship undetected — the e2e test calls the provider directly and never
1849 // crosses JSON-RPC.
1850 let rev = Request::BlobRevoke(BlobRevokeParams {
1851 scope: "photos".into(),
1852 principals: vec!["alice".into()],
1853 });
1854 let v = serde_json::to_value(&rev).unwrap();
1855 assert_eq!(v["method"], "blob_revoke");
1856 assert_eq!(v["params"]["principals"][0], "alice");
1857 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
1858
1859 let unp = Request::BlobUnpublish(BlobUnpublishParams {
1860 scope: "photos".into(),
1861 hash: "abc123".into(),
1862 });
1863 let v = serde_json::to_value(&unp).unwrap();
1864 assert_eq!(v["method"], "blob_unpublish");
1865 assert_eq!(v["params"]["hash"], "abc123");
1866 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
1867
1868 let r = Request::BlobGrant(BlobGrantParams {
1869 scope: "docs".into(),
1870 principal: "alice".into(),
1871 });
1872 let v = serde_json::to_value(&r).unwrap();
1873 assert_eq!(v["method"], "blob_grant");
1874 assert_eq!(v["params"]["principal"], "alice");
1875 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1876
1877 // BlobList is parameterless (method_of resolves it).
1878 assert_eq!(
1879 method_of(&serde_json::json!({"method": "blob_list"})),
1880 Some("blob_list")
1881 );
1882
1883 // BlobFetch → { method, params: { ticket, dest_path } }.
1884 let r = Request::BlobFetch(BlobFetchParams {
1885 ticket: "blobAAA".into(),
1886 dest_path: "/tmp/out.bin".into(),
1887 });
1888 let v = serde_json::to_value(&r).unwrap();
1889 assert_eq!(v["method"], "blob_fetch");
1890 assert_eq!(v["params"]["ticket"], "blobAAA");
1891 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1892 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1893
1894 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1895 let res = BlobPublishResult {
1896 ticket: "blobAAA".into(),
1897 hash: "ab".repeat(32),
1898 };
1899 let v = serde_json::to_value(&res).unwrap();
1900 assert_eq!(v["ticket"], "blobAAA");
1901 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1902
1903 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1904 let res = BlobScopeList {
1905 scopes: vec![ScopeInfo {
1906 name: "docs".into(),
1907 hashes: vec!["ab".repeat(32)],
1908 grants: vec!["alice".into()],
1909 }],
1910 };
1911 let v = serde_json::to_value(&res).unwrap();
1912 assert_eq!(v["scopes"][0]["name"], "docs");
1913 assert_eq!(v["scopes"][0]["grants"][0], "alice");
1914 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1915
1916 // BlobFetchResult carries the verified hash + byte length.
1917 let res = BlobFetchResult {
1918 hash: "ab".repeat(32),
1919 bytes_len: 4194304,
1920 };
1921 let v = serde_json::to_value(&res).unwrap();
1922 assert_eq!(v["bytes_len"], 4194304u64);
1923 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1924 }
1925
1926 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1927 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1928 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1929 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1930 #[test]
1931 fn stream_frames_roundtrip_with_the_documented_tags() {
1932 let snap = StreamFrame::Snapshot {
1933 active_sessions: vec![ActiveSession {
1934 peer: "bob".into(),
1935 service: "notes".into(),
1936 opened_at: 1_751_760_000,
1937 }],
1938 reachability: vec![PeerReachability {
1939 name: "bob".into(),
1940 reachable: true,
1941 rtt_ms: Some(42),
1942 age_secs: Some(3),
1943 meta: String::new(),
1944 principal: None,
1945 path: Default::default(),
1946 }],
1947 };
1948 let v = serde_json::to_value(&snap).unwrap();
1949 assert_eq!(v["type"], "snapshot");
1950 assert_eq!(v["active_sessions"][0]["peer"], "bob");
1951 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1952 assert_eq!(v["reachability"][0]["name"], "bob");
1953 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1954
1955 let event = StreamFrame::Event {
1956 record: Box::new(AuditRecord::session_open(
1957 "2026-07-03T14:02:11.480Z".into(),
1958 Some("bob".into()),
1959 "notes".into(),
1960 )),
1961 };
1962 let v = serde_json::to_value(&event).unwrap();
1963 assert_eq!(v["type"], "event");
1964 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1965 assert_eq!(v["record"]["kind"], "session_open");
1966 assert_eq!(v["record"]["peer"], "bob");
1967 assert_eq!(v["record"]["service"], "notes");
1968 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1969
1970 let lagged = StreamFrame::Lagged { dropped: 12 };
1971 let v = serde_json::to_value(&lagged).unwrap();
1972 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1973 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1974 }
1975
1976 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1977 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1978 /// raw `Value` stream instead (`ControlClient::open_stream`).
1979 #[test]
1980 fn unknown_stream_frame_type_is_rejected() {
1981 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1982 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1983 }
1984
1985 #[test]
1986 fn audit_summary_request_and_result_roundtrip() {
1987 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1988 // tolerates omitted/null params; the server dispatches on the method string (method_of).
1989 let r = Request::AuditSummary;
1990 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1991 assert_eq!(
1992 method_of(&serde_json::json!({"method": "audit_summary"})),
1993 Some("audit_summary")
1994 );
1995
1996 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1997 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1998 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1999 let res = AuditSummaryResult {
2000 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
2001 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
2002 total_sessions: 4,
2003 };
2004 let v = serde_json::to_value(&res).unwrap();
2005 assert_eq!(v["per_peer"][1][0], "bob");
2006 assert_eq!(v["per_peer"][1][1], 2u64);
2007 assert_eq!(v["per_service"][1][0], "notes");
2008 assert_eq!(v["total_sessions"], 4u64);
2009 assert_eq!(
2010 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
2011 res
2012 );
2013
2014 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
2015 // deserializes — the `#[serde(default)]` fills it with 0.
2016 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
2017 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
2018 assert_eq!(back.total_sessions, 0);
2019 assert!(back.per_peer.is_empty());
2020 }
2021}