Skip to main content

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