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::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
447#[serde(deny_unknown_fields)]
448pub struct BlobFetchParams {
449 pub ticket: String,
450 pub dest_path: String,
451}
452
453/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
454/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
455///
456/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
457/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
458/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
459/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
460/// identical to inline variant bodies.
461///
462/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
463/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
464/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
465/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
466/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468#[serde(tag = "method", content = "params", rename_all = "snake_case")]
469pub enum Request {
470 /// Register/update a `[services.*]` entry idempotently.
471 RegisterService(RegisterServiceParams),
472 Status,
473 /// Mint a one-time pairing invite granting `services`. The daemon
474 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
475 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
476 /// `method` string generically; the tag comes from `rename_all`.
477 Invite(InviteParams),
478 /// Redeem a pairing invite. The daemon dials the inviter named by
479 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
480 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
481 /// (snake_case); `method_of` reads the `method` string generically.
482 ///
483 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
484 Pair(PairParams),
485 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
486 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
487 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
488 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
489 /// NOT severed here: existing sessions run to completion; the peer only loses the
490 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
491 /// `method_of` reads the `method` string generically (no per-variant arm).
492 ///
493 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
494 PeerRemove(PeerRemoveParams),
495 /// Rename a contact's nickname (nickname) authoritatively. Renames the
496 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
497 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
498 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
499 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
500 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
501 /// host-privileged like the other pair ops.
502 PeerRename(PeerRenameParams),
503 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
504 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
505 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
506 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
507 /// vocabulary — do not build on it. Tag `"peer_add"`.
508 PeerAdd(PeerAddParams),
509 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
510 /// Distinct from the proxy's job: this returns a session the client streams.
511 /// Named `open_session` rather than `connect` to avoid colliding
512 /// with the `connect` porcelain.
513 OpenSession(OpenSessionParams),
514 /// Install a signed roster from a local file (the manual `internal roster install` path).
515 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
516 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
517 /// pins the org root on FIRST install (`b64u:`); omit it
518 /// once pinned (config carries it). Tag `"roster_install"`.
519 RosterInstall(RosterInstallParams),
520 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
521 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
522 /// `user_key` is a LOCAL path
523 /// (the key never crosses the API). Tag `"org_join"`.
524 OrgJoin(OrgJoinParams),
525 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
526 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
527 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
528 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
529 /// `"set_roster_url"`.
530 SetRosterUrl(SetRosterUrlParams),
531 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
532 /// daemon's own serialized config-write path (no lost-update window against a
533 /// concurrent grant/registration) and update the in-memory name future invites
534 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
535 SetNickname(SetNicknameParams),
536 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
537 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
538 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
539 /// on restart; the embedder re-sets on startup).
540 SetAppMetadata(SetAppMetadataParams),
541 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
542 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
543 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
544 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
545 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
546 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
547 /// [`SetRelaysResult`]. Tag `"set_relays"`.
548 SetRelays(SetRelaysParams),
549 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
550 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
551 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
552 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
553 /// hot-reloads. Idempotent. Ack result.
554 UnregisterService(UnregisterServiceParams),
555 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
556 /// and returns the service names whose allow admits the caller's principal. Answers
557 /// [`PeerServicesResult`].
558 PeerServices(PeerServicesParams),
559 ServiceAllowGrant(ServiceAllowParams),
560 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
561 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
562 /// Idempotent. Ack result.
563 ServiceAllowRevoke(ServiceAllowParams),
564 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
565 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
566 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
567 /// Tag `"blob_publish"`.
568 BlobPublish(BlobPublishParams),
569 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
570 /// nickname (the shared `principal_set` expansion). Tag
571 /// `"blob_grant"`.
572 BlobGrant(BlobGrantParams),
573 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
574 BlobList,
575 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
576 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
577 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
578 BlobFetch(BlobFetchParams),
579 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
580 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
581 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
582 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
583 /// `method_of` reads the `method` string generically (no per-variant arm).
584 AuditSummary,
585 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
586 /// connection STOPS being request/response after this call and becomes a one-way push stream
587 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
588 Subscribe,
589}
590
591/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
592/// computed porcelain-side from the invite's org_root_pk). Additive-only.
593#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
594pub struct OrgJoinResult {
595 pub org_id: String,
596}
597
598/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
599/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
600/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
601///
602/// Additive-only: any future field MUST land as
603/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
604#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
605pub struct RosterInstallResult {
606 pub org_id: String,
607 pub serial: u64,
608 /// How many live sessions were severed, for the porcelain's confirmation line.
609 #[serde(default)]
610 pub severed: u32,
611}
612
613/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
614/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
615/// carve-out as the pairing invite line). Additive-only.
616#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
617pub struct BlobPublishResult {
618 pub ticket: String,
619 pub hash: String, // bare blake3 hex
620}
621
622/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
623/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
624#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
625pub struct ScopeInfo {
626 pub name: String,
627 pub hashes: Vec<String>,
628 pub grants: Vec<String>,
629}
630
631/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
632#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
633pub struct BlobScopeList {
634 pub scopes: Vec<ScopeInfo>,
635}
636
637/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
638/// Additive-only.
639#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
640pub struct BlobFetchResult {
641 pub hash: String,
642 pub bytes_len: u64,
643}
644
645/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
646/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
647/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
648/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
649/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
650/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
651///
652/// Additive-only: any future field MUST land as
653/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
655pub struct AuditSummaryResult {
656 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
657 /// peer to attribute) but IS in `total_sessions`.
658 pub per_peer: Vec<(String, u64)>,
659 /// Sessions opened per registered service name.
660 pub per_service: Vec<(String, u64)>,
661 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
662 #[serde(default)]
663 pub total_sessions: u64,
664}
665
666/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
667/// (the ONE pairing artifact deliberately carved out of the
668/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
669/// absolute expiry in epoch seconds (≤ now + 24h).
670///
671/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
672/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
673/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
674/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
675/// ceremony" note in `docs/local-protocol.md` (#35).
676///
677/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
678/// so older payloads still deserialize.
679#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
680pub struct InviteResult {
681 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
682 pub invite_line: String,
683 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
684 pub expires_at_epoch: u64,
685}
686
687/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
688/// redeemer's local name for the new peer) plus the display-only short authentication
689/// code (SAS) — a few words the human reads aloud to a second channel to
690/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
691/// artifact (like the invite line), NOT a transport-vocabulary leak.
692///
693/// Additive-only: any future field MUST land as
694/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
695#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
696pub struct PairResult {
697 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
698 pub peer_nickname: String,
699 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
700 /// sides for the out-of-band human check. Never sent on the wire, never checked
701 /// programmatically.
702 pub sas_code: String,
703 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
704 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
705 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
706 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
707 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
708 #[serde(default, skip_serializing_if = "Vec::is_empty")]
709 pub services: Vec<String>,
710 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
711 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
712 #[serde(default, skip_serializing_if = "Option::is_none")]
713 pub app_label: Option<String>,
714 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
715 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
716 /// can align with its own — and the same value it may later pass to `open_session` to dial
717 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
718 /// binding (a legacy/keyless peer). Additive.
719 #[serde(default, skip_serializing_if = "Option::is_none")]
720 pub peer_user_id: Option<String>,
721}
722
723/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
724/// top of the base record schema: it removes no field and makes the JSONL self-describing so
725/// a consumer can filter by class without guessing from which optional fields are present.
726#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
727#[serde(rename_all = "snake_case")]
728pub enum AuditKind {
729 /// A mesh session opened (a backend was selected for an authenticated peer).
730 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
731 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
732 SessionOpen,
733 /// A mesh session closed (the backend returned / the session tore down).
734 SessionClose,
735 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
736 Request,
737 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
738 BlobFetch,
739 /// A trust mutation (pair, unpair, roster install/swap, revoke).
740 Trust,
741}
742
743/// One audit record — the union of the event classes, and the `record` payload of a
744/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
745/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
746/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
747/// `bytes_out`).
748///
749/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
750/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
751/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
752#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
753pub struct AuditRecord {
754 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
755 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
756 pub ts: String,
757 pub kind: AuditKind,
758 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
759 /// local-only events with no remote peer (a manual roster install).
760 #[serde(skip_serializing_if = "Option::is_none")]
761 pub peer: Option<String>,
762 #[serde(skip_serializing_if = "Option::is_none")]
763 pub service: Option<String>,
764 #[serde(skip_serializing_if = "Option::is_none")]
765 pub method: Option<String>,
766 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
767 #[serde(skip_serializing_if = "Option::is_none")]
768 pub tool: Option<String>,
769 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
770 #[serde(skip_serializing_if = "Option::is_none")]
771 pub args_hash: Option<String>,
772 /// Byte COUNT of the response sent back to the peer — a count, never the content.
773 #[serde(skip_serializing_if = "Option::is_none")]
774 pub bytes_out: Option<u64>,
775 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
776 #[serde(skip_serializing_if = "Option::is_none")]
777 pub status: Option<String>,
778 #[serde(skip_serializing_if = "Option::is_none")]
779 pub latency_ms: Option<u64>,
780 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
781 #[serde(skip_serializing_if = "Option::is_none")]
782 pub event: Option<String>,
783 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
784 /// nickname or `org/serial` (`Trust`).
785 #[serde(skip_serializing_if = "Option::is_none")]
786 pub target: Option<String>,
787}
788
789impl AuditRecord {
790 fn base(ts: String, kind: AuditKind) -> Self {
791 Self {
792 ts,
793 kind,
794 peer: None,
795 service: None,
796 method: None,
797 tool: None,
798 args_hash: None,
799 bytes_out: None,
800 status: None,
801 latency_ms: None,
802 event: None,
803 target: None,
804 }
805 }
806
807 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
808 let mut r = Self::base(ts, AuditKind::SessionOpen);
809 r.peer = peer;
810 r.service = Some(service);
811 r
812 }
813
814 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
815 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
816 /// reaches no backend and so is never audited by the far side's session guard — without a
817 /// dedicated constructor. DRY: reuses the existing optional `status` field.
818 pub fn with_status(mut self, status: &str) -> Self {
819 self.status = Some(status.into());
820 self
821 }
822
823 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
824 let mut r = Self::base(ts, AuditKind::SessionClose);
825 r.peer = peer;
826 r.service = Some(service);
827 r
828 }
829
830 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
831 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
832 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
833 #[allow(clippy::too_many_arguments)]
834 pub fn proxied_request(
835 ts: String,
836 peer: Option<String>,
837 service: String,
838 method: String,
839 tool: Option<String>,
840 args_hash: String,
841 bytes_out: u64,
842 status: String,
843 latency_ms: u64,
844 ) -> Self {
845 let mut r = Self::base(ts, AuditKind::Request);
846 r.peer = peer;
847 r.service = Some(service);
848 r.method = Some(method);
849 r.tool = tool;
850 r.args_hash = Some(args_hash);
851 r.bytes_out = Some(bytes_out);
852 r.status = Some(status);
853 r.latency_ms = Some(latency_ms);
854 r
855 }
856
857 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
858 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
859 pub fn proxied_notification(
860 ts: String,
861 peer: Option<String>,
862 service: String,
863 method: String,
864 tool: Option<String>,
865 args_hash: String,
866 ) -> Self {
867 let mut r = Self::base(ts, AuditKind::Request);
868 r.peer = peer;
869 r.service = Some(service);
870 r.method = Some(method);
871 r.tool = tool;
872 r.args_hash = Some(args_hash);
873 r
874 }
875
876 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
877 let mut r = Self::base(ts, AuditKind::BlobFetch);
878 r.peer = peer;
879 r.target = Some(hash);
880 r.status = Some(status);
881 r
882 }
883
884 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
885 let mut r = Self::base(ts, AuditKind::Trust);
886 r.event = Some(event);
887 r.target = target;
888 r
889 }
890}
891
892/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
893/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
894#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
895pub struct ActiveSession {
896 pub peer: String,
897 pub service: String,
898 pub opened_at: i64,
899}
900
901/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
902/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
903/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
904/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
905/// them (see `docs/local-protocol.md` "Live event stream").
906/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
907/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
908/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
909/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
910#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
911#[serde(tag = "type", rename_all = "snake_case")]
912#[non_exhaustive]
913pub enum StreamFrame {
914 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
915 /// reachability) so a fresh subscriber renders immediately without replaying history.
916 Snapshot {
917 active_sessions: Vec<ActiveSession>,
918 reachability: Vec<PeerReachability>,
919 },
920 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
921 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
922 /// `Box`, so the wire shape is the record's fields verbatim.
923 Event { record: Box<AuditRecord> },
924 /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
925 /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
926 /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
927 /// it returns, rather than on the next poll tick.
928 ///
929 /// Emitted on a CHANGE of `reachable` only. A refreshed probe with the same verdict emits
930 /// nothing, so a peer that stays up does not produce a frame per TTL refresh; `rtt_ms`/`meta`/
931 /// `services` drift is advisory detail and is not a transition. `age_secs` is `0` — the probe
932 /// just completed.
933 Reachability { peer: PeerReachability },
934 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
935 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
936 Lagged { dropped: u64 },
937}
938
939/// Extract the `method` tag from a raw request value without deserializing the whole
940/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
941/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
942/// methods (adjacent tagging rejects `params:{}` on unit variants).
943pub fn method_of(v: &serde_json::Value) -> Option<&str> {
944 v.get("method").and_then(serde_json::Value::as_str)
945}
946
947/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
948/// Config→BackendSpec is a hand-written match, not a serde passthrough.
949#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
950#[serde(rename_all = "snake_case")]
951pub enum BackendSpec {
952 Run {
953 cmd: Vec<String>,
954 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
955 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
956 /// these (identity is not spoofable by a service definition). Default empty.
957 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
958 env: BTreeMap<String, String>,
959 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
960 #[serde(default, skip_serializing_if = "Option::is_none")]
961 cwd: Option<String>,
962 },
963 Socket {
964 path: String,
965 },
966}
967
968/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
969/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
970/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
971/// `{}` (success) for an unknown name, which silently included every ephemeral service.
972pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
973
974pub const API_NAME: &str = "mcpmesh-local/1";
975/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
976///
977/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
978/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
979/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
980/// new methods, or a strictness change like params validation — bumped in the same change that
981/// makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
982/// older than a minor it requires. It never resets except on a MAJOR bump.
983pub const API_VERSION: &str = "1.13";
984/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
985/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
986/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
987/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
988/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
989/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
990/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
991/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
992/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
993/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
994/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
995/// observable contract did: a revoked principal's next session is refused even on a connection it
996/// already holds, and its live connections are severed. Previously both waited for the peer to
997/// disconnect on its own, which is unbounded (#54). A consumer can guard on
998/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
999/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
1000/// about an unknown service name — a name in neither the config nor the ephemeral registry now
1001/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
1002/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
1003/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64).
1004pub const API_MINOR: u32 = 13;
1005
1006#[cfg(test)]
1007mod tests {
1008 use super::*;
1009
1010 /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
1011 /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
1012 /// privacy guarantee that daemon never made.
1013 #[test]
1014 fn peer_path_tags_and_defaults_to_unknown() {
1015 let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
1016 assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
1017 assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
1018 let relay = tagged(PeerPath::Relay {
1019 url: Some("https://relay.example/".into()),
1020 });
1021 assert_eq!(relay["kind"], "relay");
1022 assert_eq!(relay["url"], "https://relay.example/");
1023 // A relay whose URL we do not know still tags as relay, with the key elided.
1024 let bare = tagged(PeerPath::Relay { url: None });
1025 assert_eq!(bare["kind"], "relay");
1026 assert!(bare.get("url").is_none(), "elided, not null: {bare}");
1027
1028 // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
1029 // row. Without `#[serde(other)]` an unknown `kind` errors out of
1030 // `PeerReachability` entirely, so one new variant would break every `status` read an
1031 // older pinned client does.
1032 let future: PeerPath =
1033 serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
1034 assert_eq!(future, PeerPath::Unknown);
1035 let row: PeerReachability = serde_json::from_value(serde_json::json!({
1036 "name": "bob", "reachable": true, "path": {"kind": "quantum"}
1037 }))
1038 .expect("an unknown path kind must not fail the whole row");
1039 assert_eq!(row.path, PeerPath::Unknown);
1040 assert!(row.reachable, "the rest of the row survives");
1041
1042 // A pre-#64 row: no `path` key.
1043 let old = serde_json::json!({"name": "bob", "reachable": true});
1044 let parsed: PeerReachability = serde_json::from_value(old).unwrap();
1045 assert_eq!(
1046 parsed.path,
1047 PeerPath::Unknown,
1048 "an older daemon's row must never imply a direct path"
1049 );
1050 }
1051
1052 /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
1053 /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
1054 /// consumer projects both through one code path.
1055 #[test]
1056 fn reachability_frame_tags_and_round_trips() {
1057 let frame = StreamFrame::Reachability {
1058 peer: PeerReachability {
1059 name: "bob".into(),
1060 reachable: true,
1061 rtt_ms: Some(12),
1062 age_secs: Some(0),
1063 meta: String::new(),
1064 principal: Some("eid:beef".into()),
1065 path: Default::default(),
1066 },
1067 };
1068 let v = serde_json::to_value(&frame).unwrap();
1069 assert_eq!(v["type"], "reachability");
1070 assert_eq!(v["peer"]["name"], "bob");
1071 assert_eq!(v["peer"]["reachable"], true);
1072 assert_eq!(
1073 v["peer"]["age_secs"], 0,
1074 "a transition frame is fresh by construction: {v}"
1075 );
1076 let back: StreamFrame = serde_json::from_value(v).unwrap();
1077 assert_eq!(back, frame);
1078 }
1079
1080 #[test]
1081 fn peer_reachability_serde_is_additive() {
1082 let r = PeerReachability {
1083 name: "bob".into(),
1084 reachable: true,
1085 rtt_ms: Some(42),
1086 age_secs: Some(3),
1087 meta: String::new(),
1088 principal: None,
1089 path: Default::default(),
1090 };
1091 let v = serde_json::to_value(&r).unwrap();
1092 assert_eq!(v["name"], "bob");
1093 assert_eq!(v["reachable"], true);
1094 assert_eq!(v["rtt_ms"], 42);
1095 assert_eq!(v["age_secs"], 3);
1096 // Never-probed peer: optionals elided, not null.
1097 let unknown = PeerReachability {
1098 name: "carol".into(),
1099 reachable: false,
1100 rtt_ms: None,
1101 age_secs: None,
1102 meta: String::new(),
1103 principal: None,
1104 path: Default::default(),
1105 };
1106 let uv = serde_json::to_value(&unknown).unwrap();
1107 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
1108 // An older StatusResult (no reachability field) still deserializes.
1109 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
1110 let s: StatusResult = serde_json::from_value(old).unwrap();
1111 assert!(s.reachability.is_empty());
1112 }
1113
1114 #[test]
1115 fn subscribe_method_tag_resolves() {
1116 let req = serde_json::to_value(Request::Subscribe).unwrap();
1117 assert_eq!(method_of(&req), Some("subscribe"));
1118 }
1119
1120 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
1121
1122 #[test]
1123 fn invite_params_reject_singular_service_typo() {
1124 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
1125 // InviteParams { services: [] } and mint a grants-nothing invite that looked
1126 // successful. With deny_unknown_fields the typo is a loud parse error instead.
1127 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
1128 assert!(
1129 err.is_err(),
1130 "an unknown `service` key must be rejected, not silently ignored"
1131 );
1132 // The correct plural shape still parses.
1133 let ok: InviteParams =
1134 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
1135 assert_eq!(ok.services, vec!["kb".to_string()]);
1136 }
1137
1138 #[test]
1139 fn open_session_params_reject_unknown_field() {
1140 let err = serde_json::from_value::<OpenSessionParams>(
1141 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
1142 );
1143 assert!(err.is_err(), "unknown params keys must be rejected");
1144 }
1145
1146 #[test]
1147 fn set_app_metadata_request_carries_the_method_tag() {
1148 let r = Request::SetAppMetadata(SetAppMetadataParams {
1149 metadata: "v=1.2.3".into(),
1150 });
1151 let v = serde_json::to_value(&r).unwrap();
1152 assert_eq!(v["method"], "set_app_metadata");
1153 assert_eq!(v["params"]["metadata"], "v=1.2.3");
1154 assert_eq!(method_of(&v), Some("set_app_metadata"));
1155 }
1156
1157 #[test]
1158 fn set_app_metadata_params_reject_unknown_field() {
1159 let err = serde_json::from_value::<SetAppMetadataParams>(
1160 serde_json::json!({"metadata": "x", "nonsense": 1}),
1161 );
1162 assert!(err.is_err(), "unknown params keys must be rejected");
1163 }
1164
1165 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1166 /// empty meta does not serialize.
1167 #[test]
1168 fn peer_info_principal_is_additive() {
1169 // An older payload (no principal) still deserializes; empty does not serialize.
1170 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1171 let p: PeerInfo = serde_json::from_value(old).unwrap();
1172 assert_eq!(p.principal, None);
1173 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1174 // A bound peer carries BOTH the person user_id AND the device principal (#41).
1175 let full = PeerInfo {
1176 name: "bob".into(),
1177 services: vec!["notes".into()],
1178 user_id: Some("b64u:BOB".into()),
1179 principal: Some("eid:0707".into()),
1180 };
1181 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1182 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1183 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1184 }
1185
1186 #[test]
1187 fn peer_reachability_principal_is_additive() {
1188 // Older payload (no principal) still deserializes; empty does not serialize; a set
1189 // value round-trips alongside the #40 meta so an embedder joins on the principal.
1190 let old = serde_json::json!({"name": "bob", "reachable": true});
1191 let r: PeerReachability = serde_json::from_value(old).unwrap();
1192 assert_eq!(r.principal, None);
1193 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1194 let full = PeerReachability {
1195 name: "bob".into(),
1196 reachable: true,
1197 rtt_ms: Some(12),
1198 age_secs: Some(3),
1199 meta: "v=1.2.3".into(),
1200 principal: Some("eid:0707".into()),
1201 path: Default::default(),
1202 };
1203 let back: PeerReachability =
1204 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1205 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1206 assert_eq!(back.meta, "v=1.2.3");
1207 }
1208
1209 #[test]
1210 fn peer_reachability_meta_is_additive() {
1211 // An older payload (no meta) still deserializes; an empty meta does not serialize.
1212 let old = serde_json::json!({"name": "bob", "reachable": true});
1213 let r: PeerReachability = serde_json::from_value(old).unwrap();
1214 assert_eq!(r.meta, "");
1215 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1216 // A set value round-trips.
1217 let with = PeerReachability {
1218 name: "bob".into(),
1219 reachable: true,
1220 rtt_ms: Some(12),
1221 age_secs: Some(3),
1222 meta: "v=1.2.3".into(),
1223 principal: None,
1224 path: Default::default(),
1225 };
1226 let back: PeerReachability =
1227 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1228 assert_eq!(back.meta, "v=1.2.3");
1229 }
1230
1231 #[test]
1232 fn presence_peer_meta_is_additive() {
1233 let old = serde_json::json!({
1234 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1235 });
1236 let p: PresencePeer = serde_json::from_value(old).unwrap();
1237 assert_eq!(p.meta, "");
1238 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1239 }
1240
1241 #[test]
1242 fn set_nickname_request_carries_the_method_tag() {
1243 let r = Request::SetNickname(SetNicknameParams {
1244 nickname: "workbench".into(),
1245 });
1246 let v = serde_json::to_value(&r).unwrap();
1247 assert_eq!(v["method"], "set_nickname");
1248 assert_eq!(v["params"]["nickname"], "workbench");
1249 assert_eq!(method_of(&v), Some("set_nickname"));
1250 }
1251
1252 #[test]
1253 fn set_nickname_params_reject_unknown_field() {
1254 let err = serde_json::from_value::<SetNicknameParams>(
1255 serde_json::json!({"nickname": "x", "nonsense": 1}),
1256 );
1257 assert!(err.is_err(), "unknown params keys must be rejected");
1258 }
1259
1260 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1261 /// the additive-only contract — and an empty name must not serialize at all.
1262 #[test]
1263 fn status_self_nickname_is_additive() {
1264 let old = serde_json::json!({
1265 "stack_version": "0.7.0", "services": [], "peers": []
1266 });
1267 let s: StatusResult = serde_json::from_value(old).unwrap();
1268 assert_eq!(s.self_nickname, "");
1269 let v = serde_json::to_value(&s).unwrap();
1270 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1271 }
1272
1273 #[test]
1274 fn api_minor_is_present_and_monotonic_from_hello() {
1275 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1276 // crate/stack version, additive on the Hello frame.
1277 let h = Hello {
1278 api: API_NAME.into(),
1279 api_version: API_VERSION.into(),
1280 api_minor: API_MINOR,
1281 stack_version: "9.9.9".into(),
1282 };
1283 let v = serde_json::to_value(&h).unwrap();
1284 assert_eq!(v["api_minor"], API_MINOR);
1285 // An OLD Hello without api_minor still deserializes (additive contract).
1286 let old = serde_json::json!({
1287 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1288 });
1289 let back: Hello = serde_json::from_value(old).unwrap();
1290 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1291 }
1292
1293 #[test]
1294 fn hello_result_roundtrips() {
1295 let h = Hello {
1296 api: "mcpmesh-local/1".into(),
1297 api_version: "1.0".into(),
1298 api_minor: 0,
1299 stack_version: "0.1.0".into(),
1300 };
1301 let v = serde_json::to_value(&h).unwrap();
1302 assert_eq!(v["api"], "mcpmesh-local/1");
1303 let back: Hello = serde_json::from_value(v).unwrap();
1304 assert_eq!(back, h);
1305 }
1306
1307 #[test]
1308 fn request_tagged_by_method() {
1309 let r = Request::Status;
1310 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1311 let r = Request::OpenSession(OpenSessionParams {
1312 peer: "alice".into(),
1313 service: "notes".into(),
1314 });
1315 let v = serde_json::to_value(&r).unwrap();
1316 assert_eq!(v["method"], "open_session");
1317 assert_eq!(v["params"]["peer"], "alice");
1318 }
1319
1320 #[test]
1321 fn parameterless_method_tolerates_params_forms() {
1322 // Omitted and null params deserialize straight into the unit variant.
1323 let omitted: Request =
1324 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1325 assert_eq!(omitted, Request::Status);
1326 let null: Request =
1327 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1328 .unwrap();
1329 assert_eq!(null, Request::Status);
1330
1331 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1332 // the server MUST dispatch on the method string rather than deserialize the whole
1333 // message into `Request`. This is the pattern the daemon's dispatcher uses.
1334 let empty = serde_json::json!({"method": "status", "params": {}});
1335 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1336 match method_of(&empty) {
1337 Some("status") => {} // dispatcher resolves Status via the method string
1338 other => panic!("method_of failed to resolve status: {other:?}"),
1339 }
1340 }
1341
1342 #[test]
1343 fn backend_spec_roundtrips() {
1344 let run = BackendSpec::Run {
1345 cmd: vec!["notes-mcp".into(), "--stdio".into()],
1346 env: Default::default(),
1347 cwd: None,
1348 };
1349 let v = serde_json::to_value(&run).unwrap();
1350 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1351 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1352
1353 let sock = BackendSpec::Socket {
1354 path: "/run/notes.sock".into(),
1355 };
1356 let v = serde_json::to_value(&sock).unwrap();
1357 assert_eq!(v["socket"]["path"], "/run/notes.sock");
1358 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1359 }
1360
1361 #[test]
1362 fn register_service_wire_shape() {
1363 let r = Request::RegisterService(RegisterServiceParams {
1364 name: "notes".into(),
1365 backend: BackendSpec::Run {
1366 cmd: vec!["notes-mcp".into()],
1367 env: Default::default(),
1368 cwd: None,
1369 },
1370 allow: vec!["alice".into()],
1371 ephemeral: false,
1372 });
1373 let v = serde_json::to_value(&r).unwrap();
1374 assert_eq!(
1375 v,
1376 serde_json::json!({
1377 "method": "register_service",
1378 "params": {
1379 "name": "notes",
1380 "backend": {"run": {"cmd": ["notes-mcp"]}},
1381 "allow": ["alice"],
1382 }
1383 })
1384 );
1385 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1386 }
1387
1388 #[test]
1389 fn invite_request_and_result_roundtrip() {
1390 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1391 let r = Request::Invite(InviteParams {
1392 services: vec!["notes".into(), "kb".into()],
1393 app_label: None,
1394 });
1395 let v = serde_json::to_value(&r).unwrap();
1396 assert_eq!(v["method"], "invite");
1397 assert_eq!(v["params"]["services"][0], "notes");
1398 assert_eq!(v["params"]["services"][1], "kb");
1399 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1400 // method_of resolves the tag generically (no per-variant arm).
1401 assert_eq!(
1402 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1403 Some("invite")
1404 );
1405
1406 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1407 let res = InviteResult {
1408 invite_line: "mcpmesh-invite:ABCDEF".into(),
1409 expires_at_epoch: 1_800_000_000,
1410 };
1411 let v = serde_json::to_value(&res).unwrap();
1412 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1413 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1414 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1415 }
1416
1417 #[test]
1418 fn pair_request_and_result_roundtrip() {
1419 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1420 let r = Request::Pair(PairParams {
1421 invite_line: "mcpmesh-invite:ABCDEF".into(),
1422 });
1423 let v = serde_json::to_value(&r).unwrap();
1424 assert_eq!(v["method"], "pair");
1425 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1426 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1427 // method_of resolves the tag generically (no per-variant arm).
1428 assert_eq!(
1429 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1430 Some("pair")
1431 );
1432
1433 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1434 // the granted services (the porcelain renders each as `<peer>/<service>`).
1435 let res = PairResult {
1436 peer_nickname: "alice".into(),
1437 sas_code: "tango-fig-cabbage".into(),
1438 services: vec!["notes".into(), "kb".into()],
1439 app_label: None,
1440 peer_user_id: None,
1441 };
1442 let v = serde_json::to_value(&res).unwrap();
1443 assert_eq!(v["peer_nickname"], "alice");
1444 assert_eq!(v["sas_code"], "tango-fig-cabbage");
1445 assert_eq!(v["services"][0], "notes");
1446 assert_eq!(v["services"][1], "kb");
1447 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1448
1449 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1450 // deserializes — the `#[serde(default)]` fills it with an empty list.
1451 let old_shape = serde_json::json!({
1452 "peer_nickname": "alice",
1453 "sas_code": "tango-fig-cabbage",
1454 });
1455 let back: PairResult = serde_json::from_value(old_shape).unwrap();
1456 assert_eq!(back.peer_nickname, "alice");
1457 assert!(back.services.is_empty());
1458 }
1459
1460 #[test]
1461 fn roster_install_request_and_result_roundtrip() {
1462 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1463 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1464 let r = Request::RosterInstall(RosterInstallParams {
1465 path: "/tmp/roster.json".into(),
1466 org_root_pk: Some("b64u:AAAA".into()),
1467 });
1468 let v = serde_json::to_value(&r).unwrap();
1469 assert_eq!(v["method"], "roster_install");
1470 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1471 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1472 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1473 // method_of resolves the tag generically (no per-variant arm).
1474 assert_eq!(
1475 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1476 Some("roster_install")
1477 );
1478
1479 // When the pk is omitted (a subsequent install using the pinned value), it is
1480 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1481 let omit = Request::RosterInstall(RosterInstallParams {
1482 path: "/tmp/roster.json".into(),
1483 org_root_pk: None,
1484 });
1485 let v = serde_json::to_value(&omit).unwrap();
1486 assert!(
1487 v["params"].get("org_root_pk").is_none(),
1488 "an omitted org_root_pk must not appear on the wire: {v}"
1489 );
1490 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1491
1492 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1493 let res = RosterInstallResult {
1494 org_id: "acme".into(),
1495 serial: 42,
1496 severed: 1,
1497 };
1498 let v = serde_json::to_value(&res).unwrap();
1499 assert_eq!(v["org_id"], "acme");
1500 assert_eq!(v["serial"], 42u64);
1501 assert_eq!(v["severed"], 1u32);
1502 assert_eq!(
1503 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1504 res
1505 );
1506
1507 // Additive-only: a result minted by an older daemon (no `severed` key) still
1508 // deserializes — the `#[serde(default)]` fills it with 0.
1509 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1510 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1511 assert_eq!(back.serial, 7);
1512 assert_eq!(back.severed, 0);
1513 }
1514
1515 #[test]
1516 fn org_join_request_and_result_roundtrip() {
1517 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1518 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1519 let r = Request::OrgJoin(OrgJoinParams {
1520 org_id: "acme".into(),
1521 org_root_pk: "b64u:AAAA".into(),
1522 user_id: "alice".into(),
1523 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1524 });
1525 let v = serde_json::to_value(&r).unwrap();
1526 assert_eq!(v["method"], "org_join");
1527 assert_eq!(v["params"]["org_id"], "acme");
1528 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1529 assert_eq!(v["params"]["user_id"], "alice");
1530 assert_eq!(
1531 v["params"]["user_key"],
1532 "/home/alice/.config/mcpmesh/user.key"
1533 );
1534 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1535 // method_of resolves the tag generically (no per-variant arm).
1536 assert_eq!(
1537 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1538 Some("org_join")
1539 );
1540
1541 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1542 let res = OrgJoinResult {
1543 org_id: "acme".into(),
1544 };
1545 let v = serde_json::to_value(&res).unwrap();
1546 assert_eq!(v["org_id"], "acme");
1547 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1548 }
1549
1550 #[test]
1551 fn set_roster_url_request_roundtrip() {
1552 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1553 let r = Request::SetRosterUrl(SetRosterUrlParams {
1554 url: "https://intranet.acme.com/roster.json".into(),
1555 });
1556 let v = serde_json::to_value(&r).unwrap();
1557 assert_eq!(v["method"], "set_roster_url");
1558 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1559 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1560 assert_eq!(
1561 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1562 Some("set_roster_url")
1563 );
1564 }
1565
1566 #[test]
1567 fn peer_remove_request_roundtrip() {
1568 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1569 let r = Request::PeerRemove(PeerRemoveParams {
1570 nickname: "bob".into(),
1571 });
1572 let v = serde_json::to_value(&r).unwrap();
1573 assert_eq!(v["method"], "peer_remove");
1574 assert_eq!(v["params"]["nickname"], "bob");
1575 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1576 // method_of resolves the tag generically (no per-variant arm).
1577 assert_eq!(
1578 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1579 Some("peer_remove")
1580 );
1581 }
1582
1583 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1584 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1585 /// defaulting to empty when absent.
1586 #[test]
1587 fn peer_add_request_roundtrip() {
1588 let r = Request::PeerAdd(PeerAddParams {
1589 nickname: "bob".into(),
1590 endpoint_id: "96246d3f".into(),
1591 allow: vec!["notes".into()],
1592 });
1593 let v = serde_json::to_value(&r).unwrap();
1594 assert_eq!(v["method"], "peer_add");
1595 assert_eq!(v["params"]["nickname"], "bob");
1596 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1597 assert_eq!(v["params"]["allow"][0], "notes");
1598 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1599 // An absent allow list deserializes to empty (the server-side tolerance).
1600 let p: PeerAddParams =
1601 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1602 .unwrap();
1603 assert!(p.allow.is_empty());
1604 }
1605
1606 #[test]
1607 fn peer_rename_request_roundtrip() {
1608 // By user_id (renames all of a person's devices in one op).
1609 let r = Request::PeerRename(PeerRenameParams {
1610 user_id: Some("b64u:BOB".into()),
1611 nickname: None,
1612 to: "Bobby".into(),
1613 });
1614 let v = serde_json::to_value(&r).unwrap();
1615 assert_eq!(v["method"], "peer_rename");
1616 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1617 assert_eq!(v["params"]["to"], "Bobby");
1618 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1619 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1620 assert_eq!(
1621 method_of(
1622 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1623 ),
1624 Some("peer_rename")
1625 );
1626 }
1627
1628 #[test]
1629 fn status_result_roundtrips() {
1630 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1631 // older payload with no `roster` key still deserializes to None (serde default).
1632 let s = StatusResult {
1633 stack_version: "0.1.0".into(),
1634 services: vec![ServiceInfo {
1635 name: "notes".into(),
1636 allow: vec!["alice".into()],
1637 allow_display: vec![],
1638 backend: BackendKind::Run,
1639 ephemeral: false,
1640 }],
1641 peers: vec![PeerInfo {
1642 name: "alice".into(),
1643 services: vec!["notes".into()],
1644 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1645 user_id: Some("b64u:alicepk".into()),
1646 principal: None,
1647 }],
1648 roster: None,
1649 presence: vec![],
1650 self_user_id: Some("b64u:selfpk".into()),
1651 recent_pairings: vec![],
1652 reachability: vec![],
1653 self_nickname: String::new(),
1654 };
1655 let v = serde_json::to_value(&s).unwrap();
1656 assert_eq!(v["services"][0]["backend"], "run");
1657 // The additive identity fields ride the wire when present.
1658 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1659 assert_eq!(v["self_user_id"], "b64u:selfpk");
1660 assert!(
1661 v.get("roster").is_none(),
1662 "an absent roster must not appear on the wire: {v}"
1663 );
1664 assert!(
1665 v.get("presence").is_none(),
1666 "an empty presence must not appear on the wire: {v}"
1667 );
1668 assert!(
1669 v.get("recent_pairings").is_none(),
1670 "an empty recent_pairings must not appear on the wire: {v}"
1671 );
1672 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1673
1674 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1675 // deserializes — the identity fields default to None / a nickname-only peer.
1676 let old_shape = serde_json::json!({
1677 "stack_version": "0.1.0",
1678 "services": [],
1679 "peers": [{ "name": "bob", "services": [] }],
1680 });
1681 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1682 assert!(back.roster.is_none());
1683 assert!(back.presence.is_empty());
1684 assert!(back.self_user_id.is_none());
1685 assert!(back.peers[0].user_id.is_none());
1686 assert!(back.recent_pairings.is_empty());
1687
1688 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1689 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1690 let s = StatusResult {
1691 stack_version: "0.1.0".into(),
1692 services: vec![],
1693 peers: vec![],
1694 roster: Some(RosterStatus {
1695 org_id: "acme".into(),
1696 serial: 42,
1697 state: "approved".into(),
1698 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1699 }),
1700 presence: vec![
1701 PresencePeer {
1702 user_id: "alice".into(),
1703 device_label: "laptop".into(),
1704 role: "primary".into(),
1705 online: true,
1706 meta: String::new(),
1707 },
1708 PresencePeer {
1709 user_id: "alice".into(),
1710 device_label: "desktop".into(),
1711 role: "mirror".into(),
1712 online: false,
1713 meta: String::new(),
1714 },
1715 ],
1716 self_user_id: None,
1717 recent_pairings: vec![],
1718 reachability: vec![],
1719 self_nickname: String::new(),
1720 };
1721 let v = serde_json::to_value(&s).unwrap();
1722 assert_eq!(v["roster"]["org_id"], "acme");
1723 assert_eq!(v["roster"]["serial"], 42u64);
1724 assert_eq!(v["roster"]["state"], "approved");
1725 assert_eq!(
1726 v["roster"]["org_root_fingerprint"],
1727 "tango-fig-cabbage-anchor"
1728 );
1729 assert_eq!(v["presence"][0]["user_id"], "alice");
1730 assert_eq!(v["presence"][0]["device_label"], "laptop");
1731 assert_eq!(v["presence"][0]["role"], "primary");
1732 assert_eq!(v["presence"][0]["online"], true);
1733 assert_eq!(v["presence"][1]["online"], false);
1734 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1735 }
1736
1737 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1738 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1739 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1740 /// older daemon (no key at all) still deserializes to empty.
1741 #[test]
1742 fn recent_pairings_are_additive_on_status() {
1743 let s = StatusResult {
1744 stack_version: "0.1.0".into(),
1745 services: vec![],
1746 peers: vec![],
1747 roster: None,
1748 presence: vec![],
1749 self_user_id: None,
1750 recent_pairings: vec![RecentPairing {
1751 peer_nickname: "bob".into(),
1752 sas_code: "tango-fig-cabbage".into(),
1753 paired_at_epoch: 1_800_000_000,
1754 }],
1755 reachability: vec![],
1756 self_nickname: String::new(),
1757 };
1758 let v = serde_json::to_value(&s).unwrap();
1759 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1760 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1761 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1762 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1763
1764 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1765 // the `#[serde(default)]` fills it with an empty list.
1766 let old_shape = serde_json::json!({
1767 "stack_version": "0.1.0",
1768 "services": [],
1769 "peers": [],
1770 });
1771 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1772 assert!(back.recent_pairings.is_empty());
1773 }
1774
1775 #[test]
1776 fn blob_requests_and_results_roundtrip() {
1777 // BlobPublish → { method, params: { scope, path } }.
1778 let r = Request::BlobPublish(BlobPublishParams {
1779 scope: "docs".into(),
1780 path: "/tmp/a.bin".into(),
1781 });
1782 let v = serde_json::to_value(&r).unwrap();
1783 assert_eq!(v["method"], "blob_publish");
1784 assert_eq!(v["params"]["scope"], "docs");
1785 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1786 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1787
1788 // BlobGrant → { method, params: { scope, principal } }.
1789 let r = Request::BlobGrant(BlobGrantParams {
1790 scope: "docs".into(),
1791 principal: "alice".into(),
1792 });
1793 let v = serde_json::to_value(&r).unwrap();
1794 assert_eq!(v["method"], "blob_grant");
1795 assert_eq!(v["params"]["principal"], "alice");
1796 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1797
1798 // BlobList is parameterless (method_of resolves it).
1799 assert_eq!(
1800 method_of(&serde_json::json!({"method": "blob_list"})),
1801 Some("blob_list")
1802 );
1803
1804 // BlobFetch → { method, params: { ticket, dest_path } }.
1805 let r = Request::BlobFetch(BlobFetchParams {
1806 ticket: "blobAAA".into(),
1807 dest_path: "/tmp/out.bin".into(),
1808 });
1809 let v = serde_json::to_value(&r).unwrap();
1810 assert_eq!(v["method"], "blob_fetch");
1811 assert_eq!(v["params"]["ticket"], "blobAAA");
1812 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1813 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1814
1815 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1816 let res = BlobPublishResult {
1817 ticket: "blobAAA".into(),
1818 hash: "ab".repeat(32),
1819 };
1820 let v = serde_json::to_value(&res).unwrap();
1821 assert_eq!(v["ticket"], "blobAAA");
1822 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1823
1824 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1825 let res = BlobScopeList {
1826 scopes: vec![ScopeInfo {
1827 name: "docs".into(),
1828 hashes: vec!["ab".repeat(32)],
1829 grants: vec!["alice".into()],
1830 }],
1831 };
1832 let v = serde_json::to_value(&res).unwrap();
1833 assert_eq!(v["scopes"][0]["name"], "docs");
1834 assert_eq!(v["scopes"][0]["grants"][0], "alice");
1835 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1836
1837 // BlobFetchResult carries the verified hash + byte length.
1838 let res = BlobFetchResult {
1839 hash: "ab".repeat(32),
1840 bytes_len: 4194304,
1841 };
1842 let v = serde_json::to_value(&res).unwrap();
1843 assert_eq!(v["bytes_len"], 4194304u64);
1844 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1845 }
1846
1847 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1848 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1849 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1850 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1851 #[test]
1852 fn stream_frames_roundtrip_with_the_documented_tags() {
1853 let snap = StreamFrame::Snapshot {
1854 active_sessions: vec![ActiveSession {
1855 peer: "bob".into(),
1856 service: "notes".into(),
1857 opened_at: 1_751_760_000,
1858 }],
1859 reachability: vec![PeerReachability {
1860 name: "bob".into(),
1861 reachable: true,
1862 rtt_ms: Some(42),
1863 age_secs: Some(3),
1864 meta: String::new(),
1865 principal: None,
1866 path: Default::default(),
1867 }],
1868 };
1869 let v = serde_json::to_value(&snap).unwrap();
1870 assert_eq!(v["type"], "snapshot");
1871 assert_eq!(v["active_sessions"][0]["peer"], "bob");
1872 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1873 assert_eq!(v["reachability"][0]["name"], "bob");
1874 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1875
1876 let event = StreamFrame::Event {
1877 record: Box::new(AuditRecord::session_open(
1878 "2026-07-03T14:02:11.480Z".into(),
1879 Some("bob".into()),
1880 "notes".into(),
1881 )),
1882 };
1883 let v = serde_json::to_value(&event).unwrap();
1884 assert_eq!(v["type"], "event");
1885 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1886 assert_eq!(v["record"]["kind"], "session_open");
1887 assert_eq!(v["record"]["peer"], "bob");
1888 assert_eq!(v["record"]["service"], "notes");
1889 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1890
1891 let lagged = StreamFrame::Lagged { dropped: 12 };
1892 let v = serde_json::to_value(&lagged).unwrap();
1893 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1894 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1895 }
1896
1897 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1898 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1899 /// raw `Value` stream instead (`ControlClient::open_stream`).
1900 #[test]
1901 fn unknown_stream_frame_type_is_rejected() {
1902 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1903 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1904 }
1905
1906 #[test]
1907 fn audit_summary_request_and_result_roundtrip() {
1908 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1909 // tolerates omitted/null params; the server dispatches on the method string (method_of).
1910 let r = Request::AuditSummary;
1911 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1912 assert_eq!(
1913 method_of(&serde_json::json!({"method": "audit_summary"})),
1914 Some("audit_summary")
1915 );
1916
1917 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1918 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1919 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1920 let res = AuditSummaryResult {
1921 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
1922 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
1923 total_sessions: 4,
1924 };
1925 let v = serde_json::to_value(&res).unwrap();
1926 assert_eq!(v["per_peer"][1][0], "bob");
1927 assert_eq!(v["per_peer"][1][1], 2u64);
1928 assert_eq!(v["per_service"][1][0], "notes");
1929 assert_eq!(v["total_sessions"], 4u64);
1930 assert_eq!(
1931 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
1932 res
1933 );
1934
1935 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
1936 // deserializes — the `#[serde(default)]` fills it with 0.
1937 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
1938 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
1939 assert_eq!(back.total_sessions, 0);
1940 assert!(back.per_peer.is_empty());
1941 }
1942}