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