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