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