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 serde::{Deserialize, Serialize};
15
16/// The first exchange on any `*-local/N` socket (the family's hello convention).
17#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
18pub struct Hello {
19 pub api: String, // "mcpmesh-local/1"
20 pub api_version: String, // "MAJOR.MINOR" of the protocol surface (see API_MINOR)
21 /// The protocol-compatibility MINOR as an integer, for a trivial machine comparison
22 /// (`api_minor >= N`) without string parsing. Distinct from `stack_version` (the crate
23 /// release train). Additive: an older daemon omits it and it defaults to 0.
24 #[serde(default)]
25 pub api_minor: u32,
26 pub stack_version: String,
27}
28
29/// The kind of backend answering a service — the two valid values, enforced at the
30/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
31/// kind only, never the command/path (no transport vocabulary).
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
33#[serde(rename_all = "snake_case")]
34pub enum BackendKind {
35 Run,
36 Socket,
37}
38
39/// A registered service as reported by `status` (no transport vocabulary).
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
41pub struct ServiceInfo {
42 pub name: String,
43 pub allow: Vec<String>, // nicknames/groups (flat namespace)
44 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
45 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
46 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
47 /// daemon omits it and it reads as `false` (the persistent default).
48 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
49 pub ephemeral: bool,
50}
51
52/// A known peer as reported by `status` (nickname only — never the EndpointId).
53#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
54pub struct PeerInfo {
55 pub name: String,
56 pub services: Vec<String>,
57 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
58 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
59 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
60 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
61 #[serde(default, skip_serializing_if = "Option::is_none")]
62 pub user_id: Option<String>,
63}
64
65/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean:
66/// a nickname + a bool + latency/age NUMBERS — never an endpoint-id, key, or transport path.
67#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
68pub struct PeerReachability {
69 pub name: String, // the peer's nickname
70 pub reachable: bool, // result of the last probe (false if never probed)
71 #[serde(default, skip_serializing_if = "Option::is_none")]
72 pub rtt_ms: Option<u64>, // last measured round-trip, if reachable
73 #[serde(default, skip_serializing_if = "Option::is_none")]
74 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
75}
76
77/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
78/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
79/// as-transport-vocab. Absent in a pure-pairing daemon.
80#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct RosterStatus {
82 pub org_id: String,
83 pub serial: u64,
84 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
85 pub org_root_fingerprint: String, // short-word form
86}
87
88/// One reachable roster peer device as reported by `status` (the advisory presence read).
89/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
90/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
91/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct PresencePeer {
94 pub user_id: String,
95 pub device_label: String,
96 pub role: String, // "primary" | "mirror" (roster vocabulary)
97 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
98 pub online: bool,
99}
100
101/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
102/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
103/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
104/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
105/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
106/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
107/// an epoch — never an EndpointId.
108#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
109pub struct RecentPairing {
110 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
111 pub peer_nickname: String,
112 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
113 /// `PairResult.sas_code` carried. Never checked programmatically.
114 pub sas_code: String,
115 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
116 pub paired_at_epoch: u64,
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
120pub struct StatusResult {
121 pub stack_version: String,
122 pub services: Vec<ServiceInfo>,
123 pub peers: Vec<PeerInfo>,
124 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
125 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
126 #[serde(default, skip_serializing_if = "Option::is_none")]
127 pub roster: Option<RosterStatus>,
128 /// The reachable roster peer devices (the advisory presence read), each with an `online`
129 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
130 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
131 #[serde(default, skip_serializing_if = "Vec::is_empty")]
132 pub presence: Vec<PresencePeer>,
133 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
134 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
135 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
136 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
137 #[serde(default, skip_serializing_if = "Option::is_none")]
138 pub self_user_id: Option<String>,
139 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
140 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
141 /// that has accepted no pairing since it started. Additive:
142 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
143 #[serde(default, skip_serializing_if = "Vec::is_empty")]
144 pub recent_pairings: Vec<RecentPairing>,
145 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
146 /// first probe completes. Additive: default + skip-if-empty.
147 #[serde(default, skip_serializing_if = "Vec::is_empty")]
148 pub reachability: Vec<PeerReachability>,
149 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
150 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
151 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
152 /// skip-if-empty so an older payload round-trips.
153 #[serde(default, skip_serializing_if = "String::is_empty")]
154 pub self_nickname: String,
155}
156
157/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
158#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
159#[serde(deny_unknown_fields)]
160pub struct RegisterServiceParams {
161 pub name: String,
162 pub backend: BackendSpec,
163 pub allow: Vec<String>,
164 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
165 /// to the on-disk config, and automatically unregistered when the control connection that
166 /// registered it closes (and gone on daemon restart). For an embedder that serves a
167 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
168 /// socket path solely to keep a persisted registration valid, and the stale-registration
169 /// accumulation that comes with no unregister. Default false = the persistent behavior.
170 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
171 pub ephemeral: bool,
172}
173
174/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
175/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
176/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
177/// list (an invite that grants nothing is useless — #34).
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(deny_unknown_fields)]
180pub struct InviteParams {
181 #[serde(default)]
182 pub services: Vec<String>,
183 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
184 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
185 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
186 #[serde(default, skip_serializing_if = "Option::is_none")]
187 pub app_label: Option<String>,
188}
189
190/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
191/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(deny_unknown_fields)]
194pub struct PairParams {
195 #[serde(default)]
196 pub invite_line: String,
197}
198
199/// Params of [`Request::PeerRemove`]: the nickname to unpair.
200#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
201#[serde(deny_unknown_fields)]
202pub struct PeerRemoveParams {
203 pub nickname: String,
204}
205
206/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
207/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
208#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
209#[serde(deny_unknown_fields)]
210pub struct PeerRenameParams {
211 #[serde(default)]
212 pub user_id: Option<String>,
213 #[serde(default)]
214 pub nickname: Option<String>,
215 pub to: String,
216}
217
218/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
219/// (iroh base32) plus the nickname and service allow list to install it under.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(deny_unknown_fields)]
222pub struct PeerAddParams {
223 pub nickname: String,
224 pub endpoint_id: String,
225 #[serde(default)]
226 pub allow: Vec<String>,
227}
228
229/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
230/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
232#[serde(deny_unknown_fields)]
233pub struct OpenSessionParams {
234 #[serde(default)]
235 pub peer: String,
236 #[serde(default)]
237 pub service: String,
238}
239
240/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
241/// on FIRST install (`b64u:`; omit once pinned — config carries it).
242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(deny_unknown_fields)]
244pub struct RosterInstallParams {
245 pub path: String,
246 #[serde(default, skip_serializing_if = "Option::is_none")]
247 pub org_root_pk: Option<String>,
248}
249
250/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
251/// never crosses the API.
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(deny_unknown_fields)]
254pub struct OrgJoinParams {
255 pub org_id: String,
256 pub org_root_pk: String,
257 pub user_id: String,
258 pub user_key: String,
259}
260
261/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
262/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
263/// they stored at pairing time until a re-invite.
264#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
265#[serde(deny_unknown_fields)]
266pub struct SetNicknameParams {
267 pub nickname: String,
268}
269
270/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
271#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
272#[serde(deny_unknown_fields)]
273pub struct SetRosterUrlParams {
274 pub url: String,
275}
276
277/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(deny_unknown_fields)]
280pub struct BlobPublishParams {
281 pub scope: String,
282 pub path: String,
283}
284
285/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
286#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
287#[serde(deny_unknown_fields)]
288pub struct BlobGrantParams {
289 pub scope: String,
290 pub principal: String,
291}
292
293/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295#[serde(deny_unknown_fields)]
296pub struct BlobFetchParams {
297 pub ticket: String,
298 pub dest_path: String,
299}
300
301/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
302/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
303///
304/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
305/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
306/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
307/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
308/// identical to inline variant bodies.
309///
310/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
311/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
312/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
313/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
314/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316#[serde(tag = "method", content = "params", rename_all = "snake_case")]
317pub enum Request {
318 /// Register/update a `[services.*]` entry idempotently.
319 RegisterService(RegisterServiceParams),
320 Status,
321 /// Mint a one-time pairing invite granting `services`. The daemon
322 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
323 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
324 /// `method` string generically; the tag comes from `rename_all`.
325 Invite(InviteParams),
326 /// Redeem a pairing invite. The daemon dials the inviter named by
327 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
328 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
329 /// (snake_case); `method_of` reads the `method` string generically.
330 ///
331 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
332 Pair(PairParams),
333 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
334 /// peer's `PeerEntry` (identity) AND revokes its access by removing the nickname from every
335 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
336 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
337 /// NOT severed here: existing sessions run to completion; the peer only loses the
338 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
339 /// `method_of` reads the `method` string generically (no per-variant arm).
340 ///
341 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
342 PeerRemove(PeerRemoveParams),
343 /// Rename a contact's nickname (nickname) authoritatively. Renames the
344 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
345 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
346 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
347 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
348 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
349 /// host-privileged like the other pair ops.
350 PeerRename(PeerRenameParams),
351 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
352 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
353 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
354 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
355 /// vocabulary — do not build on it. Tag `"peer_add"`.
356 PeerAdd(PeerAddParams),
357 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
358 /// Distinct from the proxy's job: this returns a session the client streams.
359 /// Named `open_session` rather than `connect` to avoid colliding
360 /// with the `connect` porcelain.
361 OpenSession(OpenSessionParams),
362 /// Install a signed roster from a local file (the manual `internal roster install` path).
363 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
364 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
365 /// pins the org root on FIRST install (`b64u:`); omit it
366 /// once pinned (config carries it). Tag `"roster_install"`.
367 RosterInstall(RosterInstallParams),
368 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
369 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
370 /// `user_key` is a LOCAL path
371 /// (the key never crosses the API). Tag `"org_join"`.
372 OrgJoin(OrgJoinParams),
373 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
374 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
375 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
376 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
377 /// `"set_roster_url"`.
378 SetRosterUrl(SetRosterUrlParams),
379 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
380 /// daemon's own serialized config-write path (no lost-update window against a
381 /// concurrent grant/registration) and update the in-memory name future invites
382 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
383 SetNickname(SetNicknameParams),
384 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
385 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
386 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
387 /// Tag `"blob_publish"`.
388 BlobPublish(BlobPublishParams),
389 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
390 /// nickname (the shared `principal_set` expansion). Tag
391 /// `"blob_grant"`.
392 BlobGrant(BlobGrantParams),
393 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
394 BlobList,
395 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
396 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
397 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
398 BlobFetch(BlobFetchParams),
399 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
400 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
401 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
402 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
403 /// `method_of` reads the `method` string generically (no per-variant arm).
404 AuditSummary,
405 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
406 /// connection STOPS being request/response after this call and becomes a one-way push stream
407 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
408 Subscribe,
409}
410
411/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
412/// computed porcelain-side from the invite's org_root_pk). Additive-only.
413#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414pub struct OrgJoinResult {
415 pub org_id: String,
416}
417
418/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
419/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
420/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
421///
422/// Additive-only: any future field MUST land as
423/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
424#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
425pub struct RosterInstallResult {
426 pub org_id: String,
427 pub serial: u64,
428 /// How many live sessions were severed, for the porcelain's confirmation line.
429 #[serde(default)]
430 pub severed: u32,
431}
432
433/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
434/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
435/// carve-out as the pairing invite line). Additive-only.
436#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
437pub struct BlobPublishResult {
438 pub ticket: String,
439 pub hash: String, // bare blake3 hex
440}
441
442/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
443/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
444#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
445pub struct ScopeInfo {
446 pub name: String,
447 pub hashes: Vec<String>,
448 pub grants: Vec<String>,
449}
450
451/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
452#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
453pub struct BlobScopeList {
454 pub scopes: Vec<ScopeInfo>,
455}
456
457/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
458/// Additive-only.
459#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
460pub struct BlobFetchResult {
461 pub hash: String,
462 pub bytes_len: u64,
463}
464
465/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
466/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
467/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
468/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
469/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
470/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
471///
472/// Additive-only: any future field MUST land as
473/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
474#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
475pub struct AuditSummaryResult {
476 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
477 /// peer to attribute) but IS in `total_sessions`.
478 pub per_peer: Vec<(String, u64)>,
479 /// Sessions opened per registered service name.
480 pub per_service: Vec<(String, u64)>,
481 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
482 #[serde(default)]
483 pub total_sessions: u64,
484}
485
486/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
487/// (the ONE pairing artifact deliberately carved out of the
488/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
489/// absolute expiry in epoch seconds (≤ now + 24h).
490///
491/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
492/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
493/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
494/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
495/// ceremony" note in `docs/local-protocol.md` (#35).
496///
497/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
498/// so older payloads still deserialize.
499#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
500pub struct InviteResult {
501 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
502 pub invite_line: String,
503 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
504 pub expires_at_epoch: u64,
505}
506
507/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
508/// redeemer's local name for the new peer) plus the display-only short authentication
509/// code (SAS) — a few words the human reads aloud to a second channel to
510/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
511/// artifact (like the invite line), NOT a transport-vocabulary leak.
512///
513/// Additive-only: any future field MUST land as
514/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
515#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
516pub struct PairResult {
517 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
518 pub peer_nickname: String,
519 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
520 /// sides for the out-of-band human check. Never sent on the wire, never checked
521 /// programmatically.
522 pub sas_code: String,
523 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
524 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
525 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
526 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
527 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
528 #[serde(default, skip_serializing_if = "Vec::is_empty")]
529 pub services: Vec<String>,
530 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
531 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
532 #[serde(default, skip_serializing_if = "Option::is_none")]
533 pub app_label: Option<String>,
534 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
535 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
536 /// can align with its own — and the same value it may later pass to `open_session` to dial
537 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
538 /// binding (a legacy/keyless peer). Additive.
539 #[serde(default, skip_serializing_if = "Option::is_none")]
540 pub peer_user_id: Option<String>,
541}
542
543/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
544/// top of the base record schema: it removes no field and makes the JSONL self-describing so
545/// a consumer can filter by class without guessing from which optional fields are present.
546#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
547#[serde(rename_all = "snake_case")]
548pub enum AuditKind {
549 /// A mesh session opened (a backend was selected for an authenticated peer).
550 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
551 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
552 SessionOpen,
553 /// A mesh session closed (the backend returned / the session tore down).
554 SessionClose,
555 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
556 Request,
557 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
558 BlobFetch,
559 /// A trust mutation (pair, unpair, roster install/swap, revoke).
560 Trust,
561}
562
563/// One audit record — the union of the event classes, and the `record` payload of a
564/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
565/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
566/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
567/// `bytes_out`).
568///
569/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
570/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
571/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
572#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
573pub struct AuditRecord {
574 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
575 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
576 pub ts: String,
577 pub kind: AuditKind,
578 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
579 /// local-only events with no remote peer (a manual roster install).
580 #[serde(skip_serializing_if = "Option::is_none")]
581 pub peer: Option<String>,
582 #[serde(skip_serializing_if = "Option::is_none")]
583 pub service: Option<String>,
584 #[serde(skip_serializing_if = "Option::is_none")]
585 pub method: Option<String>,
586 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
587 #[serde(skip_serializing_if = "Option::is_none")]
588 pub tool: Option<String>,
589 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
590 #[serde(skip_serializing_if = "Option::is_none")]
591 pub args_hash: Option<String>,
592 /// Byte COUNT of the response sent back to the peer — a count, never the content.
593 #[serde(skip_serializing_if = "Option::is_none")]
594 pub bytes_out: Option<u64>,
595 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
596 #[serde(skip_serializing_if = "Option::is_none")]
597 pub status: Option<String>,
598 #[serde(skip_serializing_if = "Option::is_none")]
599 pub latency_ms: Option<u64>,
600 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
601 #[serde(skip_serializing_if = "Option::is_none")]
602 pub event: Option<String>,
603 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
604 /// nickname or `org/serial` (`Trust`).
605 #[serde(skip_serializing_if = "Option::is_none")]
606 pub target: Option<String>,
607}
608
609impl AuditRecord {
610 fn base(ts: String, kind: AuditKind) -> Self {
611 Self {
612 ts,
613 kind,
614 peer: None,
615 service: None,
616 method: None,
617 tool: None,
618 args_hash: None,
619 bytes_out: None,
620 status: None,
621 latency_ms: None,
622 event: None,
623 target: None,
624 }
625 }
626
627 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
628 let mut r = Self::base(ts, AuditKind::SessionOpen);
629 r.peer = peer;
630 r.service = Some(service);
631 r
632 }
633
634 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
635 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
636 /// reaches no backend and so is never audited by the far side's session guard — without a
637 /// dedicated constructor. DRY: reuses the existing optional `status` field.
638 pub fn with_status(mut self, status: &str) -> Self {
639 self.status = Some(status.into());
640 self
641 }
642
643 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
644 let mut r = Self::base(ts, AuditKind::SessionClose);
645 r.peer = peer;
646 r.service = Some(service);
647 r
648 }
649
650 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
651 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
652 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
653 #[allow(clippy::too_many_arguments)]
654 pub fn proxied_request(
655 ts: String,
656 peer: Option<String>,
657 service: String,
658 method: String,
659 tool: Option<String>,
660 args_hash: String,
661 bytes_out: u64,
662 status: String,
663 latency_ms: u64,
664 ) -> Self {
665 let mut r = Self::base(ts, AuditKind::Request);
666 r.peer = peer;
667 r.service = Some(service);
668 r.method = Some(method);
669 r.tool = tool;
670 r.args_hash = Some(args_hash);
671 r.bytes_out = Some(bytes_out);
672 r.status = Some(status);
673 r.latency_ms = Some(latency_ms);
674 r
675 }
676
677 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
678 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
679 pub fn proxied_notification(
680 ts: String,
681 peer: Option<String>,
682 service: String,
683 method: String,
684 tool: Option<String>,
685 args_hash: String,
686 ) -> Self {
687 let mut r = Self::base(ts, AuditKind::Request);
688 r.peer = peer;
689 r.service = Some(service);
690 r.method = Some(method);
691 r.tool = tool;
692 r.args_hash = Some(args_hash);
693 r
694 }
695
696 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
697 let mut r = Self::base(ts, AuditKind::BlobFetch);
698 r.peer = peer;
699 r.target = Some(hash);
700 r.status = Some(status);
701 r
702 }
703
704 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
705 let mut r = Self::base(ts, AuditKind::Trust);
706 r.event = Some(event);
707 r.target = target;
708 r
709 }
710}
711
712/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
713/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
714#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
715pub struct ActiveSession {
716 pub peer: String,
717 pub service: String,
718 pub opened_at: i64,
719}
720
721/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
722/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
723/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
724/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
725/// them (see `docs/local-protocol.md` "Live event stream").
726#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
727#[serde(tag = "type", rename_all = "snake_case")]
728pub enum StreamFrame {
729 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
730 /// reachability) so a fresh subscriber renders immediately without replaying history.
731 Snapshot {
732 active_sessions: Vec<ActiveSession>,
733 reachability: Vec<PeerReachability>,
734 },
735 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
736 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
737 /// `Box`, so the wire shape is the record's fields verbatim.
738 Event { record: Box<AuditRecord> },
739 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
740 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
741 Lagged { dropped: u64 },
742}
743
744/// Extract the `method` tag from a raw request value without deserializing the whole
745/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
746/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
747/// methods (adjacent tagging rejects `params:{}` on unit variants).
748pub fn method_of(v: &serde_json::Value) -> Option<&str> {
749 v.get("method").and_then(serde_json::Value::as_str)
750}
751
752/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
753/// Config→BackendSpec is a hand-written match, not a serde passthrough.
754#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
755#[serde(rename_all = "snake_case")]
756pub enum BackendSpec {
757 Run { cmd: Vec<String> },
758 Socket { path: String },
759}
760
761pub const API_NAME: &str = "mcpmesh-local/1";
762/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
763///
764/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
765/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
766/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
767/// new methods, or a strictness change like params validation — bumped in the same change that
768/// makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
769/// older than a minor it requires. It never resets except on a MAJOR bump.
770pub const API_VERSION: &str = "1.2";
771/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
772/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37).
773pub const API_MINOR: u32 = 2;
774
775#[cfg(test)]
776mod tests {
777 use super::*;
778
779 #[test]
780 fn peer_reachability_serde_is_additive() {
781 let r = PeerReachability {
782 name: "bob".into(),
783 reachable: true,
784 rtt_ms: Some(42),
785 age_secs: Some(3),
786 };
787 let v = serde_json::to_value(&r).unwrap();
788 assert_eq!(v["name"], "bob");
789 assert_eq!(v["reachable"], true);
790 assert_eq!(v["rtt_ms"], 42);
791 assert_eq!(v["age_secs"], 3);
792 // Never-probed peer: optionals elided, not null.
793 let unknown = PeerReachability {
794 name: "carol".into(),
795 reachable: false,
796 rtt_ms: None,
797 age_secs: None,
798 };
799 let uv = serde_json::to_value(&unknown).unwrap();
800 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
801 // An older StatusResult (no reachability field) still deserializes.
802 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
803 let s: StatusResult = serde_json::from_value(old).unwrap();
804 assert!(s.reachability.is_empty());
805 }
806
807 #[test]
808 fn subscribe_method_tag_resolves() {
809 let req = serde_json::to_value(Request::Subscribe).unwrap();
810 assert_eq!(method_of(&req), Some("subscribe"));
811 }
812
813 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
814
815 #[test]
816 fn invite_params_reject_singular_service_typo() {
817 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
818 // InviteParams { services: [] } and mint a grants-nothing invite that looked
819 // successful. With deny_unknown_fields the typo is a loud parse error instead.
820 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
821 assert!(
822 err.is_err(),
823 "an unknown `service` key must be rejected, not silently ignored"
824 );
825 // The correct plural shape still parses.
826 let ok: InviteParams =
827 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
828 assert_eq!(ok.services, vec!["kb".to_string()]);
829 }
830
831 #[test]
832 fn open_session_params_reject_unknown_field() {
833 let err = serde_json::from_value::<OpenSessionParams>(
834 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
835 );
836 assert!(err.is_err(), "unknown params keys must be rejected");
837 }
838
839 #[test]
840 fn set_nickname_request_carries_the_method_tag() {
841 let r = Request::SetNickname(SetNicknameParams {
842 nickname: "workbench".into(),
843 });
844 let v = serde_json::to_value(&r).unwrap();
845 assert_eq!(v["method"], "set_nickname");
846 assert_eq!(v["params"]["nickname"], "workbench");
847 assert_eq!(method_of(&v), Some("set_nickname"));
848 }
849
850 #[test]
851 fn set_nickname_params_reject_unknown_field() {
852 let err = serde_json::from_value::<SetNicknameParams>(
853 serde_json::json!({"nickname": "x", "nonsense": 1}),
854 );
855 assert!(err.is_err(), "unknown params keys must be rejected");
856 }
857
858 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
859 /// the additive-only contract — and an empty name must not serialize at all.
860 #[test]
861 fn status_self_nickname_is_additive() {
862 let old = serde_json::json!({
863 "stack_version": "0.7.0", "services": [], "peers": []
864 });
865 let s: StatusResult = serde_json::from_value(old).unwrap();
866 assert_eq!(s.self_nickname, "");
867 let v = serde_json::to_value(&s).unwrap();
868 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
869 }
870
871 #[test]
872 fn api_minor_is_present_and_monotonic_from_hello() {
873 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
874 // crate/stack version, additive on the Hello frame.
875 let h = Hello {
876 api: API_NAME.into(),
877 api_version: API_VERSION.into(),
878 api_minor: API_MINOR,
879 stack_version: "9.9.9".into(),
880 };
881 let v = serde_json::to_value(&h).unwrap();
882 assert_eq!(v["api_minor"], API_MINOR);
883 // An OLD Hello without api_minor still deserializes (additive contract).
884 let old = serde_json::json!({
885 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
886 });
887 let back: Hello = serde_json::from_value(old).unwrap();
888 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
889 }
890
891 #[test]
892 fn hello_result_roundtrips() {
893 let h = Hello {
894 api: "mcpmesh-local/1".into(),
895 api_version: "1.0".into(),
896 api_minor: 0,
897 stack_version: "0.1.0".into(),
898 };
899 let v = serde_json::to_value(&h).unwrap();
900 assert_eq!(v["api"], "mcpmesh-local/1");
901 let back: Hello = serde_json::from_value(v).unwrap();
902 assert_eq!(back, h);
903 }
904
905 #[test]
906 fn request_tagged_by_method() {
907 let r = Request::Status;
908 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
909 let r = Request::OpenSession(OpenSessionParams {
910 peer: "alice".into(),
911 service: "notes".into(),
912 });
913 let v = serde_json::to_value(&r).unwrap();
914 assert_eq!(v["method"], "open_session");
915 assert_eq!(v["params"]["peer"], "alice");
916 }
917
918 #[test]
919 fn parameterless_method_tolerates_params_forms() {
920 // Omitted and null params deserialize straight into the unit variant.
921 let omitted: Request =
922 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
923 assert_eq!(omitted, Request::Status);
924 let null: Request =
925 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
926 .unwrap();
927 assert_eq!(null, Request::Status);
928
929 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
930 // the server MUST dispatch on the method string rather than deserialize the whole
931 // message into `Request`. This is the pattern the daemon's dispatcher uses.
932 let empty = serde_json::json!({"method": "status", "params": {}});
933 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
934 match method_of(&empty) {
935 Some("status") => {} // dispatcher resolves Status via the method string
936 other => panic!("method_of failed to resolve status: {other:?}"),
937 }
938 }
939
940 #[test]
941 fn backend_spec_roundtrips() {
942 let run = BackendSpec::Run {
943 cmd: vec!["notes-mcp".into(), "--stdio".into()],
944 };
945 let v = serde_json::to_value(&run).unwrap();
946 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
947 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
948
949 let sock = BackendSpec::Socket {
950 path: "/run/notes.sock".into(),
951 };
952 let v = serde_json::to_value(&sock).unwrap();
953 assert_eq!(v["socket"]["path"], "/run/notes.sock");
954 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
955 }
956
957 #[test]
958 fn register_service_wire_shape() {
959 let r = Request::RegisterService(RegisterServiceParams {
960 name: "notes".into(),
961 backend: BackendSpec::Run {
962 cmd: vec!["notes-mcp".into()],
963 },
964 allow: vec!["alice".into()],
965 ephemeral: false,
966 });
967 let v = serde_json::to_value(&r).unwrap();
968 assert_eq!(
969 v,
970 serde_json::json!({
971 "method": "register_service",
972 "params": {
973 "name": "notes",
974 "backend": {"run": {"cmd": ["notes-mcp"]}},
975 "allow": ["alice"],
976 }
977 })
978 );
979 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
980 }
981
982 #[test]
983 fn invite_request_and_result_roundtrip() {
984 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
985 let r = Request::Invite(InviteParams {
986 services: vec!["notes".into(), "kb".into()],
987 app_label: None,
988 });
989 let v = serde_json::to_value(&r).unwrap();
990 assert_eq!(v["method"], "invite");
991 assert_eq!(v["params"]["services"][0], "notes");
992 assert_eq!(v["params"]["services"][1], "kb");
993 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
994 // method_of resolves the tag generically (no per-variant arm).
995 assert_eq!(
996 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
997 Some("invite")
998 );
999
1000 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1001 let res = InviteResult {
1002 invite_line: "mcpmesh-invite:ABCDEF".into(),
1003 expires_at_epoch: 1_800_000_000,
1004 };
1005 let v = serde_json::to_value(&res).unwrap();
1006 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1007 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1008 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1009 }
1010
1011 #[test]
1012 fn pair_request_and_result_roundtrip() {
1013 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1014 let r = Request::Pair(PairParams {
1015 invite_line: "mcpmesh-invite:ABCDEF".into(),
1016 });
1017 let v = serde_json::to_value(&r).unwrap();
1018 assert_eq!(v["method"], "pair");
1019 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1020 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1021 // method_of resolves the tag generically (no per-variant arm).
1022 assert_eq!(
1023 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1024 Some("pair")
1025 );
1026
1027 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1028 // the granted services (the porcelain renders each as `<peer>/<service>`).
1029 let res = PairResult {
1030 peer_nickname: "alice".into(),
1031 sas_code: "tango-fig-cabbage".into(),
1032 services: vec!["notes".into(), "kb".into()],
1033 app_label: None,
1034 peer_user_id: None,
1035 };
1036 let v = serde_json::to_value(&res).unwrap();
1037 assert_eq!(v["peer_nickname"], "alice");
1038 assert_eq!(v["sas_code"], "tango-fig-cabbage");
1039 assert_eq!(v["services"][0], "notes");
1040 assert_eq!(v["services"][1], "kb");
1041 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1042
1043 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1044 // deserializes — the `#[serde(default)]` fills it with an empty list.
1045 let old_shape = serde_json::json!({
1046 "peer_nickname": "alice",
1047 "sas_code": "tango-fig-cabbage",
1048 });
1049 let back: PairResult = serde_json::from_value(old_shape).unwrap();
1050 assert_eq!(back.peer_nickname, "alice");
1051 assert!(back.services.is_empty());
1052 }
1053
1054 #[test]
1055 fn roster_install_request_and_result_roundtrip() {
1056 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1057 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1058 let r = Request::RosterInstall(RosterInstallParams {
1059 path: "/tmp/roster.json".into(),
1060 org_root_pk: Some("b64u:AAAA".into()),
1061 });
1062 let v = serde_json::to_value(&r).unwrap();
1063 assert_eq!(v["method"], "roster_install");
1064 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1065 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1066 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1067 // method_of resolves the tag generically (no per-variant arm).
1068 assert_eq!(
1069 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1070 Some("roster_install")
1071 );
1072
1073 // When the pk is omitted (a subsequent install using the pinned value), it is
1074 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1075 let omit = Request::RosterInstall(RosterInstallParams {
1076 path: "/tmp/roster.json".into(),
1077 org_root_pk: None,
1078 });
1079 let v = serde_json::to_value(&omit).unwrap();
1080 assert!(
1081 v["params"].get("org_root_pk").is_none(),
1082 "an omitted org_root_pk must not appear on the wire: {v}"
1083 );
1084 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1085
1086 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1087 let res = RosterInstallResult {
1088 org_id: "acme".into(),
1089 serial: 42,
1090 severed: 1,
1091 };
1092 let v = serde_json::to_value(&res).unwrap();
1093 assert_eq!(v["org_id"], "acme");
1094 assert_eq!(v["serial"], 42u64);
1095 assert_eq!(v["severed"], 1u32);
1096 assert_eq!(
1097 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1098 res
1099 );
1100
1101 // Additive-only: a result minted by an older daemon (no `severed` key) still
1102 // deserializes — the `#[serde(default)]` fills it with 0.
1103 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1104 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1105 assert_eq!(back.serial, 7);
1106 assert_eq!(back.severed, 0);
1107 }
1108
1109 #[test]
1110 fn org_join_request_and_result_roundtrip() {
1111 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1112 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1113 let r = Request::OrgJoin(OrgJoinParams {
1114 org_id: "acme".into(),
1115 org_root_pk: "b64u:AAAA".into(),
1116 user_id: "alice".into(),
1117 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1118 });
1119 let v = serde_json::to_value(&r).unwrap();
1120 assert_eq!(v["method"], "org_join");
1121 assert_eq!(v["params"]["org_id"], "acme");
1122 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1123 assert_eq!(v["params"]["user_id"], "alice");
1124 assert_eq!(
1125 v["params"]["user_key"],
1126 "/home/alice/.config/mcpmesh/user.key"
1127 );
1128 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1129 // method_of resolves the tag generically (no per-variant arm).
1130 assert_eq!(
1131 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1132 Some("org_join")
1133 );
1134
1135 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1136 let res = OrgJoinResult {
1137 org_id: "acme".into(),
1138 };
1139 let v = serde_json::to_value(&res).unwrap();
1140 assert_eq!(v["org_id"], "acme");
1141 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1142 }
1143
1144 #[test]
1145 fn set_roster_url_request_roundtrip() {
1146 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1147 let r = Request::SetRosterUrl(SetRosterUrlParams {
1148 url: "https://intranet.acme.com/roster.json".into(),
1149 });
1150 let v = serde_json::to_value(&r).unwrap();
1151 assert_eq!(v["method"], "set_roster_url");
1152 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1153 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1154 assert_eq!(
1155 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1156 Some("set_roster_url")
1157 );
1158 }
1159
1160 #[test]
1161 fn peer_remove_request_roundtrip() {
1162 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1163 let r = Request::PeerRemove(PeerRemoveParams {
1164 nickname: "bob".into(),
1165 });
1166 let v = serde_json::to_value(&r).unwrap();
1167 assert_eq!(v["method"], "peer_remove");
1168 assert_eq!(v["params"]["nickname"], "bob");
1169 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1170 // method_of resolves the tag generically (no per-variant arm).
1171 assert_eq!(
1172 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1173 Some("peer_remove")
1174 );
1175 }
1176
1177 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1178 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1179 /// defaulting to empty when absent.
1180 #[test]
1181 fn peer_add_request_roundtrip() {
1182 let r = Request::PeerAdd(PeerAddParams {
1183 nickname: "bob".into(),
1184 endpoint_id: "96246d3f".into(),
1185 allow: vec!["notes".into()],
1186 });
1187 let v = serde_json::to_value(&r).unwrap();
1188 assert_eq!(v["method"], "peer_add");
1189 assert_eq!(v["params"]["nickname"], "bob");
1190 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1191 assert_eq!(v["params"]["allow"][0], "notes");
1192 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1193 // An absent allow list deserializes to empty (the server-side tolerance).
1194 let p: PeerAddParams =
1195 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1196 .unwrap();
1197 assert!(p.allow.is_empty());
1198 }
1199
1200 #[test]
1201 fn peer_rename_request_roundtrip() {
1202 // By user_id (renames all of a person's devices in one op).
1203 let r = Request::PeerRename(PeerRenameParams {
1204 user_id: Some("b64u:BOB".into()),
1205 nickname: None,
1206 to: "Bobby".into(),
1207 });
1208 let v = serde_json::to_value(&r).unwrap();
1209 assert_eq!(v["method"], "peer_rename");
1210 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1211 assert_eq!(v["params"]["to"], "Bobby");
1212 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1213 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1214 assert_eq!(
1215 method_of(
1216 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1217 ),
1218 Some("peer_rename")
1219 );
1220 }
1221
1222 #[test]
1223 fn status_result_roundtrips() {
1224 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1225 // older payload with no `roster` key still deserializes to None (serde default).
1226 let s = StatusResult {
1227 stack_version: "0.1.0".into(),
1228 services: vec![ServiceInfo {
1229 name: "notes".into(),
1230 allow: vec!["alice".into()],
1231 backend: BackendKind::Run,
1232 ephemeral: false,
1233 }],
1234 peers: vec![PeerInfo {
1235 name: "alice".into(),
1236 services: vec!["notes".into()],
1237 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1238 user_id: Some("b64u:alicepk".into()),
1239 }],
1240 roster: None,
1241 presence: vec![],
1242 self_user_id: Some("b64u:selfpk".into()),
1243 recent_pairings: vec![],
1244 reachability: vec![],
1245 self_nickname: String::new(),
1246 };
1247 let v = serde_json::to_value(&s).unwrap();
1248 assert_eq!(v["services"][0]["backend"], "run");
1249 // The additive identity fields ride the wire when present.
1250 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1251 assert_eq!(v["self_user_id"], "b64u:selfpk");
1252 assert!(
1253 v.get("roster").is_none(),
1254 "an absent roster must not appear on the wire: {v}"
1255 );
1256 assert!(
1257 v.get("presence").is_none(),
1258 "an empty presence must not appear on the wire: {v}"
1259 );
1260 assert!(
1261 v.get("recent_pairings").is_none(),
1262 "an empty recent_pairings must not appear on the wire: {v}"
1263 );
1264 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1265
1266 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1267 // deserializes — the identity fields default to None / a nickname-only peer.
1268 let old_shape = serde_json::json!({
1269 "stack_version": "0.1.0",
1270 "services": [],
1271 "peers": [{ "name": "bob", "services": [] }],
1272 });
1273 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1274 assert!(back.roster.is_none());
1275 assert!(back.presence.is_empty());
1276 assert!(back.self_user_id.is_none());
1277 assert!(back.peers[0].user_id.is_none());
1278 assert!(back.recent_pairings.is_empty());
1279
1280 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1281 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1282 let s = StatusResult {
1283 stack_version: "0.1.0".into(),
1284 services: vec![],
1285 peers: vec![],
1286 roster: Some(RosterStatus {
1287 org_id: "acme".into(),
1288 serial: 42,
1289 state: "approved".into(),
1290 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1291 }),
1292 presence: vec![
1293 PresencePeer {
1294 user_id: "alice".into(),
1295 device_label: "laptop".into(),
1296 role: "primary".into(),
1297 online: true,
1298 },
1299 PresencePeer {
1300 user_id: "alice".into(),
1301 device_label: "desktop".into(),
1302 role: "mirror".into(),
1303 online: false,
1304 },
1305 ],
1306 self_user_id: None,
1307 recent_pairings: vec![],
1308 reachability: vec![],
1309 self_nickname: String::new(),
1310 };
1311 let v = serde_json::to_value(&s).unwrap();
1312 assert_eq!(v["roster"]["org_id"], "acme");
1313 assert_eq!(v["roster"]["serial"], 42u64);
1314 assert_eq!(v["roster"]["state"], "approved");
1315 assert_eq!(
1316 v["roster"]["org_root_fingerprint"],
1317 "tango-fig-cabbage-anchor"
1318 );
1319 assert_eq!(v["presence"][0]["user_id"], "alice");
1320 assert_eq!(v["presence"][0]["device_label"], "laptop");
1321 assert_eq!(v["presence"][0]["role"], "primary");
1322 assert_eq!(v["presence"][0]["online"], true);
1323 assert_eq!(v["presence"][1]["online"], false);
1324 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1325 }
1326
1327 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1328 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1329 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1330 /// older daemon (no key at all) still deserializes to empty.
1331 #[test]
1332 fn recent_pairings_are_additive_on_status() {
1333 let s = StatusResult {
1334 stack_version: "0.1.0".into(),
1335 services: vec![],
1336 peers: vec![],
1337 roster: None,
1338 presence: vec![],
1339 self_user_id: None,
1340 recent_pairings: vec![RecentPairing {
1341 peer_nickname: "bob".into(),
1342 sas_code: "tango-fig-cabbage".into(),
1343 paired_at_epoch: 1_800_000_000,
1344 }],
1345 reachability: vec![],
1346 self_nickname: String::new(),
1347 };
1348 let v = serde_json::to_value(&s).unwrap();
1349 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1350 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1351 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1352 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1353
1354 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1355 // the `#[serde(default)]` fills it with an empty list.
1356 let old_shape = serde_json::json!({
1357 "stack_version": "0.1.0",
1358 "services": [],
1359 "peers": [],
1360 });
1361 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1362 assert!(back.recent_pairings.is_empty());
1363 }
1364
1365 #[test]
1366 fn blob_requests_and_results_roundtrip() {
1367 // BlobPublish → { method, params: { scope, path } }.
1368 let r = Request::BlobPublish(BlobPublishParams {
1369 scope: "docs".into(),
1370 path: "/tmp/a.bin".into(),
1371 });
1372 let v = serde_json::to_value(&r).unwrap();
1373 assert_eq!(v["method"], "blob_publish");
1374 assert_eq!(v["params"]["scope"], "docs");
1375 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1376 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1377
1378 // BlobGrant → { method, params: { scope, principal } }.
1379 let r = Request::BlobGrant(BlobGrantParams {
1380 scope: "docs".into(),
1381 principal: "alice".into(),
1382 });
1383 let v = serde_json::to_value(&r).unwrap();
1384 assert_eq!(v["method"], "blob_grant");
1385 assert_eq!(v["params"]["principal"], "alice");
1386 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1387
1388 // BlobList is parameterless (method_of resolves it).
1389 assert_eq!(
1390 method_of(&serde_json::json!({"method": "blob_list"})),
1391 Some("blob_list")
1392 );
1393
1394 // BlobFetch → { method, params: { ticket, dest_path } }.
1395 let r = Request::BlobFetch(BlobFetchParams {
1396 ticket: "blobAAA".into(),
1397 dest_path: "/tmp/out.bin".into(),
1398 });
1399 let v = serde_json::to_value(&r).unwrap();
1400 assert_eq!(v["method"], "blob_fetch");
1401 assert_eq!(v["params"]["ticket"], "blobAAA");
1402 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1403 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1404
1405 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1406 let res = BlobPublishResult {
1407 ticket: "blobAAA".into(),
1408 hash: "ab".repeat(32),
1409 };
1410 let v = serde_json::to_value(&res).unwrap();
1411 assert_eq!(v["ticket"], "blobAAA");
1412 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1413
1414 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1415 let res = BlobScopeList {
1416 scopes: vec![ScopeInfo {
1417 name: "docs".into(),
1418 hashes: vec!["ab".repeat(32)],
1419 grants: vec!["alice".into()],
1420 }],
1421 };
1422 let v = serde_json::to_value(&res).unwrap();
1423 assert_eq!(v["scopes"][0]["name"], "docs");
1424 assert_eq!(v["scopes"][0]["grants"][0], "alice");
1425 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1426
1427 // BlobFetchResult carries the verified hash + byte length.
1428 let res = BlobFetchResult {
1429 hash: "ab".repeat(32),
1430 bytes_len: 4194304,
1431 };
1432 let v = serde_json::to_value(&res).unwrap();
1433 assert_eq!(v["bytes_len"], 4194304u64);
1434 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1435 }
1436
1437 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1438 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1439 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1440 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1441 #[test]
1442 fn stream_frames_roundtrip_with_the_documented_tags() {
1443 let snap = StreamFrame::Snapshot {
1444 active_sessions: vec![ActiveSession {
1445 peer: "bob".into(),
1446 service: "notes".into(),
1447 opened_at: 1_751_760_000,
1448 }],
1449 reachability: vec![PeerReachability {
1450 name: "bob".into(),
1451 reachable: true,
1452 rtt_ms: Some(42),
1453 age_secs: Some(3),
1454 }],
1455 };
1456 let v = serde_json::to_value(&snap).unwrap();
1457 assert_eq!(v["type"], "snapshot");
1458 assert_eq!(v["active_sessions"][0]["peer"], "bob");
1459 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1460 assert_eq!(v["reachability"][0]["name"], "bob");
1461 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1462
1463 let event = StreamFrame::Event {
1464 record: Box::new(AuditRecord::session_open(
1465 "2026-07-03T14:02:11.480Z".into(),
1466 Some("bob".into()),
1467 "notes".into(),
1468 )),
1469 };
1470 let v = serde_json::to_value(&event).unwrap();
1471 assert_eq!(v["type"], "event");
1472 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1473 assert_eq!(v["record"]["kind"], "session_open");
1474 assert_eq!(v["record"]["peer"], "bob");
1475 assert_eq!(v["record"]["service"], "notes");
1476 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1477
1478 let lagged = StreamFrame::Lagged { dropped: 12 };
1479 let v = serde_json::to_value(&lagged).unwrap();
1480 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1481 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1482 }
1483
1484 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1485 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1486 /// raw `Value` stream instead (`ControlClient::open_stream`).
1487 #[test]
1488 fn unknown_stream_frame_type_is_rejected() {
1489 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1490 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1491 }
1492
1493 #[test]
1494 fn audit_summary_request_and_result_roundtrip() {
1495 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1496 // tolerates omitted/null params; the server dispatches on the method string (method_of).
1497 let r = Request::AuditSummary;
1498 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1499 assert_eq!(
1500 method_of(&serde_json::json!({"method": "audit_summary"})),
1501 Some("audit_summary")
1502 );
1503
1504 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1505 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1506 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1507 let res = AuditSummaryResult {
1508 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
1509 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
1510 total_sessions: 4,
1511 };
1512 let v = serde_json::to_value(&res).unwrap();
1513 assert_eq!(v["per_peer"][1][0], "bob");
1514 assert_eq!(v["per_peer"][1][1], 2u64);
1515 assert_eq!(v["per_service"][1][0], "notes");
1516 assert_eq!(v["total_sessions"], 4u64);
1517 assert_eq!(
1518 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
1519 res
1520 );
1521
1522 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
1523 // deserializes — the `#[serde(default)]` fills it with 0.
1524 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
1525 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
1526 assert_eq!(back.total_sessions, 0);
1527 assert!(back.per_peer.is_empty());
1528 }
1529}