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/// WHICH producer emitted a [`StreamFrame::Reachability`] (#150). The two say different things
164/// about the world and license different user-facing statements, and until API 1.30 the frame
165/// carried no way to tell them apart.
166///
167/// Advisory attribution, never an authz input: it says where an observation CAME FROM, never who a
168/// peer is.
169#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
170#[serde(rename_all = "snake_case")]
171#[non_exhaustive]
172pub enum ReachabilitySource {
173    /// A **probe** completed — a fresh throwaway dial (`status`/`subscribe` refreshing a stale
174    /// entry). It describes that dial and nothing else: a `Probe` frame saying `Relay` does NOT
175    /// mean any live connection is relayed.
176    Probe,
177    /// A **live session**'s selected path changed under it (#92 item 2). This is a claim about the
178    /// link a peer's traffic is actually on — the frame an embedder wants when warning that a call
179    /// which WAS direct silently is not any more.
180    Session,
181    /// The daemon did not say (`api_minor < 30`), or it named a producer this client predates.
182    ///
183    /// The DEFAULT, deliberately — see [`StreamFrame::Reachability`]. Like [`PeerPath::Unknown`] it
184    /// means "we do not know" and must never be collapsed into either confident case.
185    #[default]
186    Unknown,
187}
188
189/// Hand-written so an unrecognized producer lands on [`ReachabilitySource::Unknown`] instead of
190/// failing the whole frame. [`PeerPath`] gets this from `#[serde(other)]`, which serde allows only
191/// on an internally/adjacently tagged enum; this one is a plain string, so it is spelled out. The
192/// stakes are the same as there: without it, adding a third producer later would break every
193/// `Reachability` frame an older pinned client reads, not just the new field.
194///
195/// It accepts ANY input, not just an unrecognized string — `null`, a number, an object all read as
196/// `Unknown`. `#[serde(default)]` covers an ABSENT key and nothing else, so without this a proxy or
197/// non-Rust daemon that normalizes optional fields to `null` would fail every reachability frame
198/// while this module's doc promised the field could not break a parse. A degraded attribution is
199/// the fail-safe: `Unknown` already means "we do not know", which is exactly true of a value we
200/// could not read.
201impl<'de> Deserialize<'de> for ReachabilitySource {
202    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
203        struct AnySource;
204
205        /// Every hook answers `Unknown` except `visit_str`, so a shape we do not model degrades
206        /// instead of erroring. `visit_map`/`visit_seq` must DRAIN their input — leaving it
207        /// unconsumed desynchronizes the parser and fails the enclosing frame, which is the
208        /// failure this impl exists to avoid.
209        impl<'de> serde::de::Visitor<'de> for AnySource {
210            type Value = ReachabilitySource;
211
212            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
213                f.write_str("a reachability producer name")
214            }
215
216            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> {
217                Ok(match s {
218                    "probe" => ReachabilitySource::Probe,
219                    "session" => ReachabilitySource::Session,
220                    _ => ReachabilitySource::Unknown,
221                })
222            }
223
224            fn visit_unit<E: serde::de::Error>(self) -> Result<Self::Value, E> {
225                Ok(ReachabilitySource::Unknown)
226            }
227
228            fn visit_none<E: serde::de::Error>(self) -> Result<Self::Value, E> {
229                Ok(ReachabilitySource::Unknown)
230            }
231
232            fn visit_some<D: serde::Deserializer<'de>>(
233                self,
234                d: D,
235            ) -> Result<Self::Value, D::Error> {
236                d.deserialize_any(AnySource)
237            }
238
239            fn visit_bool<E: serde::de::Error>(self, _: bool) -> Result<Self::Value, E> {
240                Ok(ReachabilitySource::Unknown)
241            }
242
243            fn visit_i64<E: serde::de::Error>(self, _: i64) -> Result<Self::Value, E> {
244                Ok(ReachabilitySource::Unknown)
245            }
246
247            fn visit_u64<E: serde::de::Error>(self, _: u64) -> Result<Self::Value, E> {
248                Ok(ReachabilitySource::Unknown)
249            }
250
251            fn visit_f64<E: serde::de::Error>(self, _: f64) -> Result<Self::Value, E> {
252                Ok(ReachabilitySource::Unknown)
253            }
254
255            fn visit_map<A: serde::de::MapAccess<'de>>(
256                self,
257                mut m: A,
258            ) -> Result<Self::Value, A::Error> {
259                while m
260                    .next_entry::<serde::de::IgnoredAny, serde::de::IgnoredAny>()?
261                    .is_some()
262                {}
263                Ok(ReachabilitySource::Unknown)
264            }
265
266            fn visit_seq<A: serde::de::SeqAccess<'de>>(
267                self,
268                mut s: A,
269            ) -> Result<Self::Value, A::Error> {
270                while s.next_element::<serde::de::IgnoredAny>()?.is_some() {}
271                Ok(ReachabilitySource::Unknown)
272            }
273        }
274
275        d.deserialize_any(AnySource)
276    }
277}
278
279/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
280/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
281/// as-transport-vocab. Absent in a pure-pairing daemon.
282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
283pub struct RosterStatus {
284    pub org_id: String,
285    pub serial: u64,
286    pub state: String, // "pending" | "approved" | "degraded" | "stopped"
287    pub org_root_fingerprint: String, // short-word form
288}
289
290/// One reachable roster peer device as reported by `status` (the advisory presence read).
291/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
292/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
293/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
294#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
295pub struct PresencePeer {
296    pub user_id: String,
297    pub device_label: String,
298    pub role: String, // "primary" | "mirror" (roster vocabulary)
299    /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
300    pub online: bool,
301    /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
302    /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
303    /// data; never an authz input. Additive: default + skip-if-empty.
304    #[serde(default, skip_serializing_if = "String::is_empty")]
305    pub meta: String,
306}
307
308/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
309/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
310/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
311/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
312/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
313/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
314/// an epoch — never an EndpointId.
315#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
316pub struct RecentPairing {
317    /// The peer's nickname as stored by the inviter (its local name for the redeemer).
318    pub peer_nickname: String,
319    /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
320    /// `PairResult.sas_code` carried. Never checked programmatically.
321    pub sas_code: String,
322    /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
323    pub paired_at_epoch: u64,
324}
325
326#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
327pub struct StatusResult {
328    pub stack_version: String,
329    pub services: Vec<ServiceInfo>,
330    pub peers: Vec<PeerInfo>,
331    /// Roster-mode status, absent in a pure-pairing daemon. Additive:
332    /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
333    #[serde(default, skip_serializing_if = "Option::is_none")]
334    pub roster: Option<RosterStatus>,
335    /// The reachable roster peer devices (the advisory presence read), each with an `online`
336    /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
337    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
338    #[serde(default, skip_serializing_if = "Vec::is_empty")]
339    pub presence: Vec<PresencePeer>,
340    /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
341    /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
342    /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
343    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
344    #[serde(default, skip_serializing_if = "Option::is_none")]
345    pub self_user_id: Option<String>,
346    /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
347    /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
348    /// that has accepted no pairing since it started. Additive:
349    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
350    #[serde(default, skip_serializing_if = "Vec::is_empty")]
351    pub recent_pairings: Vec<RecentPairing>,
352    /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
353    /// first probe completes. Additive: default + skip-if-empty.
354    #[serde(default, skip_serializing_if = "Vec::is_empty")]
355    pub reachability: Vec<PeerReachability>,
356    /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
357    /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
358    /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
359    /// skip-if-empty so an older payload round-trips.
360    #[serde(default, skip_serializing_if = "String::is_empty")]
361    pub self_nickname: String,
362    /// On-disk footprint of this node's own state (#88), so an embedder can warn a user before
363    /// ENOSPC rather than after — the audit log's write rate is driven by inbound peer traffic,
364    /// and it shares a filesystem with `state.redb` and the device key. A LIVE read (computed
365    /// per `status` call), not a boot-time snapshot. `None` only in mesh-less control-only mode.
366    /// Additive: default + skip-if-none so an older payload round-trips.
367    #[serde(default, skip_serializing_if = "Option::is_none")]
368    pub storage: Option<StorageInfo>,
369    /// THIS node's own reachability posture (#90) — see [`SelfNetwork`]. Computed live per
370    /// call; `None` in mesh-less control-only mode. Additive: default + skip-if-none.
371    #[serde(default, skip_serializing_if = "Option::is_none")]
372    pub self_network: Option<SelfNetwork>,
373}
374
375/// The `status.self_network` block (#90): THIS node's own reachability posture — the first
376/// question in every "my message never arrived" investigation, previously unanswerable from
377/// either side of the API. Self-facing only: everything here is the node's own information
378/// (relay URLs come from its own config, sanitized; direct addresses already ride its invites).
379///
380/// `online` is iroh's own semantics — a home-relay connection is established. In
381/// `relay_mode = "disabled"` it is ALWAYS `false` with an empty `relays` list: that is a
382/// configuration, not an outage — render it as "LAN-only", never as a health warning.
383///
384/// Additive-only.
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386pub struct SelfNetwork {
387    /// A home-relay connection is established (iroh's `online` definition). The signal #53's
388    /// `set_relays` never had: when this goes false on a relay-enabled node, the relay set is
389    /// the thing to look at.
390    pub online: bool,
391    /// The CONNECTED home relay's URL, sanitized to scheme + host + port (operator-supplied
392    /// relay URLs can carry userinfo tokens; `status` output gets screenshotted). `None` when
393    /// no relay is connected.
394    #[serde(default, skip_serializing_if = "Option::is_none")]
395    pub home_relay: Option<String>,
396    /// Every known home relay and its current connection state. Empty when no relays are
397    /// configured, or before the endpoint has selected any.
398    #[serde(default, skip_serializing_if = "Vec::is_empty")]
399    pub relays: Vec<RelayInfo>,
400    /// This endpoint's direct (non-relay) socket addresses — its own dialable coordinates.
401    #[serde(default, skip_serializing_if = "Vec::is_empty")]
402    pub direct_addrs: Vec<String>,
403    /// When the daemon's watcher last observed a TRANSITION (epoch seconds) — a change of
404    /// `online`, `home_relay`, or a relay's connection state; `direct_addrs` drift alone does
405    /// not stamp (nor emit a frame). OMITTED (not `null`) until the first observed transition
406    /// after boot, and from a point-in-time computation with no watcher running.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub last_change_epoch: Option<i64>,
409}
410
411/// One home relay's connection state (#90). No latency — per-relay RTT needs iroh's
412/// `net_report`, which is unstable-feature-gated as of 1.0.3; `connected` is the stable truth.
413#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
414pub struct RelayInfo {
415    /// Sanitized (scheme + host + port), like `home_relay`.
416    pub url: String,
417    pub connected: bool,
418}
419
420/// The `status.storage` block (#88): bytes actually on disk, by subsystem. Counts, never
421/// content. Additive-only.
422#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
423pub struct StorageInfo {
424    /// Summed sizes of the monthly audit files (`<state>/audit/*.jsonl`).
425    pub audit_bytes: u64,
426    /// Size of the peer/trust state store (`state.redb`).
427    pub redb_bytes: u64,
428    /// Total size under the app-blob store directory; 0 when no blob store exists.
429    pub blobs_bytes: u64,
430}
431
432/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
433#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
434#[serde(deny_unknown_fields)]
435pub struct RegisterServiceParams {
436    pub name: String,
437    pub backend: BackendSpec,
438    pub allow: Vec<String>,
439    /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
440    /// to the on-disk config, and automatically unregistered when the control connection that
441    /// registered it closes (and gone on daemon restart). For an embedder that serves a
442    /// `socket` backend from a fresh path each run, this removes the need to derive a stable
443    /// socket path solely to keep a persisted registration valid, and the stale-registration
444    /// accumulation that comes with no unregister. Default false = the persistent behavior.
445    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
446    pub ephemeral: bool,
447}
448
449/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
450/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
451/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
452/// list (an invite that grants nothing is useless — #34).
453#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
454#[serde(deny_unknown_fields)]
455pub struct InviteParams {
456    #[serde(default)]
457    pub services: Vec<String>,
458    /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
459    /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
460    /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
461    #[serde(default, skip_serializing_if = "Option::is_none")]
462    pub app_label: Option<String>,
463}
464
465/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
466/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
467#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
468#[serde(deny_unknown_fields)]
469pub struct PairParams {
470    #[serde(default)]
471    pub invite_line: String,
472}
473
474/// Params of [`Request::PeerRemove`]: the nickname to unpair.
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(deny_unknown_fields)]
477pub struct PeerRemoveParams {
478    pub nickname: String,
479}
480
481/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
482/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
483#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
484#[serde(deny_unknown_fields)]
485pub struct PeerRenameParams {
486    #[serde(default)]
487    pub user_id: Option<String>,
488    #[serde(default)]
489    pub nickname: Option<String>,
490    pub to: String,
491}
492
493/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
494/// (iroh base32) plus the nickname and service allow list to install it under.
495#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
496#[serde(deny_unknown_fields)]
497pub struct PeerAddParams {
498    pub nickname: String,
499    pub endpoint_id: String,
500    #[serde(default)]
501    pub allow: Vec<String>,
502}
503
504/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
505/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
506#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
507#[serde(deny_unknown_fields)]
508pub struct OpenSessionParams {
509    #[serde(default)]
510    pub peer: String,
511    #[serde(default)]
512    pub service: String,
513}
514
515/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
516/// on FIRST install (`b64u:`; omit once pinned — config carries it).
517#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
518#[serde(deny_unknown_fields)]
519pub struct RosterInstallParams {
520    pub path: String,
521    #[serde(default, skip_serializing_if = "Option::is_none")]
522    pub org_root_pk: Option<String>,
523}
524
525/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
526/// never crosses the API.
527#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
528#[serde(deny_unknown_fields)]
529pub struct OrgJoinParams {
530    pub org_id: String,
531    pub org_root_pk: String,
532    pub user_id: String,
533    pub user_key: String,
534}
535
536/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
537/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
538/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
539/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541#[serde(deny_unknown_fields)]
542pub struct SetAppMetadataParams {
543    pub metadata: String,
544}
545
546/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
547/// principal, or a `b64u:` user_id.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549#[serde(deny_unknown_fields)]
550pub struct PeerServicesParams {
551    pub peer: String,
552}
553
554/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
555/// caller — computed authoritatively on the peer (which owns the truth), always current, only
556/// the caller's own admitted services (never the peer's full registry).
557#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
558pub struct PeerServicesResult {
559    pub services: Vec<String>,
560}
561
562/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
563/// to remove — the deregistration mirror of `register_service`.
564#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
565#[serde(deny_unknown_fields)]
566pub struct UnregisterServiceParams {
567    pub name: String,
568}
569
570/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
571/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
572/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
573#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
574#[serde(deny_unknown_fields)]
575pub struct ServiceAllowParams {
576    pub service: String,
577    pub principal: String,
578}
579
580/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
581/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
582/// they stored at pairing time until a re-invite.
583#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
584#[serde(deny_unknown_fields)]
585pub struct SetNicknameParams {
586    pub nickname: String,
587}
588
589/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
590#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
591#[serde(deny_unknown_fields)]
592pub struct SetRosterUrlParams {
593    pub url: String,
594}
595
596/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
597/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
598/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
599/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
600/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
601/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
602/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
603/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
604#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
605#[serde(deny_unknown_fields)]
606pub struct SetRelaysParams {
607    pub relay_urls: Vec<String>,
608}
609
610/// Result of [`Request::SetRelays`] (#53).
611#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
612pub struct SetRelaysResult {
613    /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
614    pub changed: bool,
615    /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
616    /// but NOT applied live — a node restart is required for it to take effect. `false` on the
617    /// live custom→custom path (already applied to the running endpoint).
618    pub restart_required: bool,
619}
620
621/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
622#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
623#[serde(deny_unknown_fields)]
624pub struct BlobPublishParams {
625    pub scope: String,
626    pub path: String,
627}
628
629/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
630#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
631#[serde(deny_unknown_fields)]
632pub struct BlobGrantParams {
633    pub scope: String,
634    pub principal: String,
635}
636
637/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
638///
639/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
640/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
641/// access to everything else.
642#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
643#[serde(deny_unknown_fields)]
644pub struct BlobRevokeParams {
645    pub scope: String,
646    pub principals: Vec<String>,
647}
648
649/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
650///
651/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
652/// this takes effect immediately for authorization — but the bytes stay in the local store, and
653/// there is no reclaim verb yet. Do not surface this to a user as deletion.
654#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
655#[serde(deny_unknown_fields)]
656pub struct BlobUnpublishParams {
657    pub scope: String,
658    pub hash: String,
659}
660
661/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
662///
663/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
664/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
665/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
666/// turn the original publisher going offline into a hang at every fetcher.
667///
668/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
669/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
670#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
671#[serde(deny_unknown_fields)]
672pub struct BlobRepublishParams {
673    pub scope: String,
674    pub hash: String,
675}
676
677/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
678#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
679#[serde(deny_unknown_fields)]
680pub struct BlobFetchParams {
681    pub ticket: String,
682    pub dest_path: String,
683}
684
685/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
686/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
687///
688/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
689/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
690/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
691/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
692/// identical to inline variant bodies.
693///
694/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
695/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
696/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
697/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
698/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
699#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
700#[serde(tag = "method", content = "params", rename_all = "snake_case")]
701pub enum Request {
702    /// Register/update a `[services.*]` entry idempotently.
703    RegisterService(RegisterServiceParams),
704    Status,
705    /// Mint a one-time pairing invite granting `services`. The daemon
706    /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
707    /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
708    /// `method` string generically; the tag comes from `rename_all`.
709    Invite(InviteParams),
710    /// Redeem a pairing invite. The daemon dials the inviter named by
711    /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
712    /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
713    /// (snake_case); `method_of` reads the `method` string generically.
714    ///
715    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
716    Pair(PairParams),
717    /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
718    /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
719    /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
720    /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
721    /// NOT severed here: existing sessions run to completion; the peer only loses the
722    /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
723    /// `method_of` reads the `method` string generically (no per-variant arm).
724    ///
725    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
726    PeerRemove(PeerRemoveParams),
727    /// Rename a contact's nickname (nickname) authoritatively. Renames the
728    /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
729    /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
730    /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
731    /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
732    /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
733    /// host-privileged like the other pair ops.
734    PeerRename(PeerRenameParams),
735    /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
736    /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
737    /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
738    /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
739    /// vocabulary — do not build on it. Tag `"peer_add"`.
740    PeerAdd(PeerAddParams),
741    /// Open a mesh session to `peer/service`; the daemon dials and pipes.
742    /// Distinct from the proxy's job: this returns a session the client streams.
743    /// Named `open_session` rather than `connect` to avoid colliding
744    /// with the `connect` porcelain.
745    OpenSession(OpenSessionParams),
746    /// Install a signed roster from a local file (the manual `internal roster install` path).
747    /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
748    /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
749    /// pins the org root on FIRST install (`b64u:`); omit it
750    /// once pinned (config carries it). Tag `"roster_install"`.
751    RosterInstall(RosterInstallParams),
752    /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
753    /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
754    /// `user_key` is a LOCAL path
755    /// (the key never crosses the API). Tag `"org_join"`.
756    OrgJoin(OrgJoinParams),
757    /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
758    /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
759    /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
760    /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
761    /// `"set_roster_url"`.
762    SetRosterUrl(SetRosterUrlParams),
763    /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
764    /// daemon's own serialized config-write path (no lost-update window against a
765    /// concurrent grant/registration) and update the in-memory name future invites
766    /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
767    SetNickname(SetNicknameParams),
768    /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
769    /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
770    /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
771    /// on restart; the embedder re-sets on startup).
772    SetAppMetadata(SetAppMetadataParams),
773    /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
774    /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
775    /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
776    /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
777    /// is currently `default`/`disabled`, the config is persisted but the live mode transition
778    /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
779    /// [`SetRelaysResult`]. Tag `"set_relays"`.
780    SetRelays(SetRelaysParams),
781    /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
782    /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
783    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
784    /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
785    /// hot-reloads. Idempotent. Ack result.
786    UnregisterService(UnregisterServiceParams),
787    /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
788    /// and returns the service names whose allow admits the caller's principal. Answers
789    /// [`PeerServicesResult`].
790    PeerServices(PeerServicesParams),
791    ServiceAllowGrant(ServiceAllowParams),
792    /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
793    /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
794    /// Idempotent. Ack result.
795    ServiceAllowRevoke(ServiceAllowParams),
796    /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
797    /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
798    /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
799    /// Tag `"blob_publish"`.
800    BlobPublish(BlobPublishParams),
801    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
802    /// nickname (the shared `principal_set` expansion). Tag
803    /// `"blob_grant"`.
804    BlobGrant(BlobGrantParams),
805    /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
806    BlobRevoke(BlobRevokeParams),
807    /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
808    /// bytes.
809    BlobUnpublish(BlobUnpublishParams),
810    /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
811    /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
812    /// two interchangeably after a fetch.
813    BlobRepublish(BlobRepublishParams),
814    /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
815    BlobList(BlobListParams),
816    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
817    /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
818    /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
819    BlobFetch(BlobFetchParams),
820    /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
821    /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
822    /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
823    /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
824    /// `method_of` reads the `method` string generically (no per-variant arm).
825    AuditSummary,
826    /// Delete audit months strictly older than `before` (#88) — the retention lever the log
827    /// never had. Local-only and owner-only (the control socket is the daemon owner's). Answers
828    /// [`AuditPruneResult`]. Tag `"audit_prune"`.
829    AuditPrune(AuditPruneParams),
830    /// Read this node's LOCAL audit records, filtered and paged (#88) — the "show me everything
831    /// you hold about me" verb. Local-only; nothing is transmitted. Answers
832    /// [`AuditListResult`]. Tag `"audit_list"`.
833    AuditList(AuditListParams),
834    /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
835    /// connection STOPS being request/response after this call and becomes a one-way push stream
836    /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
837    Subscribe,
838}
839
840/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
841/// computed porcelain-side from the invite's org_root_pk). Additive-only.
842#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
843pub struct OrgJoinResult {
844    pub org_id: String,
845}
846
847/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
848/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
849/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
850///
851/// Additive-only: any future field MUST land as
852/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
853#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
854pub struct RosterInstallResult {
855    pub org_id: String,
856    pub serial: u64,
857    /// How many live sessions were severed, for the porcelain's confirmation line.
858    #[serde(default)]
859    pub severed: u32,
860}
861
862/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
863/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
864/// carve-out as the pairing invite line). Additive-only.
865#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
866pub struct BlobPublishResult {
867    pub ticket: String,
868    pub hash: String, // bare blake3 hex
869}
870
871/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
872/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
873#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
874pub struct ScopeInfo {
875    pub name: String,
876    pub hashes: Vec<String>,
877    pub grants: Vec<String>,
878    /// Hashes deliberately WITHDRAWN from this scope (#107): `blob_unpublish` was called, and
879    /// `blob_republish` of these into THIS scope is refused with [`ERR_BLOB_WITHDRAWN`]. Cleared
880    /// only by a deliberate `blob_publish {scope, path}`. Additive — omitted when empty, so a
881    /// pre-`api_minor` 19 client sees exactly what it saw before.
882    #[serde(default, skip_serializing_if = "Vec::is_empty")]
883    pub withdrawn: Vec<String>,
884    /// Size of `hashes` — always present, even when `counts_only` empties the vector (#84b).
885    #[serde(default)]
886    pub hash_count: usize,
887    /// Size of `grants`.
888    #[serde(default)]
889    pub grant_count: usize,
890    /// Size of `withdrawn`.
891    #[serde(default)]
892    pub withdrawn_count: usize,
893}
894
895/// Params of [`Request::BlobList`] (#84b). ALL optional — `blob_list {}` still works, which
896/// matters because the verb took no params before `api_minor` 20.
897///
898/// A DEFAULT LIMIT applies when `limit` is absent. Deliberate: unpaged, `blob_list` renders every
899/// scope into one frame against the 16 MiB cap; past it the CLIENT rejects the frame as malformed.
900/// The control surface carries no strike bound, so the connection survives — but the caller gets an
901/// opaque failure with no way to page, which is unusable rather than merely large.
902#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
903#[serde(default, deny_unknown_fields)]
904pub struct BlobListParams {
905    /// EXACT scope name, never a prefix.
906    pub scope: Option<String>,
907    /// Only scopes containing this hash; the rendering you send is normalized first.
908    pub hash: Option<String>,
909    pub limit: Option<usize>,
910    pub offset: Option<usize>,
911    /// Omit `hashes`/`grants`/`withdrawn`, keep the counts.
912    pub counts_only: bool,
913}
914
915/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
916#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
917pub struct BlobScopeList {
918    pub scopes: Vec<ScopeInfo>,
919    /// Scopes matching the filter BEFORE `limit`/`offset` (#84b). Without this you cannot tell a
920    /// complete answer from a clipped one.
921    #[serde(default)]
922    pub total: usize,
923    /// True when more scopes matched than were returned. Page with `offset` to see the rest.
924    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
925    pub truncated: bool,
926}
927
928/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
929/// Additive-only.
930#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
931pub struct BlobFetchResult {
932    pub hash: String,
933    pub bytes_len: u64,
934}
935
936/// Params of [`Request::AuditPrune`] (#88): delete monthly audit files STRICTLY older than
937/// `before` (that month itself is kept — delete-before, not delete-including). Rejects unknown
938/// fields, and the daemon validates the `YYYY-MM` shape up front: a malformed month errors
939/// loudly instead of string-comparing to nothing and reporting a clean no-op.
940#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
941#[serde(deny_unknown_fields)]
942pub struct AuditPruneParams {
943    /// A zero-padded `YYYY-MM` month key.
944    pub before: String,
945}
946
947/// Result of [`Request::AuditPrune`]: the month keys actually deleted, ascending. Empty when
948/// nothing was older than `before` (idempotent).
949#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
950pub struct AuditPruneResult {
951    pub deleted_months: Vec<String>,
952}
953
954/// Params of [`Request::AuditList`] (#88). All filters optional and AND-combined; every field
955/// absent lists everything (paged). Rejects unknown fields — a typo'd filter that silently
956/// matched everything would let a "what do you hold about X" answer overclaim.
957#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
958#[serde(deny_unknown_fields)]
959pub struct AuditListParams {
960    /// Inclusive `YYYY-MM` lower bound — month-file granularity (the rotation unit), so an
961    /// out-of-range month is skipped without parsing it.
962    #[serde(default, skip_serializing_if = "Option::is_none")]
963    pub since: Option<String>,
964    /// Inclusive `YYYY-MM` upper bound.
965    #[serde(default, skip_serializing_if = "Option::is_none")]
966    pub until: Option<String>,
967    /// One of the wire kind strings (`session_open` / `session_close` / `request` /
968    /// `blob_fetch` / `trust`). An UNKNOWN string is an error, never silently-all.
969    #[serde(default, skip_serializing_if = "Option::is_none")]
970    pub kind: Option<String>,
971    /// The record's attributed peer nickname.
972    #[serde(default, skip_serializing_if = "Option::is_none")]
973    pub peer: Option<String>,
974    /// Page size, default 500, clamped to 1000 — a month file can be arbitrarily large and the
975    /// response is ONE JSON frame under the transport's frame cap, so the clamp is load-bearing
976    /// (the same lesson as `blob_list`'s, minor 20).
977    #[serde(default, skip_serializing_if = "Option::is_none")]
978    pub limit: Option<u32>,
979    /// Records to skip (after filtering), for paging.
980    #[serde(default, skip_serializing_if = "Option::is_none")]
981    pub offset: Option<u32>,
982}
983
984/// Result of [`Request::AuditList`]: one page of matching records in chronological order
985/// (oldest month first, in-file order within a month), plus the TOTAL match count so a caller
986/// can page without a second counting call. `total` counts ALL matches, not the page.
987#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
988pub struct AuditListResult {
989    pub records: Vec<AuditRecord>,
990    pub total: u64,
991}
992
993/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
994/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
995/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
996/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
997/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
998/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
999///
1000/// Additive-only: any future field MUST land as
1001/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1002#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1003pub struct AuditSummaryResult {
1004    /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
1005    /// peer to attribute) but IS in `total_sessions`.
1006    pub per_peer: Vec<(String, u64)>,
1007    /// Sessions opened per registered service name.
1008    pub per_service: Vec<(String, u64)>,
1009    /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
1010    #[serde(default)]
1011    pub total_sessions: u64,
1012}
1013
1014/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
1015/// (the ONE pairing artifact deliberately carved out of the
1016/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
1017/// absolute expiry in epoch seconds (≤ now + 24h).
1018///
1019/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
1020/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
1021/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
1022/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
1023/// ceremony" note in `docs/local-protocol.md` (#35).
1024///
1025/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
1026/// so older payloads still deserialize.
1027#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1028pub struct InviteResult {
1029    /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
1030    pub invite_line: String,
1031    /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
1032    pub expires_at_epoch: u64,
1033}
1034
1035/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
1036/// redeemer's local name for the new peer) plus the display-only short authentication
1037/// code (SAS) — a few words the human reads aloud to a second channel to
1038/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
1039/// artifact (like the invite line), NOT a transport-vocabulary leak.
1040///
1041/// Additive-only: any future field MUST land as
1042/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1043#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1044pub struct PairResult {
1045    /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
1046    pub peer_nickname: String,
1047    /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
1048    /// sides for the out-of-band human check. Never sent on the wire, never checked
1049    /// programmatically.
1050    pub sas_code: String,
1051    /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
1052    /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
1053    /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
1054    /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
1055    /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
1056    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1057    pub services: Vec<String>,
1058    /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
1059    /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
1060    #[serde(default, skip_serializing_if = "Option::is_none")]
1061    pub app_label: Option<String>,
1062    /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
1063    /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
1064    /// can align with its own — and the same value it may later pass to `open_session` to dial
1065    /// this peer by identity rather than by local nickname. `None` if the inviter presented no
1066    /// binding (a legacy/keyless peer). Additive.
1067    #[serde(default, skip_serializing_if = "Option::is_none")]
1068    pub peer_user_id: Option<String>,
1069}
1070
1071/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
1072/// top of the base record schema: it removes no field and makes the JSONL self-describing so
1073/// a consumer can filter by class without guessing from which optional fields are present.
1074#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1075#[serde(rename_all = "snake_case")]
1076pub enum AuditKind {
1077    /// A mesh session opened (a backend was selected for an authenticated peer).
1078    /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
1079    /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
1080    SessionOpen,
1081    /// A mesh session closed (the backend returned / the session tore down).
1082    SessionClose,
1083    /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
1084    Request,
1085    /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
1086    BlobFetch,
1087    /// A trust mutation (pair, unpair, roster install/swap, revoke).
1088    Trust,
1089}
1090
1091/// One audit record — the union of the event classes, and the `record` payload of a
1092/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
1093/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
1094/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
1095/// `bytes_out`).
1096///
1097/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
1098/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
1099/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
1100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1101pub struct AuditRecord {
1102    /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
1103    /// prefix also selects the monthly file (the rotation boundary), so it is always present.
1104    pub ts: String,
1105    pub kind: AuditKind,
1106    /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
1107    /// local-only events with no remote peer (a manual roster install).
1108    #[serde(skip_serializing_if = "Option::is_none")]
1109    pub peer: Option<String>,
1110    #[serde(skip_serializing_if = "Option::is_none")]
1111    pub service: Option<String>,
1112    #[serde(skip_serializing_if = "Option::is_none")]
1113    pub method: Option<String>,
1114    /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
1115    #[serde(skip_serializing_if = "Option::is_none")]
1116    pub tool: Option<String>,
1117    /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
1118    #[serde(skip_serializing_if = "Option::is_none")]
1119    pub args_hash: Option<String>,
1120    /// Byte COUNT of the response sent back to the peer — a count, never the content.
1121    #[serde(skip_serializing_if = "Option::is_none")]
1122    pub bytes_out: Option<u64>,
1123    /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
1124    #[serde(skip_serializing_if = "Option::is_none")]
1125    pub status: Option<String>,
1126    #[serde(skip_serializing_if = "Option::is_none")]
1127    pub latency_ms: Option<u64>,
1128    /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
1129    #[serde(skip_serializing_if = "Option::is_none")]
1130    pub event: Option<String>,
1131    /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
1132    /// nickname or `org/serial` (`Trust`).
1133    #[serde(skip_serializing_if = "Option::is_none")]
1134    pub target: Option<String>,
1135    /// The subject's STABLE principal, from the same gate resolution that produced `peer`
1136    /// (#57, `api_minor >= 29`). `peer` is a display name and collides — two devices under one
1137    /// nickname were indistinguishable in the stream and the on-disk log. Same argument and
1138    /// shape as `PeerInfo` (#41), `PeerReachability` (#42), and `ActiveSession` (#73).
1139    ///
1140    /// TWO NAMESPACES, deliberately: session/request/blob records attribute the DEVICE
1141    /// (`eid:<hex>`, like `ActiveSession` — the exact authenticated endpoint), while the trust
1142    /// `pair` record carries the value the grant appended to the allow (`b64u:<pk>` when the
1143    /// device presented a user binding, else `eid:`, #38). Joining a bound peer's sessions to
1144    /// its allow entry therefore goes through the `status` peers list (which carries BOTH the
1145    /// device principal and the `user_id`), not string equality on this field alone.
1146    ///
1147    /// Deliberately absent on: `unpair` (may tear down several devices — no single subject),
1148    /// `roster_install` (purely local), and the failed-outbound-dial session record (our own
1149    /// dial, not a gate-resolved caller). Absent on every record written before 0.24.0.
1150    #[serde(default, skip_serializing_if = "Option::is_none")]
1151    pub principal: Option<String>,
1152}
1153
1154impl AuditRecord {
1155    fn base(ts: String, kind: AuditKind) -> Self {
1156        Self {
1157            ts,
1158            kind,
1159            peer: None,
1160            service: None,
1161            method: None,
1162            tool: None,
1163            args_hash: None,
1164            bytes_out: None,
1165            status: None,
1166            latency_ms: None,
1167            event: None,
1168            target: None,
1169            principal: None,
1170        }
1171    }
1172
1173    /// `principal` is an EXPLICIT parameter on every constructor (#57, kept from the original
1174    /// #72 design): a builder would let a call site silently omit it and reintroduce the
1175    /// collapsed-identity bug for that one event class. Pass `None` only for the documented
1176    /// no-single-subject records (see the field doc).
1177    pub fn session_open(
1178        ts: String,
1179        peer: Option<String>,
1180        service: String,
1181        principal: Option<String>,
1182    ) -> Self {
1183        let mut r = Self::base(ts, AuditKind::SessionOpen);
1184        r.peer = peer;
1185        r.service = Some(service);
1186        r.principal = principal;
1187        r
1188    }
1189
1190    /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
1191    /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
1192    /// reaches no backend and so is never audited by the far side's session guard — without a
1193    /// dedicated constructor. DRY: reuses the existing optional `status` field.
1194    pub fn with_status(mut self, status: &str) -> Self {
1195        self.status = Some(status.into());
1196        self
1197    }
1198
1199    pub fn session_close(
1200        ts: String,
1201        peer: Option<String>,
1202        service: String,
1203        principal: Option<String>,
1204    ) -> Self {
1205        let mut r = Self::base(ts, AuditKind::SessionClose);
1206        r.peer = peer;
1207        r.service = Some(service);
1208        r.principal = principal;
1209        r
1210    }
1211
1212    /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
1213    /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
1214    /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
1215    #[allow(clippy::too_many_arguments)]
1216    pub fn proxied_request(
1217        ts: String,
1218        peer: Option<String>,
1219        service: String,
1220        method: String,
1221        tool: Option<String>,
1222        args_hash: String,
1223        bytes_out: u64,
1224        status: String,
1225        latency_ms: u64,
1226        principal: Option<String>,
1227    ) -> Self {
1228        let mut r = Self::base(ts, AuditKind::Request);
1229        r.peer = peer;
1230        r.service = Some(service);
1231        r.method = Some(method);
1232        r.tool = tool;
1233        r.args_hash = Some(args_hash);
1234        r.bytes_out = Some(bytes_out);
1235        r.status = Some(status);
1236        r.latency_ms = Some(latency_ms);
1237        r.principal = principal;
1238        r
1239    }
1240
1241    /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
1242    /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
1243    pub fn proxied_notification(
1244        ts: String,
1245        peer: Option<String>,
1246        service: String,
1247        method: String,
1248        tool: Option<String>,
1249        args_hash: String,
1250        principal: Option<String>,
1251    ) -> Self {
1252        let mut r = Self::base(ts, AuditKind::Request);
1253        r.peer = peer;
1254        r.service = Some(service);
1255        r.method = Some(method);
1256        r.tool = tool;
1257        r.args_hash = Some(args_hash);
1258        r.principal = principal;
1259        r
1260    }
1261
1262    pub fn blob_fetch(
1263        ts: String,
1264        peer: Option<String>,
1265        hash: String,
1266        status: String,
1267        principal: Option<String>,
1268    ) -> Self {
1269        let mut r = Self::base(ts, AuditKind::BlobFetch);
1270        r.peer = peer;
1271        r.target = Some(hash);
1272        r.status = Some(status);
1273        r.principal = principal;
1274        r
1275    }
1276
1277    pub fn trust(
1278        ts: String,
1279        event: String,
1280        target: Option<String>,
1281        principal: Option<String>,
1282    ) -> Self {
1283        let mut r = Self::base(ts, AuditKind::Trust);
1284        r.event = Some(event);
1285        r.target = target;
1286        r.principal = principal;
1287        r
1288    }
1289}
1290
1291/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
1292/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
1293#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1294pub struct ActiveSession {
1295    pub peer: String,
1296    pub service: String,
1297    pub opened_at: i64,
1298    /// The caller's STABLE device principal, `eid:<hex>` (#73).
1299    ///
1300    /// `peer` is a display nickname and collides: two devices under one nickname, or two contacts
1301    /// sharing a display name, are indistinguishable in the live-session view. So "who is using my
1302    /// service right now", per-peer session counts, and any UI that lets a user act on a live
1303    /// session (revoke, disconnect, inspect) were all keyed on a collidable string.
1304    ///
1305    /// Same argument and same shape as [`PeerInfo`] (#41) and [`PeerReachability`] (#42).
1306    /// Nicknames NEVER authorize; this is the value to key on.
1307    ///
1308    /// **Snapshot only, for now.** `ActiveSession` appears in [`StreamFrame::Snapshot`] — there is
1309    /// no `active_sessions` on `StatusResult`. A client that keeps its view current by applying
1310    /// subsequent `session_open`/`session_close` events still has a collision problem: those are
1311    /// [`AuditRecord`]s and carry no principal (#57, unmerged). So the snapshot distinguishes two
1312    /// same-nickname devices and the next `session_close` for that nickname does not say which row
1313    /// to drop. Re-subscribe for an authoritative view until #57 lands.
1314    ///
1315    /// Always present for a real row — `Option` only so an older client round-trips. Additive.
1316    #[serde(default, skip_serializing_if = "Option::is_none")]
1317    pub principal: Option<String>,
1318}
1319
1320/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
1321/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
1322/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
1323/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
1324/// them (see `docs/local-protocol.md` "Live event stream").
1325/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
1326/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
1327/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
1328/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
1329#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1330#[serde(tag = "type", rename_all = "snake_case")]
1331#[non_exhaustive]
1332pub enum StreamFrame {
1333    /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
1334    /// reachability) so a fresh subscriber renders immediately without replaying history.
1335    Snapshot {
1336        active_sessions: Vec<ActiveSession>,
1337        reachability: Vec<PeerReachability>,
1338        /// THIS node's own reachability posture (#90), so a fresh subscriber renders it without
1339        /// a `status` poll. `None` in mesh-less control-only mode. Additive: default +
1340        /// skip-if-none so an older payload round-trips.
1341        #[serde(default, skip_serializing_if = "Option::is_none")]
1342        self_network: Option<SelfNetwork>,
1343    },
1344    /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
1345    /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
1346    /// `Box`, so the wire shape is the record's fields verbatim.
1347    Event { record: Box<AuditRecord> },
1348    /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
1349    /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
1350    /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
1351    /// it returns, rather than on the next poll tick.
1352    ///
1353    /// Emitted on a change of `reachable` **or of `path`**. A refresh with the same verdict AND the
1354    /// same path emits nothing, so a peer that stays up does not produce a frame per TTL refresh;
1355    /// `rtt_ms`/`meta`/`services` drift is advisory detail and is not a transition. `age_secs` is
1356    /// `0` — the observation just completed.
1357    ///
1358    /// **Do not treat this as an up/down toggle.** It carried that meaning through 0.18, and this
1359    /// doc said "on a CHANGE of `reachable` only" until 1.22 — which stopped being true in 0.19.0
1360    /// (#92 item 1), when `path` joined the transition rule. A consumer that assumed same-verdict
1361    /// frames were impossible was reading a stale guarantee.
1362    ///
1363    /// Two producers, as of API 1.22 — and since 1.30 `source` says WHICH ONE, so the distinction
1364    /// is readable rather than inferred:
1365    ///
1366    /// - [`ReachabilitySource::Probe`] — a probe completing (`status`/`subscribe` refreshing a
1367    ///   stale entry). It describes a throwaway dial, not anyone's live connection.
1368    /// - [`ReachabilitySource::Session`] — a live session whose selected path changed under it
1369    ///   (#92 item 2). A claim about the link in use.
1370    ///
1371    /// The second producer is why `path` is trustworthy for a long-lived session: a session that
1372    /// degrades Direct→Relay mid-call now says so when it happens, rather than staying silently
1373    /// mislabelled until something probes. `path` is a truth claim about where user data went, so
1374    /// `Unknown` means "we do not know" and must never be rendered as private.
1375    ///
1376    /// **`rtt_ms` is not a discriminator, and never was** (#150). Until 1.30 this doc said a
1377    /// session-sourced frame carries `rtt_ms: None` — true only of a FIRST observation, where no
1378    /// round trip was measured and none is invented. A session-sourced frame for an
1379    /// already-probed peer carries that probe's `rtt_ms: Some(..)`, because the path watcher
1380    /// deliberately leaves `rtt_ms`/`meta`/`probed_at` alone (refreshing them would stamp a stale
1381    /// RTT as fresh and suppress the corrective probe — #92 review). That is the common case for a
1382    /// peer probed at pairing time and then watched through a long call. Read `source`.
1383    Reachability {
1384        peer: PeerReachability,
1385        /// Which producer emitted this frame (#150). `api_minor >= 30`.
1386        ///
1387        /// Additive: `#[serde(default)]`, landing on [`ReachabilitySource::Unknown`] — NOT on
1388        /// `Probe`. A daemon at `api_minor` 22–29 already has both producers, so an absent field
1389        /// genuinely does not say which one ran; defaulting to `Probe` would assert the wrong
1390        /// producer for every session-sourced frame such a daemon emits, which is the exact
1391        /// ambiguity this field exists to remove.
1392        #[serde(default)]
1393        source: ReachabilitySource,
1394    },
1395    /// THIS node's own network posture CHANGED (#90): `online` flipped, the home relay moved,
1396    /// or a relay's connection state changed — pushed so an embedder learns "you just went
1397    /// unreachable" the moment it happens instead of on a poll tick, and so #53's `set_relays`
1398    /// finally has a signal telling someone to use it. `direct_addrs` drift alone does not
1399    /// emit (address churn is chatty and not a decision point; it rides the next frame).
1400    /// `api_minor >= 28`.
1401    SelfNetwork { self_network: SelfNetwork },
1402    /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
1403    /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
1404    Lagged { dropped: u64 },
1405}
1406
1407/// Extract the `method` tag from a raw request value without deserializing the whole
1408/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
1409/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
1410/// methods (adjacent tagging rejects `params:{}` on unit variants).
1411pub fn method_of(v: &serde_json::Value) -> Option<&str> {
1412    v.get("method").and_then(serde_json::Value::as_str)
1413}
1414
1415/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
1416/// Config→BackendSpec is a hand-written match, not a serde passthrough.
1417#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1418#[serde(rename_all = "snake_case")]
1419pub enum BackendSpec {
1420    Run {
1421        cmd: Vec<String>,
1422        /// Per-service environment variables (#51) for the spawned child. Overlaid on the
1423        /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
1424        /// these (identity is not spoofable by a service definition). Default empty.
1425        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1426        env: BTreeMap<String, String>,
1427        /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
1428        #[serde(default, skip_serializing_if = "Option::is_none")]
1429        cwd: Option<String>,
1430    },
1431    Socket {
1432        path: String,
1433    },
1434}
1435
1436/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
1437/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
1438/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
1439/// `{}` (success) for an unknown name, which silently included every ephemeral service.
1440pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
1441/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
1442/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
1443pub const ERR_NO_SUCH_BLOB: i64 = -32041;
1444/// The blob was deliberately withdrawn from this scope (#107). Distinct from
1445/// [`ERR_NO_SUCH_BLOB`]: that means "fetch it first", this means "someone un-shared this on
1446/// purpose — `blob_publish` from the file if the re-share is intended".
1447pub const ERR_BLOB_WITHDRAWN: i64 = -32042;
1448/// `pair` was refused because the redeemer's nickname is already held by a DIFFERENT paired peer
1449/// (#87), so an embedder can branch on the one refusal that has a self-service remedy — rename and
1450/// redeem the same invite again — without reading the prose (#147).
1451///
1452/// Reading the prose was the only option before this code, and it does not survive translation: the
1453/// message is generated on the INVITER's side and travels to the redeemer, so the embedder that
1454/// DISPLAYS it cannot rewrite it into its own vocabulary except by substring-matching our copy.
1455/// Branch on this and write your own sentence naming your own rename affordance.
1456///
1457/// Deliberately narrow. It rides ONLY this refusal, which is sent exclusively to a caller that
1458/// proved possession of a live invite secret. The generic refusal keeps `-32000` and its opaque
1459/// reason: distinguishing unknown-vs-expired-vs-wrong-secret would be a redemption oracle.
1460pub const ERR_NICKNAME_TAKEN: i64 = -32043;
1461
1462pub const API_NAME: &str = "mcpmesh-local/1";
1463/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
1464///
1465/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
1466///   transport already rejects a mismatched `api`, so an equality check on that is redundant).
1467/// - **MINOR** ([`API_MINOR`]) increments on a surface change within a major — additive fields, new
1468///   methods, or a strictness change like params validation — bumped in the same change that makes
1469///   it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon older
1470///   than a minor it requires. It never resets except on a MAJOR bump.
1471///
1472///   It also bumps for a change to what a field MEANS with no change to its shape — six of the
1473///   thirty have, see [`API_MINOR`]'s history. "Every surface change" is what this line used
1474///   to claim, and it was wrong in both directions: minor 9's entry records surface changes that
1475///   shipped WITHOUT a bump, and six bumps changed no type at all. Read the history, not the rule.
1476pub const API_VERSION: &str = "1.31";
1477/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
1478/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
1479/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
1480/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
1481/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
1482/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
1483/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
1484/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
1485/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
1486/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
1487/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
1488/// observable contract did: a revoked principal's next session is refused even on a connection it
1489/// already holds, and its live connections are severed. Previously both waited for the peer to
1490/// disconnect on its own, which is unbounded (#54). A consumer can guard on
1491/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
1492/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
1493/// about an unknown service name — a name in neither the config nor the ephemeral registry now
1494/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
1495/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
1496/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
1497/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
1498/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
1499/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
1500/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
1501/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
1502/// errored on any daemon without an org root key, though their scope gate never needed one (#61);
1503/// to 17 when the service answer began coming from the LIVE registry rather than config + overlay,
1504/// so a grant the accept path would refuse is no longer advertised. Three surfaces share that
1505/// resolver and all changed together: `status`'s `services[].allow`, `peer_services`' name list,
1506/// and the `mcpmesh/ping/1` probe's `services`. No wire shape changed, only the source of truth —
1507/// exactly the class of change a downstream cannot see in a type diff (#100); to 18 with `blob_republish`, so a fetched blob can
1508/// be re-served and every recipient becomes a source (#83); to 19 with durable blob revocation — an
1509/// unpublish now survives a later republish via a per-scope withdrawal set, and
1510/// [`ERR_BLOB_WITHDRAWN`] distinguishes "deliberately withdrawn" from "never had it" (#107); to 20
1511/// with `blob_list` filters + paging AND a DEFAULT limit of 256 scopes (the clamp is 4096) — a
1512/// daemon with more scopes than that previously answered with
1513/// everything, and past the 16 MiB frame cap the CLIENT rejected the response as malformed, leaving
1514/// the caller an opaque failure with no way to page. The connection survived: the control surface
1515/// carries no strike bound. This is a behaviour change for existing callers, detectable via the new
1516/// `total`/`truncated` (#84b); to 21 when a
1517/// PATH change became a reachability transition — [`StreamFrame::Reachability`] stopped being an
1518/// up/down toggle and same-verdict frames became possible (#92); to 22 with a SECOND producer for
1519/// that frame: a live per-session watcher that pushes when a session's selected path changes,
1520/// rather than waiting for a probe, at a cadence probes never had (#92); to 23 when
1521/// [`PeerReachability::rtt_ms`] stopped including the path-settle window — a relayed peer could
1522/// previously never report under 600ms, so "relayed AND fast" was unreachable by construction
1523/// (#123); to 24 when `reachable` stopped sharing a deadline with path classification — a relayed
1524/// peer whose pong arrived after ~2.4s was reported OFFLINE while it was answering (#128); to 25
1525/// with [`ActiveSession::principal`] — the live-session view was keyed on a display nickname, so
1526/// two devices under one nickname were indistinguishable and any UI acting on a session (revoke,
1527/// disconnect, inspect) keyed on a collidable string (#73); to 26 when a
1528/// rate-limited inbound NOTIFICATION stopped being silently dropped and became a recorded audit
1529/// event — no type changed; the observable audit stream did (#76, #139); to 27 with the `audit_prune` /
1530/// `audit_list` verbs, `StatusResult::storage`, and the opt-in `[limits].audit_retain_months`
1531/// boot retention — the audit log stopped being a permanent, unbounded, unreadable record (#88);
1532/// to 28 with `StatusResult::self_network` / `StreamFrame::SelfNetwork` / the snapshot's copy —
1533/// the node's OWN reachability posture, previously unanswerable from either side of the API
1534/// (#90); to 29 with [`AuditRecord::principal`] — stable identity on the event stream and the
1535/// on-disk log, resolving #57's parked docs conflict in favour of the #41/#42/#73 line (the
1536/// audit surface bans secrets and raw hex, not the prefixed principal rendering); to 30 with
1537/// [`StreamFrame::Reachability`]'s `source` — the frame has had TWO producers since 22 with no way
1538/// to tell them apart, so an embedder could not distinguish "a throwaway dial went via a relay"
1539/// from "the link this call is on just degraded", and had to hedge every message down to the
1540/// weaker claim. `rtt_ms: None` was never the discriminator the doc implied (#150); to 31 with
1541/// [`ERR_NICKNAME_TAKEN`] — the nickname-collision `pair` refusal is branchable instead of
1542/// `-32000`, so an embedder writes its own recovery copy rather than substring-matching ours. The
1543/// prose changed with it: it named the `set_nickname` CONTROL VERB as the remedy, which a GUI user
1544/// cannot type, and the refusal is generated inviter-side so the embedder displaying it could not
1545/// rewrite it (#147).
1546///
1547/// **Not every semantic change gets a minor, and that is the gap to watch (#122).** A minor marks a
1548/// change to this *surface*. A change to behaviour BEHIND the surface — same fields, same shapes,
1549/// different meaning — may not bump it, and is invisible to a type diff. 17 and 24 above happen to
1550/// be that class and did bump; do not infer from them that every such change will. When bumping
1551/// several minors at once, read this block end to end AND the release notes, not the diff.
1552///
1553/// That class is bigger than it looks: **10, 17, 21, 22, 23 and 24 all shipped with no change to
1554/// any type in this file** — they moved meaning, not shape. Six of the thirty. A downstream
1555/// that diffs types across a multi-minor bump sees nothing for any of them.
1556pub const API_MINOR: u32 = 31;
1557
1558#[cfg(test)]
1559mod tests {
1560    use super::*;
1561
1562    /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
1563    /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
1564    /// privacy guarantee that daemon never made.
1565    #[test]
1566    fn peer_path_tags_and_defaults_to_unknown() {
1567        let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
1568        assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
1569        assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
1570        let relay = tagged(PeerPath::Relay {
1571            url: Some("https://relay.example/".into()),
1572        });
1573        assert_eq!(relay["kind"], "relay");
1574        assert_eq!(relay["url"], "https://relay.example/");
1575        // A relay whose URL we do not know still tags as relay, with the key elided.
1576        let bare = tagged(PeerPath::Relay { url: None });
1577        assert_eq!(bare["kind"], "relay");
1578        assert!(bare.get("url").is_none(), "elided, not null: {bare}");
1579
1580        // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
1581        // row. Without `#[serde(other)]` an unknown `kind` errors out of
1582        // `PeerReachability` entirely, so one new variant would break every `status` read an
1583        // older pinned client does.
1584        let future: PeerPath =
1585            serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
1586        assert_eq!(future, PeerPath::Unknown);
1587        let row: PeerReachability = serde_json::from_value(serde_json::json!({
1588            "name": "bob", "reachable": true, "path": {"kind": "quantum"}
1589        }))
1590        .expect("an unknown path kind must not fail the whole row");
1591        assert_eq!(row.path, PeerPath::Unknown);
1592        assert!(row.reachable, "the rest of the row survives");
1593
1594        // A pre-#64 row: no `path` key.
1595        let old = serde_json::json!({"name": "bob", "reachable": true});
1596        let parsed: PeerReachability = serde_json::from_value(old).unwrap();
1597        assert_eq!(
1598            parsed.path,
1599            PeerPath::Unknown,
1600            "an older daemon's row must never imply a direct path"
1601        );
1602    }
1603
1604    /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
1605    /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
1606    /// consumer projects both through one code path.
1607    #[test]
1608    fn reachability_frame_tags_and_round_trips() {
1609        let frame = StreamFrame::Reachability {
1610            peer: PeerReachability {
1611                name: "bob".into(),
1612                reachable: true,
1613                rtt_ms: Some(12),
1614                age_secs: Some(0),
1615                meta: String::new(),
1616                principal: Some("eid:beef".into()),
1617                path: Default::default(),
1618            },
1619            source: ReachabilitySource::Probe,
1620        };
1621        let v = serde_json::to_value(&frame).unwrap();
1622        assert_eq!(v["type"], "reachability");
1623        assert_eq!(v["peer"]["name"], "bob");
1624        assert_eq!(v["peer"]["reachable"], true);
1625        assert_eq!(
1626            v["peer"]["age_secs"], 0,
1627            "a transition frame is fresh by construction: {v}"
1628        );
1629        assert_eq!(v["source"], "probe", "#150: the producer is named: {v}");
1630        let back: StreamFrame = serde_json::from_value(v).unwrap();
1631        assert_eq!(back, frame);
1632    }
1633
1634    /// #150: the frame's `source` wire shape, and the two ways it must degrade.
1635    ///
1636    /// The default is the load-bearing part. An absent key comes from a daemon at `api_minor`
1637    /// 22–29, which ALREADY has both producers — so it must land on `Unknown`, never on `Probe`.
1638    /// Defaulting to `Probe` would tell a consumer "a throwaway dial saw this" about frames that
1639    /// were a live session degrading, which is the ambiguity the field exists to remove.
1640    #[test]
1641    fn reachability_source_tags_and_defaults_to_unknown() {
1642        let tagged = |s: ReachabilitySource| serde_json::to_value(s).unwrap();
1643        assert_eq!(tagged(ReachabilitySource::Probe), "probe");
1644        assert_eq!(tagged(ReachabilitySource::Session), "session");
1645        assert_eq!(tagged(ReachabilitySource::Unknown), "unknown");
1646        for s in [
1647            ReachabilitySource::Probe,
1648            ReachabilitySource::Session,
1649            ReachabilitySource::Unknown,
1650        ] {
1651            let back: ReachabilitySource = serde_json::from_value(tagged(s)).unwrap();
1652            assert_eq!(back, s, "round trip");
1653        }
1654
1655        let peer = serde_json::json!({"name": "bob", "reachable": true});
1656
1657        // A pre-#150 frame: no `source` key at all.
1658        let old: StreamFrame =
1659            serde_json::from_value(serde_json::json!({"type": "reachability", "peer": peer}))
1660                .expect("an older daemon's frame must still parse");
1661        let StreamFrame::Reachability { source, .. } = old else {
1662            panic!("expected a reachability frame");
1663        };
1664        assert_eq!(
1665            source,
1666            ReachabilitySource::Unknown,
1667            "an api_minor 22-29 daemon has BOTH producers, so an absent key must not claim Probe"
1668        );
1669
1670        // A producer from a NEWER daemon must degrade to Unknown, not fail the whole frame — the
1671        // same stake `PeerPath` buys with `#[serde(other)]`. Without the hand-written Deserialize
1672        // a third producer would break every Reachability frame an older pinned client reads.
1673        let future: StreamFrame = serde_json::from_value(
1674            serde_json::json!({"type": "reachability", "peer": peer, "source": "telemetry"}),
1675        )
1676        .expect("an unknown producer must not fail the whole frame");
1677        let StreamFrame::Reachability { source, peer } = future else {
1678            panic!("expected a reachability frame");
1679        };
1680        assert_eq!(source, ReachabilitySource::Unknown);
1681        assert!(peer.reachable, "the rest of the frame survives");
1682    }
1683
1684    /// #150 gate: "an unrecognized value reads as `unknown`" must hold for any VALUE, not just an
1685    /// unrecognized string.
1686    ///
1687    /// `#[serde(default)]` covers an absent key and nothing else, so `"source": null` — what a
1688    /// proxy or non-Rust daemon that normalizes optional fields produces — went through the
1689    /// deserializer and failed the WHOLE frame, silently dropping a liveness transition while the
1690    /// protocol doc promised the field could not break a parse. The container shapes matter
1691    /// separately: a visitor that answers without draining a map/seq desynchronizes the parser and
1692    /// fails the frame anyway, which looks identical from outside.
1693    #[test]
1694    fn a_malformed_source_degrades_instead_of_failing_the_frame() {
1695        let peer = serde_json::json!({"name": "bob", "reachable": true});
1696        for bad in [
1697            serde_json::Value::Null,
1698            serde_json::json!(7),
1699            serde_json::json!(-1),
1700            serde_json::json!(1.5),
1701            serde_json::json!(true),
1702            serde_json::json!({"kind": "probe", "nested": {"deep": [1, 2]}}),
1703            serde_json::json!(["probe", "session"]),
1704        ] {
1705            let frame: StreamFrame = serde_json::from_value(
1706                serde_json::json!({"type": "reachability", "peer": peer, "source": bad}),
1707            )
1708            .unwrap_or_else(|e| panic!("`source: {bad}` must not fail the whole frame: {e}"));
1709            let StreamFrame::Reachability { source, peer } = frame else {
1710                panic!("expected a reachability frame");
1711            };
1712            assert_eq!(source, ReachabilitySource::Unknown, "for source: {bad}");
1713            assert!(peer.reachable, "the rest of the frame survives: {bad}");
1714        }
1715    }
1716
1717    /// #90: the self-network frame tags as `{"type":"self_network","self_network":{…}}` — the
1718    /// SAME block `status` and the snapshot carry. Pinned explicitly (like the reachability
1719    /// tag) so a variant rename cannot slip past a suite whose two ends share the type while
1720    /// breaking every doc-following third-party client.
1721    #[test]
1722    fn self_network_frame_tags_and_round_trips() {
1723        let frame = StreamFrame::SelfNetwork {
1724            self_network: SelfNetwork {
1725                online: true,
1726                home_relay: Some("https://relay.example:443".into()),
1727                relays: vec![RelayInfo {
1728                    url: "https://relay.example:443".into(),
1729                    connected: true,
1730                }],
1731                direct_addrs: vec!["192.168.1.2:4444".into()],
1732                last_change_epoch: Some(1_753_842_000),
1733            },
1734        };
1735        let v = serde_json::to_value(&frame).unwrap();
1736        assert_eq!(v["type"], "self_network");
1737        assert_eq!(v["self_network"]["online"], true);
1738        assert_eq!(v["self_network"]["home_relay"], "https://relay.example:443");
1739        assert_eq!(v["self_network"]["relays"][0]["connected"], true);
1740        let back: StreamFrame = serde_json::from_value(v).unwrap();
1741        assert_eq!(back, frame);
1742    }
1743
1744    #[test]
1745    fn peer_reachability_serde_is_additive() {
1746        let r = PeerReachability {
1747            name: "bob".into(),
1748            reachable: true,
1749            rtt_ms: Some(42),
1750            age_secs: Some(3),
1751            meta: String::new(),
1752            principal: None,
1753            path: Default::default(),
1754        };
1755        let v = serde_json::to_value(&r).unwrap();
1756        assert_eq!(v["name"], "bob");
1757        assert_eq!(v["reachable"], true);
1758        assert_eq!(v["rtt_ms"], 42);
1759        assert_eq!(v["age_secs"], 3);
1760        // Never-probed peer: optionals elided, not null.
1761        let unknown = PeerReachability {
1762            name: "carol".into(),
1763            reachable: false,
1764            rtt_ms: None,
1765            age_secs: None,
1766            meta: String::new(),
1767            principal: None,
1768            path: Default::default(),
1769        };
1770        let uv = serde_json::to_value(&unknown).unwrap();
1771        assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
1772        // An older StatusResult (no reachability field) still deserializes.
1773        let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
1774        let s: StatusResult = serde_json::from_value(old).unwrap();
1775        assert!(s.reachability.is_empty());
1776    }
1777
1778    #[test]
1779    fn subscribe_method_tag_resolves() {
1780        let req = serde_json::to_value(Request::Subscribe).unwrap();
1781        assert_eq!(method_of(&req), Some("subscribe"));
1782    }
1783
1784    // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
1785
1786    #[test]
1787    fn invite_params_reject_singular_service_typo() {
1788        // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
1789        // InviteParams { services: [] } and mint a grants-nothing invite that looked
1790        // successful. With deny_unknown_fields the typo is a loud parse error instead.
1791        let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
1792        assert!(
1793            err.is_err(),
1794            "an unknown `service` key must be rejected, not silently ignored"
1795        );
1796        // The correct plural shape still parses.
1797        let ok: InviteParams =
1798            serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
1799        assert_eq!(ok.services, vec!["kb".to_string()]);
1800    }
1801
1802    #[test]
1803    fn open_session_params_reject_unknown_field() {
1804        let err = serde_json::from_value::<OpenSessionParams>(
1805            serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
1806        );
1807        assert!(err.is_err(), "unknown params keys must be rejected");
1808    }
1809
1810    #[test]
1811    fn set_app_metadata_request_carries_the_method_tag() {
1812        let r = Request::SetAppMetadata(SetAppMetadataParams {
1813            metadata: "v=1.2.3".into(),
1814        });
1815        let v = serde_json::to_value(&r).unwrap();
1816        assert_eq!(v["method"], "set_app_metadata");
1817        assert_eq!(v["params"]["metadata"], "v=1.2.3");
1818        assert_eq!(method_of(&v), Some("set_app_metadata"));
1819    }
1820
1821    #[test]
1822    fn set_app_metadata_params_reject_unknown_field() {
1823        let err = serde_json::from_value::<SetAppMetadataParams>(
1824            serde_json::json!({"metadata": "x", "nonsense": 1}),
1825        );
1826        assert!(err.is_err(), "unknown params keys must be rejected");
1827    }
1828
1829    /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1830    /// empty meta does not serialize.
1831    #[test]
1832    fn peer_info_principal_is_additive() {
1833        // An older payload (no principal) still deserializes; empty does not serialize.
1834        let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1835        let p: PeerInfo = serde_json::from_value(old).unwrap();
1836        assert_eq!(p.principal, None);
1837        assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1838        // A bound peer carries BOTH the person user_id AND the device principal (#41).
1839        let full = PeerInfo {
1840            name: "bob".into(),
1841            services: vec!["notes".into()],
1842            user_id: Some("b64u:BOB".into()),
1843            principal: Some("eid:0707".into()),
1844        };
1845        let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1846        assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1847        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1848    }
1849
1850    #[test]
1851    fn active_session_principal_is_additive() {
1852        // An OLD payload (no `principal`) must still deserialize — #73 is additive.
1853        let old: ActiveSession =
1854            serde_json::from_str(r#"{"peer":"bob","service":"notes","opened_at":7}"#).unwrap();
1855        assert_eq!(old.principal, None, "serde(default) supplies it");
1856
1857        // And a `None` must not serialize, so an old client sees the shape it expects.
1858        let json = serde_json::to_string(&old).unwrap();
1859        assert!(
1860            !json.contains("principal"),
1861            "skip_serializing_if must omit it: {json}"
1862        );
1863
1864        // A real row round-trips the principal.
1865        let new = ActiveSession {
1866            peer: "bob".into(),
1867            service: "notes".into(),
1868            opened_at: 7,
1869            principal: Some("eid:1f0a".into()),
1870        };
1871        let back: ActiveSession =
1872            serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap();
1873        assert_eq!(back.principal.as_deref(), Some("eid:1f0a"));
1874    }
1875
1876    #[test]
1877    fn peer_reachability_principal_is_additive() {
1878        // Older payload (no principal) still deserializes; empty does not serialize; a set
1879        // value round-trips alongside the #40 meta so an embedder joins on the principal.
1880        let old = serde_json::json!({"name": "bob", "reachable": true});
1881        let r: PeerReachability = serde_json::from_value(old).unwrap();
1882        assert_eq!(r.principal, None);
1883        assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1884        let full = PeerReachability {
1885            name: "bob".into(),
1886            reachable: true,
1887            rtt_ms: Some(12),
1888            age_secs: Some(3),
1889            meta: "v=1.2.3".into(),
1890            principal: Some("eid:0707".into()),
1891            path: Default::default(),
1892        };
1893        let back: PeerReachability =
1894            serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1895        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1896        assert_eq!(back.meta, "v=1.2.3");
1897    }
1898
1899    #[test]
1900    fn peer_reachability_meta_is_additive() {
1901        // An older payload (no meta) still deserializes; an empty meta does not serialize.
1902        let old = serde_json::json!({"name": "bob", "reachable": true});
1903        let r: PeerReachability = serde_json::from_value(old).unwrap();
1904        assert_eq!(r.meta, "");
1905        assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1906        // A set value round-trips.
1907        let with = PeerReachability {
1908            name: "bob".into(),
1909            reachable: true,
1910            rtt_ms: Some(12),
1911            age_secs: Some(3),
1912            meta: "v=1.2.3".into(),
1913            principal: None,
1914            path: Default::default(),
1915        };
1916        let back: PeerReachability =
1917            serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1918        assert_eq!(back.meta, "v=1.2.3");
1919    }
1920
1921    #[test]
1922    fn presence_peer_meta_is_additive() {
1923        let old = serde_json::json!({
1924            "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1925        });
1926        let p: PresencePeer = serde_json::from_value(old).unwrap();
1927        assert_eq!(p.meta, "");
1928        assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1929    }
1930
1931    #[test]
1932    fn set_nickname_request_carries_the_method_tag() {
1933        let r = Request::SetNickname(SetNicknameParams {
1934            nickname: "workbench".into(),
1935        });
1936        let v = serde_json::to_value(&r).unwrap();
1937        assert_eq!(v["method"], "set_nickname");
1938        assert_eq!(v["params"]["nickname"], "workbench");
1939        assert_eq!(method_of(&v), Some("set_nickname"));
1940    }
1941
1942    #[test]
1943    fn set_nickname_params_reject_unknown_field() {
1944        let err = serde_json::from_value::<SetNicknameParams>(
1945            serde_json::json!({"nickname": "x", "nonsense": 1}),
1946        );
1947        assert!(err.is_err(), "unknown params keys must be rejected");
1948    }
1949
1950    /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1951    /// the additive-only contract — and an empty name must not serialize at all.
1952    #[test]
1953    fn status_self_nickname_is_additive() {
1954        let old = serde_json::json!({
1955            "stack_version": "0.7.0", "services": [], "peers": []
1956        });
1957        let s: StatusResult = serde_json::from_value(old).unwrap();
1958        assert_eq!(s.self_nickname, "");
1959        let v = serde_json::to_value(&s).unwrap();
1960        assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1961    }
1962
1963    #[test]
1964    fn api_minor_is_present_and_monotonic_from_hello() {
1965        // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1966        // crate/stack version, additive on the Hello frame.
1967        let h = Hello {
1968            api: API_NAME.into(),
1969            api_version: API_VERSION.into(),
1970            api_minor: API_MINOR,
1971            stack_version: "9.9.9".into(),
1972        };
1973        let v = serde_json::to_value(&h).unwrap();
1974        assert_eq!(v["api_minor"], API_MINOR);
1975        // An OLD Hello without api_minor still deserializes (additive contract).
1976        let old = serde_json::json!({
1977            "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1978        });
1979        let back: Hello = serde_json::from_value(old).unwrap();
1980        assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1981    }
1982
1983    #[test]
1984    fn hello_result_roundtrips() {
1985        let h = Hello {
1986            api: "mcpmesh-local/1".into(),
1987            api_version: "1.0".into(),
1988            api_minor: 0,
1989            stack_version: "0.1.0".into(),
1990        };
1991        let v = serde_json::to_value(&h).unwrap();
1992        assert_eq!(v["api"], "mcpmesh-local/1");
1993        let back: Hello = serde_json::from_value(v).unwrap();
1994        assert_eq!(back, h);
1995    }
1996
1997    #[test]
1998    fn request_tagged_by_method() {
1999        let r = Request::Status;
2000        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
2001        let r = Request::OpenSession(OpenSessionParams {
2002            peer: "alice".into(),
2003            service: "notes".into(),
2004        });
2005        let v = serde_json::to_value(&r).unwrap();
2006        assert_eq!(v["method"], "open_session");
2007        assert_eq!(v["params"]["peer"], "alice");
2008    }
2009
2010    #[test]
2011    fn parameterless_method_tolerates_params_forms() {
2012        // Omitted and null params deserialize straight into the unit variant.
2013        let omitted: Request =
2014            serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
2015        assert_eq!(omitted, Request::Status);
2016        let null: Request =
2017            serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
2018                .unwrap();
2019        assert_eq!(null, Request::Status);
2020
2021        // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
2022        // the server MUST dispatch on the method string rather than deserialize the whole
2023        // message into `Request`. This is the pattern the daemon's dispatcher uses.
2024        let empty = serde_json::json!({"method": "status", "params": {}});
2025        assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
2026        match method_of(&empty) {
2027            Some("status") => {} // dispatcher resolves Status via the method string
2028            other => panic!("method_of failed to resolve status: {other:?}"),
2029        }
2030    }
2031
2032    #[test]
2033    fn backend_spec_roundtrips() {
2034        let run = BackendSpec::Run {
2035            cmd: vec!["notes-mcp".into(), "--stdio".into()],
2036            env: Default::default(),
2037            cwd: None,
2038        };
2039        let v = serde_json::to_value(&run).unwrap();
2040        assert_eq!(v["run"]["cmd"][0], "notes-mcp");
2041        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
2042
2043        let sock = BackendSpec::Socket {
2044            path: "/run/notes.sock".into(),
2045        };
2046        let v = serde_json::to_value(&sock).unwrap();
2047        assert_eq!(v["socket"]["path"], "/run/notes.sock");
2048        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
2049    }
2050
2051    #[test]
2052    fn register_service_wire_shape() {
2053        let r = Request::RegisterService(RegisterServiceParams {
2054            name: "notes".into(),
2055            backend: BackendSpec::Run {
2056                cmd: vec!["notes-mcp".into()],
2057                env: Default::default(),
2058                cwd: None,
2059            },
2060            allow: vec!["alice".into()],
2061            ephemeral: false,
2062        });
2063        let v = serde_json::to_value(&r).unwrap();
2064        assert_eq!(
2065            v,
2066            serde_json::json!({
2067                "method": "register_service",
2068                "params": {
2069                    "name": "notes",
2070                    "backend": {"run": {"cmd": ["notes-mcp"]}},
2071                    "allow": ["alice"],
2072                }
2073            })
2074        );
2075        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2076    }
2077
2078    #[test]
2079    fn invite_request_and_result_roundtrip() {
2080        // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
2081        let r = Request::Invite(InviteParams {
2082            services: vec!["notes".into(), "kb".into()],
2083            app_label: None,
2084        });
2085        let v = serde_json::to_value(&r).unwrap();
2086        assert_eq!(v["method"], "invite");
2087        assert_eq!(v["params"]["services"][0], "notes");
2088        assert_eq!(v["params"]["services"][1], "kb");
2089        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2090        // method_of resolves the tag generically (no per-variant arm).
2091        assert_eq!(
2092            method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
2093            Some("invite")
2094        );
2095
2096        // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
2097        let res = InviteResult {
2098            invite_line: "mcpmesh-invite:ABCDEF".into(),
2099            expires_at_epoch: 1_800_000_000,
2100        };
2101        let v = serde_json::to_value(&res).unwrap();
2102        assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
2103        assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
2104        assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
2105    }
2106
2107    #[test]
2108    fn pair_request_and_result_roundtrip() {
2109        // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
2110        let r = Request::Pair(PairParams {
2111            invite_line: "mcpmesh-invite:ABCDEF".into(),
2112        });
2113        let v = serde_json::to_value(&r).unwrap();
2114        assert_eq!(v["method"], "pair");
2115        assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
2116        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2117        // method_of resolves the tag generically (no per-variant arm).
2118        assert_eq!(
2119            method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
2120            Some("pair")
2121        );
2122
2123        // PairResult carries the inviter's suggested nickname + the display-only SAS words +
2124        // the granted services (the porcelain renders each as `<peer>/<service>`).
2125        let res = PairResult {
2126            peer_nickname: "alice".into(),
2127            sas_code: "tango-fig-cabbage".into(),
2128            services: vec!["notes".into(), "kb".into()],
2129            app_label: None,
2130            peer_user_id: None,
2131        };
2132        let v = serde_json::to_value(&res).unwrap();
2133        assert_eq!(v["peer_nickname"], "alice");
2134        assert_eq!(v["sas_code"], "tango-fig-cabbage");
2135        assert_eq!(v["services"][0], "notes");
2136        assert_eq!(v["services"][1], "kb");
2137        assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
2138
2139        // Additive-only: a PairResult minted by an older daemon (no `services` key) still
2140        // deserializes — the `#[serde(default)]` fills it with an empty list.
2141        let old_shape = serde_json::json!({
2142            "peer_nickname": "alice",
2143            "sas_code": "tango-fig-cabbage",
2144        });
2145        let back: PairResult = serde_json::from_value(old_shape).unwrap();
2146        assert_eq!(back.peer_nickname, "alice");
2147        assert!(back.services.is_empty());
2148    }
2149
2150    #[test]
2151    fn roster_install_request_and_result_roundtrip() {
2152        // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
2153        // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
2154        let r = Request::RosterInstall(RosterInstallParams {
2155            path: "/tmp/roster.json".into(),
2156            org_root_pk: Some("b64u:AAAA".into()),
2157        });
2158        let v = serde_json::to_value(&r).unwrap();
2159        assert_eq!(v["method"], "roster_install");
2160        assert_eq!(v["params"]["path"], "/tmp/roster.json");
2161        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
2162        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2163        // method_of resolves the tag generically (no per-variant arm).
2164        assert_eq!(
2165            method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
2166            Some("roster_install")
2167        );
2168
2169        // When the pk is omitted (a subsequent install using the pinned value), it is
2170        // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
2171        let omit = Request::RosterInstall(RosterInstallParams {
2172            path: "/tmp/roster.json".into(),
2173            org_root_pk: None,
2174        });
2175        let v = serde_json::to_value(&omit).unwrap();
2176        assert!(
2177            v["params"].get("org_root_pk").is_none(),
2178            "an omitted org_root_pk must not appear on the wire: {v}"
2179        );
2180        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
2181
2182        // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
2183        let res = RosterInstallResult {
2184            org_id: "acme".into(),
2185            serial: 42,
2186            severed: 1,
2187        };
2188        let v = serde_json::to_value(&res).unwrap();
2189        assert_eq!(v["org_id"], "acme");
2190        assert_eq!(v["serial"], 42u64);
2191        assert_eq!(v["severed"], 1u32);
2192        assert_eq!(
2193            serde_json::from_value::<RosterInstallResult>(v).unwrap(),
2194            res
2195        );
2196
2197        // Additive-only: a result minted by an older daemon (no `severed` key) still
2198        // deserializes — the `#[serde(default)]` fills it with 0.
2199        let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
2200        let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
2201        assert_eq!(back.serial, 7);
2202        assert_eq!(back.severed, 0);
2203    }
2204
2205    #[test]
2206    fn org_join_request_and_result_roundtrip() {
2207        // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
2208        // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
2209        let r = Request::OrgJoin(OrgJoinParams {
2210            org_id: "acme".into(),
2211            org_root_pk: "b64u:AAAA".into(),
2212            user_id: "alice".into(),
2213            user_key: "/home/alice/.config/mcpmesh/user.key".into(),
2214        });
2215        let v = serde_json::to_value(&r).unwrap();
2216        assert_eq!(v["method"], "org_join");
2217        assert_eq!(v["params"]["org_id"], "acme");
2218        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
2219        assert_eq!(v["params"]["user_id"], "alice");
2220        assert_eq!(
2221            v["params"]["user_key"],
2222            "/home/alice/.config/mcpmesh/user.key"
2223        );
2224        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2225        // method_of resolves the tag generically (no per-variant arm).
2226        assert_eq!(
2227            method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
2228            Some("org_join")
2229        );
2230
2231        // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
2232        let res = OrgJoinResult {
2233            org_id: "acme".into(),
2234        };
2235        let v = serde_json::to_value(&res).unwrap();
2236        assert_eq!(v["org_id"], "acme");
2237        assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
2238    }
2239
2240    #[test]
2241    fn set_roster_url_request_roundtrip() {
2242        // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
2243        let r = Request::SetRosterUrl(SetRosterUrlParams {
2244            url: "https://intranet.acme.com/roster.json".into(),
2245        });
2246        let v = serde_json::to_value(&r).unwrap();
2247        assert_eq!(v["method"], "set_roster_url");
2248        assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
2249        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2250        assert_eq!(
2251            method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
2252            Some("set_roster_url")
2253        );
2254    }
2255
2256    #[test]
2257    fn peer_remove_request_roundtrip() {
2258        // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
2259        let r = Request::PeerRemove(PeerRemoveParams {
2260            nickname: "bob".into(),
2261        });
2262        let v = serde_json::to_value(&r).unwrap();
2263        assert_eq!(v["method"], "peer_remove");
2264        assert_eq!(v["params"]["nickname"], "bob");
2265        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2266        // method_of resolves the tag generically (no per-variant arm).
2267        assert_eq!(
2268            method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
2269            Some("peer_remove")
2270        );
2271    }
2272
2273    /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
2274    /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
2275    /// defaulting to empty when absent.
2276    #[test]
2277    fn peer_add_request_roundtrip() {
2278        let r = Request::PeerAdd(PeerAddParams {
2279            nickname: "bob".into(),
2280            endpoint_id: "96246d3f".into(),
2281            allow: vec!["notes".into()],
2282        });
2283        let v = serde_json::to_value(&r).unwrap();
2284        assert_eq!(v["method"], "peer_add");
2285        assert_eq!(v["params"]["nickname"], "bob");
2286        assert_eq!(v["params"]["endpoint_id"], "96246d3f");
2287        assert_eq!(v["params"]["allow"][0], "notes");
2288        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2289        // An absent allow list deserializes to empty (the server-side tolerance).
2290        let p: PeerAddParams =
2291            serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
2292                .unwrap();
2293        assert!(p.allow.is_empty());
2294    }
2295
2296    #[test]
2297    fn peer_rename_request_roundtrip() {
2298        // By user_id (renames all of a person's devices in one op).
2299        let r = Request::PeerRename(PeerRenameParams {
2300            user_id: Some("b64u:BOB".into()),
2301            nickname: None,
2302            to: "Bobby".into(),
2303        });
2304        let v = serde_json::to_value(&r).unwrap();
2305        assert_eq!(v["method"], "peer_rename");
2306        assert_eq!(v["params"]["user_id"], "b64u:BOB");
2307        assert_eq!(v["params"]["to"], "Bobby");
2308        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2309        // A provisional contact is renamed by nickname; omitted user_id defaults to None.
2310        assert_eq!(
2311            method_of(
2312                &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
2313            ),
2314            Some("peer_rename")
2315        );
2316    }
2317
2318    #[test]
2319    fn status_result_roundtrips() {
2320        // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
2321        // older payload with no `roster` key still deserializes to None (serde default).
2322        let s = StatusResult {
2323            stack_version: "0.1.0".into(),
2324            services: vec![ServiceInfo {
2325                name: "notes".into(),
2326                allow: vec!["alice".into()],
2327                allow_display: vec![],
2328                backend: BackendKind::Run,
2329                ephemeral: false,
2330            }],
2331            peers: vec![PeerInfo {
2332                name: "alice".into(),
2333                services: vec!["notes".into()],
2334                // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
2335                user_id: Some("b64u:alicepk".into()),
2336                principal: None,
2337            }],
2338            roster: None,
2339            presence: vec![],
2340            self_user_id: Some("b64u:selfpk".into()),
2341            recent_pairings: vec![],
2342            reachability: vec![],
2343            self_nickname: String::new(),
2344            storage: None,
2345            self_network: None,
2346        };
2347        let v = serde_json::to_value(&s).unwrap();
2348        assert_eq!(v["services"][0]["backend"], "run");
2349        // The additive identity fields ride the wire when present.
2350        assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
2351        assert_eq!(v["self_user_id"], "b64u:selfpk");
2352        assert!(
2353            v.get("roster").is_none(),
2354            "an absent roster must not appear on the wire: {v}"
2355        );
2356        assert!(
2357            v.get("presence").is_none(),
2358            "an empty presence must not appear on the wire: {v}"
2359        );
2360        assert!(
2361            v.get("recent_pairings").is_none(),
2362            "an empty recent_pairings must not appear on the wire: {v}"
2363        );
2364        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
2365
2366        // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
2367        // deserializes — the identity fields default to None / a nickname-only peer.
2368        let old_shape = serde_json::json!({
2369            "stack_version": "0.1.0",
2370            "services": [],
2371            "peers": [{ "name": "bob", "services": [] }],
2372        });
2373        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
2374        assert!(back.roster.is_none());
2375        assert!(back.presence.is_empty());
2376        assert!(back.self_user_id.is_none());
2377        assert!(back.peers[0].user_id.is_none());
2378        assert!(back.recent_pairings.is_empty());
2379
2380        // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
2381        // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
2382        let s = StatusResult {
2383            stack_version: "0.1.0".into(),
2384            services: vec![],
2385            peers: vec![],
2386            roster: Some(RosterStatus {
2387                org_id: "acme".into(),
2388                serial: 42,
2389                state: "approved".into(),
2390                org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
2391            }),
2392            presence: vec![
2393                PresencePeer {
2394                    user_id: "alice".into(),
2395                    device_label: "laptop".into(),
2396                    role: "primary".into(),
2397                    online: true,
2398                    meta: String::new(),
2399                },
2400                PresencePeer {
2401                    user_id: "alice".into(),
2402                    device_label: "desktop".into(),
2403                    role: "mirror".into(),
2404                    online: false,
2405                    meta: String::new(),
2406                },
2407            ],
2408            self_user_id: None,
2409            recent_pairings: vec![],
2410            reachability: vec![],
2411            self_nickname: String::new(),
2412            storage: None,
2413            self_network: None,
2414        };
2415        let v = serde_json::to_value(&s).unwrap();
2416        assert_eq!(v["roster"]["org_id"], "acme");
2417        assert_eq!(v["roster"]["serial"], 42u64);
2418        assert_eq!(v["roster"]["state"], "approved");
2419        assert_eq!(
2420            v["roster"]["org_root_fingerprint"],
2421            "tango-fig-cabbage-anchor"
2422        );
2423        assert_eq!(v["presence"][0]["user_id"], "alice");
2424        assert_eq!(v["presence"][0]["device_label"], "laptop");
2425        assert_eq!(v["presence"][0]["role"], "primary");
2426        assert_eq!(v["presence"][0]["online"], true);
2427        assert_eq!(v["presence"][1]["online"], false);
2428        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
2429    }
2430
2431    /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
2432    /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
2433    /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
2434    /// older daemon (no key at all) still deserializes to empty.
2435    #[test]
2436    fn recent_pairings_are_additive_on_status() {
2437        let s = StatusResult {
2438            stack_version: "0.1.0".into(),
2439            services: vec![],
2440            peers: vec![],
2441            roster: None,
2442            presence: vec![],
2443            self_user_id: None,
2444            recent_pairings: vec![RecentPairing {
2445                peer_nickname: "bob".into(),
2446                sas_code: "tango-fig-cabbage".into(),
2447                paired_at_epoch: 1_800_000_000,
2448            }],
2449            reachability: vec![],
2450            self_nickname: String::new(),
2451            storage: None,
2452            self_network: None,
2453        };
2454        let v = serde_json::to_value(&s).unwrap();
2455        assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
2456        assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
2457        assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
2458        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
2459
2460        // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
2461        // the `#[serde(default)]` fills it with an empty list.
2462        let old_shape = serde_json::json!({
2463            "stack_version": "0.1.0",
2464            "services": [],
2465            "peers": [],
2466        });
2467        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
2468        assert!(back.recent_pairings.is_empty());
2469    }
2470
2471    #[test]
2472    fn blob_requests_and_results_roundtrip() {
2473        // BlobPublish → { method, params: { scope, path } }.
2474        let r = Request::BlobPublish(BlobPublishParams {
2475            scope: "docs".into(),
2476            path: "/tmp/a.bin".into(),
2477        });
2478        let v = serde_json::to_value(&r).unwrap();
2479        assert_eq!(v["method"], "blob_publish");
2480        assert_eq!(v["params"]["scope"], "docs");
2481        assert_eq!(v["params"]["path"], "/tmp/a.bin");
2482        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2483
2484        // BlobGrant → { method, params: { scope, principal } }.
2485        // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
2486        // would otherwise ship undetected — the e2e test calls the provider directly and never
2487        // crosses JSON-RPC.
2488        let rev = Request::BlobRevoke(BlobRevokeParams {
2489            scope: "photos".into(),
2490            principals: vec!["alice".into()],
2491        });
2492        let v = serde_json::to_value(&rev).unwrap();
2493        assert_eq!(v["method"], "blob_revoke");
2494        assert_eq!(v["params"]["principals"][0], "alice");
2495        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
2496
2497        let unp = Request::BlobUnpublish(BlobUnpublishParams {
2498            scope: "photos".into(),
2499            hash: "abc123".into(),
2500        });
2501        let v = serde_json::to_value(&unp).unwrap();
2502        assert_eq!(v["method"], "blob_unpublish");
2503        assert_eq!(v["params"]["hash"], "abc123");
2504        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
2505
2506        let r = Request::BlobGrant(BlobGrantParams {
2507            scope: "docs".into(),
2508            principal: "alice".into(),
2509        });
2510        let v = serde_json::to_value(&r).unwrap();
2511        assert_eq!(v["method"], "blob_grant");
2512        assert_eq!(v["params"]["principal"], "alice");
2513        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2514
2515        // BlobList is parameterless (method_of resolves it).
2516        assert_eq!(
2517            method_of(&serde_json::json!({"method": "blob_list"})),
2518            Some("blob_list")
2519        );
2520
2521        // BlobFetch → { method, params: { ticket, dest_path } }.
2522        let r = Request::BlobFetch(BlobFetchParams {
2523            ticket: "blobAAA".into(),
2524            dest_path: "/tmp/out.bin".into(),
2525        });
2526        let v = serde_json::to_value(&r).unwrap();
2527        assert_eq!(v["method"], "blob_fetch");
2528        assert_eq!(v["params"]["ticket"], "blobAAA");
2529        assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
2530        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2531
2532        // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
2533        let res = BlobPublishResult {
2534            ticket: "blobAAA".into(),
2535            hash: "ab".repeat(32),
2536        };
2537        let v = serde_json::to_value(&res).unwrap();
2538        assert_eq!(v["ticket"], "blobAAA");
2539        assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
2540
2541        // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
2542        let res = BlobScopeList {
2543            scopes: vec![ScopeInfo {
2544                name: "docs".into(),
2545                hashes: vec!["ab".repeat(32)],
2546                grants: vec!["alice".into()],
2547                withdrawn: vec![],
2548                hash_count: 1,
2549                grant_count: 1,
2550                withdrawn_count: 0,
2551            }],
2552            total: 1,
2553            truncated: false,
2554        };
2555        let v = serde_json::to_value(&res).unwrap();
2556        assert_eq!(v["scopes"][0]["name"], "docs");
2557        assert_eq!(v["scopes"][0]["grants"][0], "alice");
2558        assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
2559
2560        // BlobFetchResult carries the verified hash + byte length.
2561        let res = BlobFetchResult {
2562            hash: "ab".repeat(32),
2563            bytes_len: 4194304,
2564        };
2565        let v = serde_json::to_value(&res).unwrap();
2566        assert_eq!(v["bytes_len"], 4194304u64);
2567        assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
2568    }
2569
2570    /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
2571    /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
2572    /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
2573    /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
2574    #[test]
2575    fn stream_frames_roundtrip_with_the_documented_tags() {
2576        let snap = StreamFrame::Snapshot {
2577            self_network: None,
2578            active_sessions: vec![ActiveSession {
2579                peer: "bob".into(),
2580                service: "notes".into(),
2581                opened_at: 1_751_760_000,
2582                principal: None,
2583            }],
2584            reachability: vec![PeerReachability {
2585                name: "bob".into(),
2586                reachable: true,
2587                rtt_ms: Some(42),
2588                age_secs: Some(3),
2589                meta: String::new(),
2590                principal: None,
2591                path: Default::default(),
2592            }],
2593        };
2594        let v = serde_json::to_value(&snap).unwrap();
2595        assert_eq!(v["type"], "snapshot");
2596        assert_eq!(v["active_sessions"][0]["peer"], "bob");
2597        assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
2598        assert_eq!(v["reachability"][0]["name"], "bob");
2599        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
2600
2601        let event = StreamFrame::Event {
2602            record: Box::new(AuditRecord::session_open(
2603                "2026-07-03T14:02:11.480Z".into(),
2604                Some("bob".into()),
2605                "notes".into(),
2606                None,
2607            )),
2608        };
2609        let v = serde_json::to_value(&event).unwrap();
2610        assert_eq!(v["type"], "event");
2611        // The record's fields ride verbatim under `record` — no Box indirection on the wire.
2612        assert_eq!(v["record"]["kind"], "session_open");
2613        assert_eq!(v["record"]["peer"], "bob");
2614        assert_eq!(v["record"]["service"], "notes");
2615        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
2616
2617        let lagged = StreamFrame::Lagged { dropped: 12 };
2618        let v = serde_json::to_value(&lagged).unwrap();
2619        assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
2620        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
2621    }
2622
2623    /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
2624    /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
2625    /// raw `Value` stream instead (`ControlClient::open_stream`).
2626    #[test]
2627    fn unknown_stream_frame_type_is_rejected() {
2628        let future = serde_json::json!({ "type": "future_kind", "x": 1 });
2629        assert!(serde_json::from_value::<StreamFrame>(future).is_err());
2630    }
2631
2632    #[test]
2633    fn audit_summary_request_and_result_roundtrip() {
2634        // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
2635        // tolerates omitted/null params; the server dispatches on the method string (method_of).
2636        let r = Request::AuditSummary;
2637        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
2638        assert_eq!(
2639            method_of(&serde_json::json!({"method": "audit_summary"})),
2640            Some("audit_summary")
2641        );
2642
2643        // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
2644        // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
2645        // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
2646        let res = AuditSummaryResult {
2647            per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
2648            per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
2649            total_sessions: 4,
2650        };
2651        let v = serde_json::to_value(&res).unwrap();
2652        assert_eq!(v["per_peer"][1][0], "bob");
2653        assert_eq!(v["per_peer"][1][1], 2u64);
2654        assert_eq!(v["per_service"][1][0], "notes");
2655        assert_eq!(v["total_sessions"], 4u64);
2656        assert_eq!(
2657            serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
2658            res
2659        );
2660
2661        // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
2662        // deserializes — the `#[serde(default)]` fills it with 0.
2663        let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
2664        let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
2665        assert_eq!(back.total_sessions, 0);
2666        assert!(back.per_peer.is_empty());
2667    }
2668}