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