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    /// The org's DECLARED group namespace, in roster document order (#93). `api_minor >= 46`.
299    ///
300    /// The set an `allow` entry may name — a roster is refused if any user carries a group outside
301    /// it — so this is what a UI offers when assigning membership. Without it an embedder in roster
302    /// mode had managed group membership it could not enumerate, and the only way to learn the
303    /// groups was to hand-parse the daemon-owned `roster.json`.
304    ///
305    /// Display/authoring input, never an authorization answer: naming a group grants nothing.
306    /// Additive — a payload from an older daemon reads as an empty list.
307    #[serde(default, skip_serializing_if = "Vec::is_empty")]
308    pub groups: Vec<String>,
309}
310
311/// One reachable roster peer device as reported by `status` (the advisory presence read).
312/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
313/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
314/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
315#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
316pub struct PresencePeer {
317    pub user_id: String,
318    /// The person's human display name from the roster (#93). `api_minor >= 46`.
319    ///
320    /// `user_id` is an authorization handle; this is what a UI puts next to a face. The roster
321    /// carried it all along and the control seam dropped it, so an embedder had a presence list it
322    /// could only label with an opaque id. Display-only — never an authz input.
323    ///
324    /// Additive: absent from an older daemon's payload, and empty when the roster's own field is.
325    #[serde(default, skip_serializing_if = "String::is_empty")]
326    pub display_name: String,
327    /// The groups this person belongs to (#93). `api_minor >= 46`.
328    ///
329    /// The same strings an `allow` entry names, so a UI can show why someone is admitted without
330    /// re-deriving it. Advisory display data: the gate reads the roster, never this. Additive.
331    #[serde(default, skip_serializing_if = "Vec::is_empty")]
332    pub groups: Vec<String>,
333    pub device_label: String,
334    pub role: String, // "primary" | "mirror" (roster vocabulary)
335    /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
336    pub online: bool,
337    /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
338    /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
339    /// data; never an authz input. Additive: default + skip-if-empty.
340    #[serde(default, skip_serializing_if = "String::is_empty")]
341    pub meta: String,
342}
343
344/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
345/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
346/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
347/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
348/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
349/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
350/// an epoch — never an EndpointId.
351#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
352pub struct RecentPairing {
353    /// The peer's nickname as stored by the inviter (its local name for the redeemer).
354    pub peer_nickname: String,
355    /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
356    /// `PairResult.sas_code` carried. Never checked programmatically.
357    pub sas_code: String,
358    /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
359    pub paired_at_epoch: u64,
360}
361
362#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
363pub struct StatusResult {
364    pub stack_version: String,
365    pub services: Vec<ServiceInfo>,
366    pub peers: Vec<PeerInfo>,
367    /// Roster-mode status, absent in a pure-pairing daemon. Additive:
368    /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
369    #[serde(default, skip_serializing_if = "Option::is_none")]
370    pub roster: Option<RosterStatus>,
371    /// The reachable roster peer devices (the advisory presence read), each with an `online`
372    /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
373    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
374    #[serde(default, skip_serializing_if = "Vec::is_empty")]
375    pub presence: Vec<PresencePeer>,
376    /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
377    /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
378    /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
379    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
380    #[serde(default, skip_serializing_if = "Option::is_none")]
381    pub self_user_id: Option<String>,
382    /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
383    /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
384    /// that has accepted no pairing since it started. Additive:
385    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
386    #[serde(default, skip_serializing_if = "Vec::is_empty")]
387    pub recent_pairings: Vec<RecentPairing>,
388    /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
389    /// first probe completes. Additive: default + skip-if-empty.
390    #[serde(default, skip_serializing_if = "Vec::is_empty")]
391    pub reachability: Vec<PeerReachability>,
392    /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
393    /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
394    /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
395    /// skip-if-empty so an older payload round-trips.
396    #[serde(default, skip_serializing_if = "String::is_empty")]
397    pub self_nickname: String,
398    /// On-disk footprint of this node's own state (#88), so an embedder can warn a user before
399    /// ENOSPC rather than after — the audit log's write rate is driven by inbound peer traffic,
400    /// and it shares a filesystem with `state.redb` and the device key. A LIVE read (computed
401    /// per `status` call), not a boot-time snapshot. `None` only in mesh-less control-only mode.
402    /// Additive: default + skip-if-none so an older payload round-trips.
403    #[serde(default, skip_serializing_if = "Option::is_none")]
404    pub storage: Option<StorageInfo>,
405    /// THIS node's own reachability posture (#90) — see [`SelfNetwork`]. Computed live per
406    /// call; `None` in mesh-less control-only mode. Additive: default + skip-if-none.
407    #[serde(default, skip_serializing_if = "Option::is_none")]
408    pub self_network: Option<SelfNetwork>,
409}
410
411/// The `status.self_network` block (#90): THIS node's own reachability posture — the first
412/// question in every "my message never arrived" investigation, previously unanswerable from
413/// either side of the API. Self-facing only: everything here is the node's own information
414/// (relay URLs come from its own config, sanitized; direct addresses already ride its invites).
415///
416/// `online` is iroh's own semantics — a home-relay connection is established. In
417/// `relay_mode = "disabled"` it is ALWAYS `false` with an empty `relays` list: that is a
418/// configuration, not an outage — render it as "LAN-only", never as a health warning.
419///
420/// Additive-only.
421///
422/// **`Default` is `{online: false, relays: []}` — which is exactly the shape above meaning
423/// "deliberately LAN-only" (#148).** The porcelain reads it that way and SUPPRESSES the "no relay
424/// connection" line for it. So a fixture built with `..Default::default()` claims a healthy
425/// LAN-only posture, not an unknown one. There is no third value for a `bool`; the honest way to
426/// say "nobody looked" is `StatusResult.self_network: None`, which is what a defaulted
427/// `StatusResult` gives you.
428#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
429pub struct SelfNetwork {
430    /// A home-relay connection is established (iroh's `online` definition). The signal #53's
431    /// `set_relays` never had: when this goes false on a relay-enabled node, the relay set is
432    /// the thing to look at.
433    pub online: bool,
434    /// The CONNECTED home relay's URL, sanitized to scheme + host + port (operator-supplied
435    /// relay URLs can carry userinfo tokens; `status` output gets screenshotted). `None` when
436    /// no relay is connected.
437    #[serde(default, skip_serializing_if = "Option::is_none")]
438    pub home_relay: Option<String>,
439    /// Every known home relay and its current connection state. Empty when no relays are
440    /// configured, or before the endpoint has selected any.
441    #[serde(default, skip_serializing_if = "Vec::is_empty")]
442    pub relays: Vec<RelayInfo>,
443    /// This endpoint's direct (non-relay) socket addresses — its own dialable coordinates.
444    #[serde(default, skip_serializing_if = "Vec::is_empty")]
445    pub direct_addrs: Vec<String>,
446    /// When the daemon's watcher last observed a TRANSITION (epoch seconds) — a change of
447    /// `online`, `home_relay`, or a relay's connection state; `direct_addrs` drift alone does
448    /// not stamp (nor emit a frame). OMITTED (not `null`) until the first observed transition
449    /// after boot, and from a point-in-time computation with no watcher running.
450    #[serde(default, skip_serializing_if = "Option::is_none")]
451    pub last_change_epoch: Option<i64>,
452    /// This node's `[network].presence_mode` (#89): `"paired"` | `"granted"` | `"off"` — who
453    /// currently gets an answer to the `mcpmesh/ping/1` reachability probe.
454    ///
455    /// Reported because the setting was otherwise **unobservable**: an operator who set it had no
456    /// way to confirm it took effect, and a product backing a privacy switch with it could not show
457    /// the user its real state. Always present from `api_minor >= 38`.
458    ///
459    /// **It is not "appear offline".** It withholds the pong payload and makes our own probe report
460    /// this node unreachable; it does not hide that the node is running (a QUIC application close
461    /// implies a completed handshake, and `mcpmesh/pair/1` answers any stranger by design). Do not
462    /// render it to users as invisibility.
463    #[serde(default, skip_serializing_if = "Option::is_none")]
464    pub presence_mode: Option<String>,
465    /// When the relay last reported that ANOTHER endpoint is presenting this node's identity
466    /// (#134, epoch seconds), or absent if never — the overwhelmingly common case.
467    ///
468    /// Two nodes booted from COPIES of one mesh root share an endpoint id. The relay can serve only
469    /// one, so the displaced node's peers simply go unreachable with nothing saying why; diagnosing
470    /// that cost a downstream real time. This is that missing "why".
471    ///
472    /// **Sticky, and a timestamp rather than a flag.** The condition is announced once, as the
473    /// displaced connection is dropped — it is not a state the relay keeps reporting — so a
474    /// self-clearing flag would read false by the time anyone called `status`. Judge staleness from
475    /// the epoch, exactly as with `last_change_epoch`.
476    ///
477    /// **Absence is not proof of uniqueness.** Detection needs an
478    /// `IdentityConflictLayer` in the process's `tracing` subscriber: the standalone daemon
479    /// installs one at boot, but an EMBEDDED node cannot (a subscriber is global and the host owns
480    /// it) and reports `None` until the host installs it. Never render absence as "identity
481    /// verified unique".
482    ///
483    /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`. `api_minor >= 32`.
484    #[serde(default, skip_serializing_if = "Option::is_none")]
485    pub identity_conflict_epoch: Option<i64>,
486}
487
488/// One home relay's connection state (#90). No latency — per-relay RTT needs iroh's
489/// `net_report`, which is unstable-feature-gated as of 1.0.3; `connected` is the stable truth.
490#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
491pub struct RelayInfo {
492    /// Sanitized (scheme + host + port), like `home_relay`.
493    pub url: String,
494    pub connected: bool,
495}
496
497/// The `status.storage` block (#88): bytes actually on disk, by subsystem. Counts, never
498/// content. Additive-only.
499///
500/// **`Default` is all zeros, which reads as "measured, and found empty" (#148).** It is here so a
501/// fixture can build one field and elide the rest; it is not a way to say "unmeasured". For that,
502/// leave `StatusResult.storage` as `None` — a defaulted `StatusResult` does exactly that.
503#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
504pub struct StorageInfo {
505    /// Summed sizes of the monthly audit files (`<state>/audit/*.jsonl`).
506    pub audit_bytes: u64,
507    /// Size of the peer/trust state store (`state.redb`).
508    pub redb_bytes: u64,
509    /// Total size under the app-blob store directory; 0 when no blob store exists.
510    pub blobs_bytes: u64,
511    /// Blob garbage collection (#80), or `None` when it is not configured — which is the default
512    /// and the behavior of every release up to 0.42.0.
513    ///
514    /// `None` means "not collecting", NOT "collecting and idle": a configured collector reports
515    /// `Some` with `runs: 0` until its first sweep.
516    #[serde(default, skip_serializing_if = "Option::is_none")]
517    pub blobs_gc: Option<BlobsGcInfo>,
518}
519
520/// The `status.storage.blobs_gc` block (#80): what the background app-blob collector has done.
521///
522/// **There is deliberately no `bytes_reclaimed`.** iroh-blobs calls back only BEFORE a sweep, never
523/// after, so any byte count here would be a guess. `blobs_bytes` is measured by walking the store
524/// directory; an operator reads reclaim off that, over time.
525#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
526pub struct BlobsGcInfo {
527    /// The interval the store is actually running on, in seconds.
528    pub interval_secs: u64,
529    /// Runs STARTED. iroh-blobs offers no completion callback, so this counts sweeps begun.
530    ///
531    /// **Watch this number.** Upstream's collector `break`s its loop on the first sweep error
532    /// rather than continuing, so one failure silently ends collection until the daemon restarts. A
533    /// `runs` that stops advancing across several intervals is the only signal that happened.
534    ///
535    /// Also: the collector SLEEPS before its first run, so a node with a 24h interval reports
536    /// `runs: 0` for its first 24 hours. That is not a fault.
537    pub runs: u64,
538    /// Unix seconds at the start of the most recent run; `None` before the first.
539    pub last_run_epoch: Option<i64>,
540    /// Hashes protected on the most recent run — the size of the liveness root the scope table
541    /// produced.
542    pub last_protected: u64,
543    /// Runs ABORTED because the liveness root could not be read. Each one swept nothing, which is
544    /// the intended fail-safe; a number that climbs means collection is not happening.
545    pub aborted: u64,
546}
547
548/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
549#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
550#[serde(deny_unknown_fields)]
551pub struct RegisterServiceParams {
552    pub name: String,
553    pub backend: BackendSpec,
554    pub allow: Vec<String>,
555    /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
556    /// to the on-disk config, and automatically unregistered when the control connection that
557    /// registered it closes (and gone on daemon restart). For an embedder that serves a
558    /// `socket` backend from a fresh path each run, this removes the need to derive a stable
559    /// socket path solely to keep a persisted registration valid, and the stale-registration
560    /// accumulation that comes with no unregister. Default false = the persistent behavior.
561    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
562    pub ephemeral: bool,
563    /// Per-service proxied-request rate (#63), falling back to `[limits].rate_limit_per_min`.
564    ///
565    /// **CLAMPED, never honoured upward.** `[limits].rate_limit_per_min` is a hard ceiling: a
566    /// larger value here is reduced to it, so a control call cannot uncap a service. Before #63
567    /// every service a peer could reach drew from one shared bucket, so a noisy service starved a
568    /// quiet one; buckets are now per `(service, endpoint)`.
569    ///
570    /// `0` is rejected rather than silently blocking every request. `api_minor >= 40`.
571    #[serde(default, skip_serializing_if = "Option::is_none")]
572    pub rate_limit_per_min: Option<u32>,
573}
574
575/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
576/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
577/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
578/// list (an invite that grants nothing is useless — #34).
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
580#[serde(deny_unknown_fields)]
581pub struct InviteParams {
582    #[serde(default)]
583    pub services: Vec<String>,
584    /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
585    /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
586    /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
587    #[serde(default, skip_serializing_if = "Option::is_none")]
588    pub app_label: Option<String>,
589    /// How many times this invite may be redeemed (#87). Absent = **1**, the single-use behaviour
590    /// every existing caller already gets.
591    ///
592    /// Each redemption runs its OWN SAS ceremony and writes its own mutual peer rows — this is not
593    /// a shared or group identity, it is N independent pairings that happen to share one secret.
594    /// Onboarding a team stops being N mint-and-send rounds.
595    ///
596    /// Clamped to [`MAX_INVITE_USES`]; `0` is rejected rather than silently meaning "unusable". A
597    /// bearer credential's blast radius is `max_uses` × TTL, so it is opt-in and capped on purpose.
598    /// The value actually applied comes back in [`InviteResult::uses_remaining`] — read that rather
599    /// than assuming you got what you asked for.
600    ///
601    /// **`api_minor >= 35`, and sending it to an older daemon FAILS rather than degrading.**
602    /// `InviteParams` is `deny_unknown_fields`, so an `api_minor < 35` daemon answers `-32602
603    /// unknown field 'max_uses'` — it does not quietly mint a single-use invite. Loud is the right
604    /// behaviour; omit the field entirely when talking to one.
605    #[serde(default, skip_serializing_if = "Option::is_none")]
606    pub max_uses: Option<u32>,
607    /// YOUR local name for whoever redeems this invite (#87), overriding the nickname they claim
608    /// for themselves in the ceremony.
609    ///
610    /// The redeemer's self-claimed name is usually its hostname, so two same-model laptops collide
611    /// and the pairing is refused with [`ERR_NICKNAME_TAKEN`]. Before this field the only fixes
612    /// were to ask the other person to rename their machine, or to unpair whoever holds the name.
613    /// This lets you just call them something else.
614    ///
615    /// Local only: it is never sent to the peer and never affects what they call themselves or
616    /// you. It does **not** bypass the collision check — an alias that itself collides is refused
617    /// identically, because a duplicate display name makes your own `<peer>/<service>` routing
618    /// ambiguous whoever chose it.
619    ///
620    /// **Rejected with `max_uses > 1`:** one alias applied to every redeemer of a multi-use invite
621    /// would collide on the second redemption, so it is refused at MINT rather than producing an
622    /// invite that works exactly once. `api_minor >= 39`.
623    #[serde(default, skip_serializing_if = "Option::is_none")]
624    pub peer_nickname: Option<String>,
625    /// Mint a SELF-ENROLLMENT invite (#86): the redeemer becomes another device of **you**, not a
626    /// peer.
627    ///
628    /// The ceremony is the ordinary one — same secret, same SAS. What differs is the outcome:
629    /// neither side writes a peer row and nothing is granted, and the inviter signs a device→user
630    /// binding for the redeemer's authenticated endpoint. Both devices then present the same
631    /// `user_pk`, so every peer resolves them to ONE `user_id`.
632    ///
633    /// **The private key never moves.** The enrolling device signs a binding for the new device's
634    /// endpoint and hands over only that signature, so a second copy of the identity never exists.
635    /// The consequence: an enrolled device cannot enroll a third — enroll every device from the one
636    /// that holds the key.
637    ///
638    /// **The SAS matters more here than anywhere else.** The inviter signs a binding for whichever
639    /// endpoint redeems, so a redemption by an impostor mints *that impostor* a binding for your
640    /// identity. Requires `max_uses = 1` and an empty `services`, both refused otherwise.
641    /// `api_minor >= 43`.
642    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
643    pub as_self: bool,
644}
645
646/// The ceiling on [`InviteParams::max_uses`] (#87). Comfortably above "a team", far below "a
647/// fleet": one leaked invite line must not be able to enroll an unbounded number of devices for the
648/// whole 24h TTL.
649pub const MAX_INVITE_USES: u32 = 64;
650
651/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
652/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
653#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
654#[serde(deny_unknown_fields)]
655pub struct PairParams {
656    #[serde(default)]
657    pub invite_line: String,
658    /// YOUR local name for the inviter (#87), overriding the nickname their invite suggests.
659    ///
660    /// An invite carries the inviter's suggestion for what you should call them — usually their
661    /// hostname. If you already use that name for a different peer, the pairing is refused with
662    /// [`ERR_INVITE_NAME_CONFLICT`] and the message tells you to go ask them for a new invite.
663    /// This lets you resolve it yourself, without `set_nickname` (which rewrites your own GLOBAL
664    /// self-name — not what anyone wants in order to add one colleague).
665    ///
666    /// Local only: never sent to the inviter. It does **not** bypass the collision check — an alias
667    /// that itself collides is refused identically, because a duplicate display name makes your own
668    /// `<peer>/<service>` routing ambiguous whoever chose it. `api_minor >= 39`.
669    #[serde(default, skip_serializing_if = "Option::is_none")]
670    pub as_nickname: Option<String>,
671    /// Consent to complete a SELF-ENROLLMENT (#178): a `mcpmesh-enroll:` line is refused with
672    /// [`ERR_SELF_ENROLL_NOT_OFFERED`] unless this is set.
673    ///
674    /// Defaults to `false`, which is the whole point. #86 gave self-enrollment its own scheme so a
675    /// version-skewed redeemer refuses rather than pairing wrongly — but a CURRENT caller that only
676    /// ever meant to pair still ran the ceremony to completion, and learned which one it had run
677    /// from [`PairResult::enrolled_as_self`] only AFTER the device→user binding was written. That
678    /// binding admits this device to everyone who trusts the inviter's `user_id`, and it is
679    /// irrevocable short of rotating that user key — so "observe it afterwards" is not a place a
680    /// caller can refuse from.
681    ///
682    /// Set it when the ceremony is one your UI actually OFFERED ("add another of my devices"). Leave
683    /// it unset on an ordinary "join / add a contact" field: the refusal costs nothing, the invite is
684    /// untouched (nothing is dialled and nothing is burned), and the same line still works if the
685    /// person is then offered the real choice.
686    ///
687    /// To decide BEFORE calling — to show the right prompt rather than recover from a refusal — use
688    /// `mcpmesh_node::pairing::is_enrollment_line`. `api_minor >= 45`.
689    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
690    pub allow_self_enroll: bool,
691}
692
693/// Params of [`Request::PeerRemove`]: the nickname to unpair.
694#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
695#[serde(deny_unknown_fields)]
696pub struct PeerRemoveParams {
697    pub nickname: String,
698}
699
700/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
701/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
702#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
703#[serde(deny_unknown_fields)]
704pub struct PeerRenameParams {
705    #[serde(default)]
706    pub user_id: Option<String>,
707    #[serde(default)]
708    pub nickname: Option<String>,
709    pub to: String,
710}
711
712/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
713/// (iroh base32) plus the nickname and service allow list to install it under.
714#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
715#[serde(deny_unknown_fields)]
716pub struct PeerAddParams {
717    pub nickname: String,
718    pub endpoint_id: String,
719    #[serde(default)]
720    pub allow: Vec<String>,
721}
722
723/// Params of [`Request::PeerEndorse`] (#65): vouch for a peer so a third party can install them.
724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
725#[serde(deny_unknown_fields)]
726pub struct PeerEndorseParams {
727    /// The subject's endpoint id, `eid:<hex>` — usually a peer you are paired with, though the
728    /// daemon does not require that: an endorsement is YOUR statement, and the recipient decides
729    /// what it is worth.
730    pub subject: String,
731    /// The subject's user key, `b64u:`, when you are also vouching for that. The recipient will
732    /// additionally require the SUBJECT's own device binding before trusting it — see
733    /// [`PeerIntroduceParams::subject_binding`].
734    #[serde(default, skip_serializing_if = "Option::is_none")]
735    pub subject_user_id: Option<String>,
736}
737
738/// Result of [`Request::PeerEndorse`] (#65) — hand both fields to the recipient.
739#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
740pub struct PeerEndorseResult {
741    /// YOUR user id, `b64u:` — what the recipient passes as `endorsed_by`. They must already be
742    /// paired with you for it to resolve.
743    pub endorsed_by: String,
744    /// The signature, `b64u:` — what the recipient passes as `evidence`.
745    pub evidence: String,
746}
747
748/// Params of [`Request::PeerIntroduce`] (#65): install a peer vouched for by someone you are
749/// already paired with.
750///
751/// The endorsement replaces pairing's SAS with the endorser's signature, so you are trusting that
752/// endorser's judgment and key hygiene as well as their identity. It buys identity resolution only
753/// — see [`Request::PeerIntroduce`].
754#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
755#[serde(deny_unknown_fields)]
756pub struct PeerIntroduceParams {
757    /// The subject's endpoint id, `eid:<hex>` — who is being introduced.
758    pub subject: String,
759    /// The endorser's user public key, `b64u:`. MUST be the `user_id` of a CURRENTLY paired peer:
760    /// the chain has to terminate at someone you paired with yourself, so an endorsement from a
761    /// stranger — or from someone you have since unpaired — is refused.
762    pub endorsed_by: String,
763    /// The endorser's signature over the domain-separated preimage, `b64u:`.
764    pub evidence: String,
765    /// The subject's OWN user key, `b64u:`, so several of the subject's devices resolve to one
766    /// person. Part of the endorser's signed statement, so it cannot be added or removed after
767    /// the fact.
768    ///
769    /// **Requires `subject_binding` too, and is REFUSED without it.** A `user_id` is
770    /// authorization-bearing — service `allow` lists match on it — so the endorser vouching for it
771    /// is not enough: an endorser could otherwise name a *victim's* `user_id` (which is public, on
772    /// `status` and every audit record) for an attacker's endpoint, and the attacker would inherit
773    /// that victim's grants. The subject must prove the key is theirs.
774    #[serde(default, skip_serializing_if = "Option::is_none")]
775    pub subject_user_id: Option<String>,
776    /// The SUBJECT's own device→user binding for `subject_user_id`, `b64u:` — the same signature a
777    /// peer presents at pairing (`mcpmesh/join/device-binding/1`), proving *it* controls that user
778    /// key and that the key is bound to *this* endpoint.
779    ///
780    /// Two independent signatures are required for a `user_id`, and they say different things: the
781    /// endorser's says "I vouch for this endpoint", the subject's says "this user key is mine".
782    /// Neither alone is sufficient.
783    #[serde(default, skip_serializing_if = "Option::is_none")]
784    pub subject_binding: Option<String>,
785    /// YOUR local name for the subject. Same rules and the same collision guard as pairing (#87).
786    pub nickname: String,
787}
788
789/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
790/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
791#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
792#[serde(deny_unknown_fields)]
793pub struct OpenSessionParams {
794    #[serde(default)]
795    pub peer: String,
796    #[serde(default)]
797    pub service: String,
798}
799
800/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
801/// on FIRST install (`b64u:`; omit once pinned — config carries it).
802#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
803#[serde(deny_unknown_fields)]
804pub struct RosterInstallParams {
805    pub path: String,
806    #[serde(default, skip_serializing_if = "Option::is_none")]
807    pub org_root_pk: Option<String>,
808}
809
810/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
811/// never crosses the API.
812#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
813#[serde(deny_unknown_fields)]
814pub struct OrgJoinParams {
815    pub org_id: String,
816    pub org_root_pk: String,
817    pub user_id: String,
818    pub user_key: String,
819}
820
821/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
822/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
823/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
824/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
825#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
826#[serde(deny_unknown_fields)]
827pub struct SetAppMetadataParams {
828    pub metadata: String,
829}
830
831/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
832/// principal, or a `b64u:` user_id.
833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
834#[serde(deny_unknown_fields)]
835pub struct PeerServicesParams {
836    pub peer: String,
837}
838
839/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
840/// caller — computed authoritatively on the peer (which owns the truth), always current, only
841/// the caller's own admitted services (never the peer's full registry).
842#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
843pub struct PeerServicesResult {
844    pub services: Vec<String>,
845}
846
847/// Params of [`Request::PeerDiagnostics`] (#140): the peer to dump — a nickname or an `eid:`
848/// device principal.
849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
850#[serde(deny_unknown_fields)]
851pub struct PeerDiagnosticsParams {
852    pub peer: String,
853}
854
855/// Result of [`Request::PeerDiagnostics`] (#140): the DURABLE per-peer state this node carries,
856/// for diagnosing why a specific long-lived pairing behaves differently from a fresh one.
857///
858/// **This surface carries a PEER's transport coordinates on purpose.** The rendered porcelain is
859/// address-free everywhere — nicknames and path KINDS — because that discipline keeps a peer's
860/// coordinates out of screenshots. (`SelfNetwork.direct_addrs` already returns this node's OWN
861/// addresses on `status`; what is new here is another endpoint's.) The question this answers is
862/// "what address is this node about to dial, and where did it come from", which has no answer
863/// without the address. It is your own store's record of your own paired peers. Do not render it
864/// in ordinary porcelain, and read it before pasting it anywhere public.
865///
866/// The intended use is a paired capture: run it on BOTH ends of a stuck pairing and compare the
867/// stored hint against the live path each side reports.
868#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
869pub struct PeerDiagnosticsResult {
870    /// The peer's nickname as this node stores it.
871    pub nickname: String,
872    /// The peer's stable `eid:` device principal.
873    pub principal: String,
874    /// The peer's `b64u:` user_id if it proved a device→user binding at pairing.
875    #[serde(default, skip_serializing_if = "Option::is_none")]
876    pub user_id: Option<String>,
877    /// When the pairing was written (epoch seconds as a string), if recorded. A LONG-LIVED pairing
878    /// is exactly what #140 is about, so the age is part of the evidence.
879    #[serde(default, skip_serializing_if = "Option::is_none")]
880    pub paired_at: Option<String>,
881    /// The persisted dial HINT, verbatim as stored — the durable state a freshly paired identity
882    /// does not have. `None` for a peer added without one.
883    ///
884    /// It is MERGED with discovery rather than replacing it — iroh inserts it as one more
885    /// candidate path (`Source::App`) and then triggers address lookup.
886    ///
887    /// **But that lookup is skipped when a path is already selected.** iroh's
888    /// `trigger_address_lookup` returns early if `selected_path.is_some()`, and a selected path is
889    /// cleared only when the last connection to that peer closes. So on a pair that already holds
890    /// an open RELAYED connection — live sessions, dial-backs, a working relay — discovery does
891    /// NOT re-run, and this hint is the only addressing the dial contributes. Do not read "merged,
892    /// so a stale hint is harmless" as unconditional; it is least true in exactly the state a
893    /// stuck pairing is in.
894    ///
895    /// It is the only durable per-peer state ON THIS NODE'S DISK that the dial path reads, which
896    /// is what makes it the first thing to compare between two ends. It is not the only durable
897    /// state a long-lived identity carries — a published discovery record under the same key, and
898    /// [`SelfNetwork::identity_conflict_epoch`], live elsewhere.
899    #[serde(default, skip_serializing_if = "Option::is_none")]
900    pub last_addr: Option<String>,
901    /// The addresses parsed out of `last_addr`, for reading without a JSON round trip: IP
902    /// addresses verbatim, relay URLs as `relay <url>` and SANITIZED to scheme+host+port (an
903    /// operator's relay URL can carry a userinfo token, and this output is meant to be pasted into
904    /// an issue). Empty when the hint is absent, unparseable, or for a different endpoint — all of
905    /// which degrade to an id-only dial.
906    ///
907    /// A `relay …` entry with no IP alongside it is worth noticing: that hint can never punch.
908    #[serde(default, skip_serializing_if = "Vec::is_empty")]
909    pub hint_addrs: Vec<String>,
910    /// Whether `last_addr` parses AND its embedded id matches this peer. A `false` here with a
911    /// present `last_addr` means the hint is being silently discarded at every dial.
912    pub hint_usable: bool,
913    /// This node's LIVE view of the peer, read straight from the reachability cache — the same
914    /// values `status` reports, repeated here so one capture holds both the durable and the live
915    /// side. `None` when this peer has **never been probed**, which is the honest answer on a
916    /// freshly restarted daemon; it is not the same as unreachable.
917    ///
918    /// Read from the cache rather than through `status`'s projection deliberately: that projection
919    /// spawns a background probe for every stale peer, which would make this diagnostic a
920    /// participant in the reproduction it is meant to observe.
921    #[serde(default, skip_serializing_if = "Option::is_none")]
922    pub reachability: Option<PeerReachability>,
923}
924
925/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
926/// to remove — the deregistration mirror of `register_service`.
927#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
928#[serde(deny_unknown_fields)]
929pub struct UnregisterServiceParams {
930    pub name: String,
931}
932
933/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
934/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
935/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
936#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
937#[serde(deny_unknown_fields)]
938pub struct ServiceAllowParams {
939    pub service: String,
940    pub principal: String,
941}
942
943/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
944/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
945/// they stored at pairing time until a re-invite.
946#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
947#[serde(deny_unknown_fields)]
948pub struct SetNicknameParams {
949    pub nickname: String,
950}
951
952/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
953#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
954#[serde(deny_unknown_fields)]
955pub struct SetRosterUrlParams {
956    pub url: String,
957}
958
959/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
960/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
961/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
962/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
963/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
964/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
965/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
966/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
967#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
968#[serde(deny_unknown_fields)]
969pub struct SetRelaysParams {
970    pub relay_urls: Vec<String>,
971}
972
973/// Result of [`Request::SetRelays`] (#53).
974#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
975pub struct SetRelaysResult {
976    /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
977    pub changed: bool,
978    /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
979    /// but NOT applied live — a node restart is required for it to take effect. `false` on the
980    /// live custom→custom path (already applied to the running endpoint).
981    pub restart_required: bool,
982}
983
984/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
985#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
986#[serde(deny_unknown_fields)]
987pub struct BlobPublishParams {
988    pub scope: String,
989    pub path: String,
990}
991
992/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
993#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
994#[serde(deny_unknown_fields)]
995pub struct BlobGrantParams {
996    pub scope: String,
997    pub principal: String,
998}
999
1000/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
1001///
1002/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
1003/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
1004/// access to everything else.
1005#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1006#[serde(deny_unknown_fields)]
1007pub struct BlobRevokeParams {
1008    pub scope: String,
1009    pub principals: Vec<String>,
1010}
1011
1012/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
1013///
1014/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
1015/// this takes effect immediately for authorization — but the bytes stay in the local store until a
1016/// GARBAGE-COLLECTION sweep reclaims them, and only a node that set `[blobs].gc_interval` runs one
1017/// (#80, `api_minor >= 49`). There is no reclaim VERB — collection is periodic and configured at
1018/// store construction, so "deleted" means "deleted within an interval" at best. On a node with no
1019/// interval configured — the default — the bytes stay forever. Do not surface this to a user as
1020/// deletion unless you know the node collects.
1021#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1022#[serde(deny_unknown_fields)]
1023pub struct BlobUnpublishParams {
1024    pub scope: String,
1025    pub hash: String,
1026}
1027
1028/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
1029///
1030/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
1031/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
1032/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
1033/// turn the original publisher going offline into a hang at every fetcher.
1034///
1035/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
1036/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
1037#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1038#[serde(deny_unknown_fields)]
1039pub struct BlobRepublishParams {
1040    pub scope: String,
1041    pub hash: String,
1042}
1043
1044/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
1045#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1046#[serde(deny_unknown_fields)]
1047pub struct BlobFetchParams {
1048    pub ticket: String,
1049    pub dest_path: String,
1050    /// ADDITIONAL sources to try if the ticket's publisher does not answer (#83).
1051    /// `api_minor >= 47`.
1052    ///
1053    /// Content addressing makes every recipient a potential source, and without this the control
1054    /// API made that unusable: a ticket names ONE address, so a file shared with a room became
1055    /// unfetchable the moment the sender closed their laptop — even though other people in the room
1056    /// already held the identical, verified bytes.
1057    ///
1058    /// Each entry is a stable principal (`eid:` device, `b64u:` user_id) or a paired nickname —
1059    /// the same vocabulary `open_session` takes. They are tried **in order, after** the ticket's own
1060    /// address, so the publisher stays the first choice and a live one costs nothing. An offline
1061    /// publisher costs one dial timeout before the first alternate is tried.
1062    ///
1063    /// **An alternate only works if it can serve you.** The bytes are BLAKE3-verified against the
1064    /// ticket's hash whoever supplies them, so a hostile alternate cannot substitute content — but
1065    /// it must have republished the hash into a scope that grants you, or it answers with a
1066    /// permission refusal and the fetch moves on. Every failure mode falls through, not only an
1067    /// unreachable dial: a refusal, a missing hash, a mid-stream reset, and a stalled transfer all
1068    /// move to the next source.
1069    ///
1070    /// Additive: absent from an older caller's payload and read as empty, which is the
1071    /// single-source behaviour.
1072    /// Capped at [`MAX_BLOB_SOURCES`]; more is an error rather than a silent truncation.
1073    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1074    pub from: Vec<String>,
1075}
1076
1077/// The ceiling on [`BlobFetchParams::from`] (#83).
1078///
1079/// Sources are tried SEQUENTIALLY and each costs up to a dial timeout, so an unbounded list is an
1080/// unbounded wait on a request that holds one of the connection's [`MAX_INFLIGHT`] slots — and
1081/// naming a PERSON expands to every device of theirs, so the list a caller writes is not the number
1082/// of dials it buys. Comfortably above "everyone in a room", far below anything that turns a fetch
1083/// into an hour.
1084///
1085/// Exceeding it is an ERROR, not a truncation: silently dropping the tail would make a fetch fail
1086/// while the source that had the blob sat unused, which is exactly what this feature exists to
1087/// prevent.
1088pub const MAX_BLOB_SOURCES: usize = 32;
1089
1090/// Params of [`Request::BlobFetchCancel`] (#172): stop every in-flight [`Request::BlobFetch`] of
1091/// this blob.
1092///
1093/// Keyed by HASH, not by JSON-RPC id, and the reason is not aesthetic: [`crate::ControlClient`]
1094/// borrows `&mut self` for a request's whole duration, so a client physically cannot send an
1095/// id-keyed cancel down the connection whose request it would name. A hash is reachable from
1096/// anywhere — including a fresh connection — and it is already the key a consumer holds, since
1097/// every [`crate::StreamFrame::BlobTransfer`] carries it.
1098#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1099#[serde(deny_unknown_fields)]
1100pub struct BlobFetchCancelParams {
1101    /// The blob's BLAKE3 hash, hex — as it appears on `BlobTransfer` frames and `BlobFetchResult`.
1102    pub hash: String,
1103}
1104
1105/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
1106/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
1107///
1108/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
1109/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
1110/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
1111/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
1112/// identical to inline variant bodies.
1113///
1114/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
1115/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
1116/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
1117/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
1118/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
1119#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1120#[serde(tag = "method", content = "params", rename_all = "snake_case")]
1121pub enum Request {
1122    /// Register/update a `[services.*]` entry idempotently.
1123    RegisterService(RegisterServiceParams),
1124    Status,
1125    /// Mint a pairing invite granting `services` — single-use unless `max_uses` says otherwise
1126    /// (#87). The daemon
1127    /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
1128    /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
1129    /// `method` string generically; the tag comes from `rename_all`.
1130    Invite(InviteParams),
1131    /// Redeem a pairing invite. The daemon dials the inviter named by
1132    /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
1133    /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
1134    /// (snake_case); `method_of` reads the `method` string generically.
1135    ///
1136    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
1137    Pair(PairParams),
1138    /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
1139    /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
1140    /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
1141    /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
1142    /// NOT severed here: existing sessions run to completion; the peer only loses the
1143    /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
1144    /// `method_of` reads the `method` string generically (no per-variant arm).
1145    ///
1146    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
1147    PeerRemove(PeerRemoveParams),
1148    /// Rename a contact's nickname (nickname) authoritatively. Renames the
1149    /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
1150    /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
1151    /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
1152    /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
1153    /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
1154    /// host-privileged like the other pair ops.
1155    PeerRename(PeerRenameParams),
1156    /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
1157    /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
1158    /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
1159    /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
1160    /// vocabulary — do not build on it. Tag `"peer_add"`.
1161    PeerAdd(PeerAddParams),
1162    /// Install a peer from a SIGNED endorsement by someone you are already paired with (#65) —
1163    /// O(N) onboarding for a small group, without a fresh two-human SAS ceremony per pair.
1164    ///
1165    /// **It installs IDENTITY, never AUTHORIZATION.** The subject becomes resolvable; it is granted
1166    /// nothing. Service access stays principal-keyed in config (#38) and an explicit, separate act.
1167    /// That is what bounds the feature: a compromised endorser can make you KNOW about an attacker,
1168    /// it cannot make you SERVE one.
1169    ///
1170    /// Unlike [`PeerAdd`](Self::PeerAdd) — which is reserved precisely because the caller merely
1171    /// ASSERTS an id — this is verifiable: the endorsement is checked against a user key you
1172    /// already hold from pairing with the endorser. Tag `"peer_introduce"`.
1173    PeerIntroduce(PeerIntroduceParams),
1174    /// PRODUCE an endorsement of a peer, for someone else to redeem with
1175    /// [`PeerIntroduce`](Self::PeerIntroduce) (#65). The other half of an introduction: without it
1176    /// nothing can generate `evidence`, and the install half is unusable.
1177    ///
1178    /// Signs with THIS node's user key, so the result is only meaningful to someone who has paired
1179    /// with you. Endorsing does not change your own trust in the subject. Tag `"peer_endorse"`.
1180    PeerEndorse(PeerEndorseParams),
1181    /// Open a mesh session to `peer/service`; the daemon dials and pipes.
1182    /// Distinct from the proxy's job: this returns a session the client streams.
1183    /// Named `open_session` rather than `connect` to avoid colliding
1184    /// with the `connect` porcelain.
1185    OpenSession(OpenSessionParams),
1186    /// Install a signed roster from a local file (the manual `internal roster install` path).
1187    /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
1188    /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
1189    /// pins the org root on FIRST install (`b64u:`); omit it
1190    /// once pinned (config carries it). Tag `"roster_install"`.
1191    RosterInstall(RosterInstallParams),
1192    /// Read the installed roster's MEMBERSHIP: the declared groups, and every person with their
1193    /// display name, groups, and devices (#93). Parameterless. Tag `"roster_members"`.
1194    ///
1195    /// The read half of roster mode. `status` reports that a roster exists (`RosterStatus`) and who
1196    /// is currently online (`PresencePeer`); neither answered "who is in this org" — a person with
1197    /// no live device appeared nowhere at all, so an embedder could not draw a member list, and
1198    /// the only route to one was hand-parsing the daemon-owned `roster.json`.
1199    ///
1200    /// ADVISORY and display-oriented, like `status`: the gate reads the roster document, never
1201    /// this. Empty in a pure-pairing daemon or before the first roster is installed.
1202    RosterMembers,
1203    /// AUTHOR an org: mint this node's org root key, sign an empty roster (serial 1), install it
1204    /// (which pins the root), and return the copyable org invite (#66). Tag `"org_create"`.
1205    ///
1206    /// One-time per node — a second call is refused rather than replacing the key, because
1207    /// replacing it would orphan every roster it has signed.
1208    OrgCreate(OrgCreateParams),
1209    /// APPROVE a join code into the roster: verify its device→user-key binding, upsert the member
1210    /// with the given groups, bump the serial, re-sign, install (#66). Tag `"org_approve"`.
1211    ///
1212    /// The cryptographic half of the ceremony. Verifying that the code came from the PERSON you
1213    /// think it did stays an out-of-band human step, and `join_code_fingerprint` in the result is
1214    /// what the two humans compare.
1215    OrgApprove(OrgApproveParams),
1216    /// INSPECT a join code without approving it (#66): who it claims to be, and the fingerprint the
1217    /// two humans compare. Read-only — nothing is signed, installed, or persisted.
1218    /// Tag `"org_join_code"`.
1219    ///
1220    /// This is what makes an "approve this person" button correct rather than merely possible. The
1221    /// fingerprint has to be shown and confirmed out-of-band BEFORE the approval, because a
1222    /// substituted code is caught there or not at all — and reading it off `OrgApprove`'s result
1223    /// is too late, the member is already in the signed roster. The CLI always had this (it
1224    /// decoded the code locally); an embedder could not, since the join-code format lives in
1225    /// `mcpmesh-node` and not on this seam.
1226    OrgJoinCode(OrgJoinCodeParams),
1227    /// REVOKE from the roster: remove a person, one device, or a person's user key, then bump,
1228    /// re-sign, and install — which severs the cut devices' live sessions (#66).
1229    /// Tag `"org_revoke"`.
1230    OrgRevoke(OrgRevokeParams),
1231    /// EXPORT this node's user key as a recovery phrase (#85 ask 2). Parameterless.
1232    /// Tag `"user_key_export"`.
1233    ///
1234    /// **The phrase IS the private key**, in a form a human can write down. Anyone who reads it can
1235    /// present this identity. It is deliberately not logged, not audited, and not echoed anywhere
1236    /// but this response.
1237    UserKeyExport,
1238    /// IMPORT a user key from a recovery phrase (#85 ask 2), so a person's `b64u:` survives the
1239    /// hardware. Tag `"user_key_import"`.
1240    UserKeyImport(UserKeyImportParams),
1241    /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
1242    /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
1243    /// `user_key` is a LOCAL path
1244    /// (the key never crosses the API). Tag `"org_join"`.
1245    OrgJoin(OrgJoinParams),
1246    /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
1247    /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
1248    /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
1249    /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
1250    /// `"set_roster_url"`.
1251    SetRosterUrl(SetRosterUrlParams),
1252    /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
1253    /// daemon's own serialized config-write path (no lost-update window against a
1254    /// concurrent grant/registration) and update the in-memory name future invites
1255    /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
1256    SetNickname(SetNicknameParams),
1257    /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
1258    /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
1259    /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
1260    /// on restart; the embedder re-sets on startup).
1261    SetAppMetadata(SetAppMetadataParams),
1262    /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
1263    /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
1264    /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
1265    /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
1266    /// is currently `default`/`disabled`, the config is persisted but the live mode transition
1267    /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
1268    /// [`SetRelaysResult`]. Tag `"set_relays"`.
1269    SetRelays(SetRelaysParams),
1270    /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
1271    /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
1272    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
1273    /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
1274    /// hot-reloads. Idempotent. Ack result.
1275    UnregisterService(UnregisterServiceParams),
1276    /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
1277    /// and returns the service names whose allow admits the caller's principal. Answers
1278    /// [`PeerServicesResult`].
1279    PeerServices(PeerServicesParams),
1280    /// Dump the DURABLE per-peer state this node carries for one peer (#140) — the persisted dial
1281    /// hint, the pairing stamp, and the live reachability row, in one capture. A DIAGNOSTIC verb:
1282    /// unlike every other surface it carries transport vocabulary on purpose. Answers with
1283    /// [`PeerDiagnosticsResult`]. `api_minor >= 33`.
1284    PeerDiagnostics(PeerDiagnosticsParams),
1285    ServiceAllowGrant(ServiceAllowParams),
1286    /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
1287    /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
1288    /// Idempotent. Ack result.
1289    ServiceAllowRevoke(ServiceAllowParams),
1290    /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
1291    /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
1292    /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
1293    /// Tag `"blob_publish"`.
1294    BlobPublish(BlobPublishParams),
1295    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
1296    /// nickname (the shared `principal_set` expansion). Tag
1297    /// `"blob_grant"`.
1298    BlobGrant(BlobGrantParams),
1299    /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
1300    BlobRevoke(BlobRevokeParams),
1301    /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
1302    /// bytes.
1303    BlobUnpublish(BlobUnpublishParams),
1304    /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
1305    /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
1306    /// two interchangeably after a fetch.
1307    BlobRepublish(BlobRepublishParams),
1308    /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
1309    BlobList(BlobListParams),
1310    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
1311    /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
1312    /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
1313    BlobFetch(BlobFetchParams),
1314    /// Cancel every in-flight [`BlobFetch`](Self::BlobFetch) of one hash (#172). Answers a
1315    /// [`BlobFetchCancelResult`]; the cancelled fetches themselves answer [`ERR_CANCELLED`].
1316    /// Tag `"blob_fetch_cancel"`.
1317    BlobFetchCancel(BlobFetchCancelParams),
1318    /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
1319    /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
1320    /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
1321    /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
1322    /// `method_of` reads the `method` string generically (no per-variant arm).
1323    AuditSummary,
1324    /// Delete audit months strictly older than `before` (#88) — the retention lever the log
1325    /// never had. Local-only and owner-only (the control socket is the daemon owner's). Answers
1326    /// [`AuditPruneResult`]. Tag `"audit_prune"`.
1327    AuditPrune(AuditPruneParams),
1328    /// Read this node's LOCAL audit records, filtered and paged (#88) — the "show me everything
1329    /// you hold about me" verb. Local-only; nothing is transmitted. Answers
1330    /// [`AuditListResult`]. Tag `"audit_list"`.
1331    AuditList(AuditListParams),
1332    /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
1333    /// connection STOPS being request/response after this call and becomes a one-way push stream
1334    /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
1335    Subscribe,
1336}
1337
1338/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
1339/// computed porcelain-side from the invite's org_root_pk). Additive-only.
1340#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1341pub struct OrgJoinResult {
1342    pub org_id: String,
1343    /// `true` when the org root was pinned but this node's ROSTER TRANSPORT is not running, so the
1344    /// join is only half in effect until the daemon restarts (#93). `api_minor >= 46`.
1345    ///
1346    /// Roster mode is decided at BOOT: it fixes the ALPN set bound on the endpoint and whether
1347    /// gossip, presence and app-blobs are constructed at all. The roster GATE hot-swaps live. So a
1348    /// node that booted in pairing mode and then joins an org reaches a state where MCP sessions to
1349    /// org members work as soon as a roster arrives, while `status.presence` stays permanently
1350    /// empty and every blob verb hard-closes with `blobs not enabled` — succeeding partially, with
1351    /// no error anywhere, which a caller previously had no way to detect.
1352    ///
1353    /// **What to do with it:** if `true`, tell the user the join succeeded and the node must
1354    /// restart before presence and file sharing work. Do not treat it as a failure — nothing was
1355    /// left half-written; the pin is durable and the restart is sufficient.
1356    ///
1357    /// `false` when the transport is already composed (the node booted with an org root pinned), or
1358    /// on a re-join of an org this node is already in.
1359    ///
1360    /// Same shape as [`SetRelaysResult::restart_required`] (#53), for the same reason. Additive:
1361    /// absent from an older daemon's payload and reads as `false` — which was that daemon's
1362    /// implicit, and wrong, answer.
1363    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1364    pub restart_required: bool,
1365}
1366
1367/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
1368/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
1369/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
1370///
1371/// Additive-only: any future field MUST land as
1372/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1374pub struct RosterInstallResult {
1375    pub org_id: String,
1376    pub serial: u64,
1377    /// How many live sessions were severed, for the porcelain's confirmation line.
1378    #[serde(default)]
1379    pub severed: u32,
1380}
1381
1382/// Params of [`Request::OrgCreate`] (#66).
1383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1384#[serde(deny_unknown_fields)]
1385pub struct OrgCreateParams {
1386    /// The org's name — its `org_id`, the value every member's roster carries.
1387    pub name: String,
1388    /// How long the signed roster stays valid, in seconds. Omit for the 90-day default.
1389    ///
1390    /// This is an operator-grade default and a sharp edge at small scale: past it the roster
1391    /// degrades and the group stops working, which for a handful of laptops can arrive days after
1392    /// one of them was closed for a long weekend. A small team should pass a long value here
1393    /// deliberately rather than discover the default later.
1394    #[serde(default, skip_serializing_if = "Option::is_none")]
1395    pub expires_secs: Option<i64>,
1396    /// An HTTPS URL where the signed roster will be published. Carried in the org invite (so a
1397    /// joiner bootstraps its first roster) AND pinned in this operator's `[roster].url`.
1398    #[serde(default, skip_serializing_if = "Option::is_none")]
1399    pub roster_url: Option<String>,
1400}
1401
1402/// Result of [`Request::OrgCreate`] (#66).
1403#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1404pub struct OrgCreateResult {
1405    pub org_id: String,
1406    pub serial: u64,
1407    /// The copyable `mcpmesh-org:` invite to hand a joiner — one of the two permitted opaque
1408    /// artifacts on this surface, the same carve-out the pairing invite line takes.
1409    pub org_invite: String,
1410    /// The org root's fingerprint in short words, for the out-of-band read-back that anchors every
1411    /// joiner's trust. NOT the key.
1412    pub org_root_fingerprint: String,
1413}
1414
1415/// Params of [`Request::OrgApprove`] (#66).
1416#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1417#[serde(deny_unknown_fields)]
1418pub struct OrgApproveParams {
1419    /// The `mcpmesh-join:` code the joiner sent.
1420    pub join_code: String,
1421    /// The groups to grant. Each must be DECLARED in the roster (see
1422    /// [`RosterMembersResult::groups`]) — an undeclared one is refused, because it would make an
1423    /// `allow` entry naming it ambiguous.
1424    #[serde(default)]
1425    pub groups: Vec<String>,
1426    /// Override the `user_id` the joiner requested. Omit to accept theirs.
1427    ///
1428    /// Worth using: the requested id is chosen by the person being approved, and it is the string
1429    /// every `allow` entry will name.
1430    #[serde(default, skip_serializing_if = "Option::is_none")]
1431    pub user_id: Option<String>,
1432}
1433
1434/// Result of [`Request::OrgApprove`] (#66).
1435#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1436pub struct OrgApproveResult {
1437    pub user_id: String,
1438    pub groups: Vec<String>,
1439    pub org_id: String,
1440    pub serial: u64,
1441    /// The join code's fingerprint in short words — the enrollment analogue of the pairing SAS.
1442    ///
1443    /// **Show this to the operator and have them confirm it out-of-band before trusting the
1444    /// approval.** Nothing else binds the person to the `user_pk` in the code, so a substituted
1445    /// code is caught here or not at all. Returned rather than checked, because only the human can
1446    /// check it.
1447    pub join_code_fingerprint: String,
1448}
1449
1450/// Params of [`Request::UserKeyImport`] (#85 ask 2).
1451#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
1452#[serde(deny_unknown_fields)]
1453pub struct UserKeyImportParams {
1454    /// The recovery phrase, as written down. Whitespace and case are forgiven; a wrong word, the
1455    /// wrong count, or a failed checksum are refused by position rather than guessed at.
1456    pub recovery_phrase: String,
1457    /// Replace an EXISTING user key. Defaults to `false`, and the refusal is the point: importing
1458    /// over a live key discards the identity this node currently presents, which is irreversible
1459    /// without that key's own phrase.
1460    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1461    pub replace: bool,
1462}
1463
1464/// Result of [`Request::UserKeyExport`] (#85 ask 2).
1465///
1466/// **`recovery_phrase` is the private key.** Show it to the person who owns it, once, and do not
1467/// persist it anywhere your application would not persist the key file itself.
1468#[derive(Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1469pub struct UserKeyExportResult {
1470    /// 33 words. Write them down in order.
1471    pub recovery_phrase: String,
1472    /// The `b64u:` identity this phrase restores — safe to display and to record, unlike the
1473    /// phrase. Compare it after an import to confirm the right identity came back.
1474    pub user_id: String,
1475}
1476
1477/// REDACTING `Debug` — the phrase is a private key, and a derived one would put it in any
1478/// `tracing::debug!(?params)` a future change adds to the dispatch, or in an embedder's `dbg!`.
1479/// Three lines to make that leak unrepresentable rather than merely absent today.
1480impl std::fmt::Debug for UserKeyImportParams {
1481    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1482        f.debug_struct("UserKeyImportParams")
1483            .field("recovery_phrase", &"<redacted>")
1484            .field("replace", &self.replace)
1485            .finish()
1486    }
1487}
1488
1489/// REDACTING `Debug` — see [`UserKeyImportParams`]. The `user_id` is safe and is kept, because a
1490/// `{:?}` with nothing in it is worse for debugging than one with the non-secret half.
1491impl std::fmt::Debug for UserKeyExportResult {
1492    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1493        f.debug_struct("UserKeyExportResult")
1494            .field("recovery_phrase", &"<redacted>")
1495            .field("user_id", &self.user_id)
1496            .finish()
1497    }
1498}
1499
1500/// Result of [`Request::UserKeyImport`] (#85 ask 2).
1501#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1502pub struct UserKeyImportResult {
1503    /// The `b64u:` identity now in effect. **Compare it against the one you are recovering** — the
1504    /// phrase's checksum catches most transcription errors, but a `user_id` that does not match is
1505    /// the definitive answer, and the only one that distinguishes "restored the wrong key" from
1506    /// "peers have not seen me yet".
1507    pub user_id: String,
1508    /// `true` when this discarded a REAL identity — a user key the node had loaded from disk,
1509    /// rather than one it minted at this boot and had never presented to anyone.
1510    ///
1511    /// The distinction is the useful one: a fresh node always has a key on disk before an import
1512    /// can run (its own boot mints one), so "a file existed" would be `true` for every recovery on
1513    /// new hardware and would have a UI warn that something was destroyed when nothing was.
1514    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1515    pub replaced: bool,
1516}
1517
1518/// Params of [`Request::OrgJoinCode`] (#66).
1519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1520#[serde(deny_unknown_fields)]
1521pub struct OrgJoinCodeParams {
1522    /// The `mcpmesh-join:` code to inspect.
1523    pub join_code: String,
1524}
1525
1526/// Result of [`Request::OrgJoinCode`] (#66): what a join code claims, plus the fingerprint that
1527/// decides whether to believe it.
1528///
1529/// The claims are ATTACKER-CONTROLLED — they come out of a code someone handed you. `display_name`
1530/// and `requested_user_id` are what the sender asked for, not facts. What is verified is the
1531/// device→user-key binding (a bad one is refused rather than reported), and what is *checkable* is
1532/// `join_code_fingerprint`.
1533#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1534pub struct OrgJoinCodeResult {
1535    /// The human name the code carries. Sender-chosen — render it, do not trust it.
1536    pub display_name: String,
1537    /// The `user_id` the sender is asking for. Sender-chosen, and it is what every `allow` entry
1538    /// would name, so it is worth an operator's attention before approving.
1539    pub requested_user_id: String,
1540    /// The label of the device being enrolled. Sender-chosen.
1541    pub device_label: String,
1542    /// The fingerprint in short words — the enrollment analogue of the pairing SAS.
1543    ///
1544    /// **Show this and have the operator confirm it out-of-band before calling
1545    /// [`Request::OrgApprove`].** Nothing in a join code binds it to a person; a substituted code
1546    /// carries a different `user_pk` and so diverges here. This is the entire check.
1547    pub join_code_fingerprint: String,
1548}
1549
1550/// Params of [`Request::OrgRevoke`] (#66).
1551#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1552#[serde(deny_unknown_fields)]
1553pub struct OrgRevokeParams {
1554    /// Who or what to revoke: a `user_id` (the person and every device), or `"<user_id>/<label>"`
1555    /// (one device).
1556    pub target: String,
1557    /// Treat this as a USER-KEY rotation instead: remove the person but leave their devices
1558    /// un-revoked, so the same hardware re-enrolls under a fresh user key and is re-approved with
1559    /// the same `user_id`.
1560    ///
1561    /// The distinction is the point — a departure must revoke the devices, a rotation must not.
1562    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1563    pub user_key: bool,
1564}
1565
1566/// Result of [`Request::OrgRevoke`] (#66).
1567#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1568pub struct OrgRevokeResult {
1569    pub target: String,
1570    /// `"person"` | `"device"` | `"user-key-rotation"` — which grammar the target resolved to, so a
1571    /// caller can confirm the destructive reading it got was the one it meant.
1572    pub mode: String,
1573    pub org_id: String,
1574    pub serial: u64,
1575    /// Live sessions severed by the install. Revocation is IMMEDIATE (#54): a cut device's existing
1576    /// connections are closed, not left to drain.
1577    #[serde(default)]
1578    pub severed: u32,
1579}
1580
1581/// Result of [`Request::RosterMembers`]: the org's membership as an embedder renders it (#93).
1582///
1583/// Distinct from `status.presence` in what it enumerates: that lists reachable DEVICES and omits a
1584/// person entirely when none of their devices is up. This lists every person the roster carries,
1585/// online or not — a member list, not a presence list — with `online` per device so a UI can draw
1586/// both from one read.
1587///
1588/// ADVISORY. Every field here is display or authoring input; nothing in it is an authorization
1589/// answer. The gate reads the signed roster.
1590#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1591pub struct RosterMembersResult {
1592    /// The org's declared group namespace, in document order — the set an `allow` entry may name.
1593    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1594    pub groups: Vec<String>,
1595    /// Every person in the roster, ordered by `user_id` for a stable display.
1596    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1597    pub users: Vec<RosterMember>,
1598}
1599
1600/// One person in a [`RosterMembersResult`] (#93).
1601#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1602pub struct RosterMember {
1603    /// The stable authorization handle — what an `allow` entry names.
1604    pub user_id: String,
1605    /// The human name, for display. Empty if the roster's own field is.
1606    #[serde(default, skip_serializing_if = "String::is_empty")]
1607    pub display_name: String,
1608    /// The groups this person belongs to, each declared in [`RosterMembersResult::groups`].
1609    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1610    pub groups: Vec<String>,
1611    /// Their ACTIVE devices — revoked ones are absent, exactly as the gate sees it. Ordered
1612    /// primary-before-mirror, then by label.
1613    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1614    pub devices: Vec<RosterMemberDevice>,
1615}
1616
1617/// One device of a [`RosterMember`] (#93).
1618#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1619pub struct RosterMemberDevice {
1620    /// The device's human label.
1621    pub label: String,
1622    /// `"primary"` | `"mirror"` — the advisory dial-ordering hint, never a security property.
1623    pub role: String,
1624    /// The device's stable `eid:` principal — the SAME vocabulary [`PeerInfo::principal`] carries,
1625    /// and what a per-device `allow` entry names.
1626    ///
1627    /// Included where `PresencePeer` deliberately omits it, because this surface exists to be
1628    /// ACTED on: an embedder granting or revoking one device of a person needs the handle to name
1629    /// it, and the alternative is a nickname that does not exist in roster mode.
1630    pub principal: String,
1631    /// Whether the device has a live presence heartbeat. Advisory — absence never blocks a dial,
1632    /// and never removes a dial candidate.
1633    pub online: bool,
1634}
1635
1636/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
1637/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
1638/// carve-out as the pairing invite line). Additive-only.
1639#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1640pub struct BlobPublishResult {
1641    pub ticket: String,
1642    pub hash: String, // bare blake3 hex
1643}
1644
1645/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
1646/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
1647#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1648pub struct ScopeInfo {
1649    pub name: String,
1650    pub hashes: Vec<String>,
1651    pub grants: Vec<String>,
1652    /// Hashes deliberately WITHDRAWN from this scope (#107): `blob_unpublish` was called, and
1653    /// `blob_republish` of these into THIS scope is refused with [`ERR_BLOB_WITHDRAWN`]. Cleared
1654    /// only by a deliberate `blob_publish {scope, path}`. Additive — omitted when empty, so a
1655    /// pre-`api_minor` 19 client sees exactly what it saw before.
1656    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1657    pub withdrawn: Vec<String>,
1658    /// Size of `hashes` — always present, even when `counts_only` empties the vector (#84b).
1659    #[serde(default)]
1660    pub hash_count: usize,
1661    /// Size of `grants`.
1662    #[serde(default)]
1663    pub grant_count: usize,
1664    /// Size of `withdrawn`.
1665    #[serde(default)]
1666    pub withdrawn_count: usize,
1667}
1668
1669/// Params of [`Request::BlobList`] (#84b). ALL optional — `blob_list {}` still works, which
1670/// matters because the verb took no params before `api_minor` 20.
1671///
1672/// A DEFAULT LIMIT applies when `limit` is absent. Deliberate: unpaged, `blob_list` renders every
1673/// scope into one frame against the 16 MiB cap; past it the CLIENT rejects the frame as malformed.
1674/// The control surface carries no strike bound, so the connection survives — but the caller gets an
1675/// opaque failure with no way to page, which is unusable rather than merely large.
1676#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1677#[serde(default, deny_unknown_fields)]
1678pub struct BlobListParams {
1679    /// EXACT scope name, never a prefix.
1680    pub scope: Option<String>,
1681    /// Only scopes containing this hash; the rendering you send is normalized first.
1682    pub hash: Option<String>,
1683    pub limit: Option<usize>,
1684    pub offset: Option<usize>,
1685    /// Omit `hashes`/`grants`/`withdrawn`, keep the counts.
1686    pub counts_only: bool,
1687}
1688
1689/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
1690#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1691pub struct BlobScopeList {
1692    pub scopes: Vec<ScopeInfo>,
1693    /// Scopes matching the filter BEFORE `limit`/`offset` (#84b). Without this you cannot tell a
1694    /// complete answer from a clipped one.
1695    #[serde(default)]
1696    pub total: usize,
1697    /// True when more scopes matched than were returned. Page with `offset` to see the rest.
1698    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1699    pub truncated: bool,
1700}
1701
1702/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
1703/// Additive-only.
1704#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1705pub struct BlobFetchResult {
1706    pub hash: String,
1707    pub bytes_len: u64,
1708}
1709
1710/// Result of [`Request::BlobFetchCancel`] (#172).
1711#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1712pub struct BlobFetchCancelResult {
1713    /// True when a fetch of that hash was in flight and has been told to stop. False is NOT an
1714    /// error — it means nothing was fetching that blob here, which is also what a caller sees when
1715    /// it races a fetch that just finished.
1716    pub cancelled: bool,
1717}
1718
1719/// Params of [`Request::AuditPrune`] (#88): delete monthly audit files STRICTLY older than
1720/// `before` (that month itself is kept — delete-before, not delete-including). Rejects unknown
1721/// fields, and the daemon validates the `YYYY-MM` shape up front: a malformed month errors
1722/// loudly instead of string-comparing to nothing and reporting a clean no-op.
1723#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1724#[serde(deny_unknown_fields)]
1725pub struct AuditPruneParams {
1726    /// A zero-padded `YYYY-MM` month key.
1727    pub before: String,
1728}
1729
1730/// Result of [`Request::AuditPrune`]: the month keys actually deleted, ascending. Empty when
1731/// nothing was older than `before` (idempotent).
1732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1733pub struct AuditPruneResult {
1734    pub deleted_months: Vec<String>,
1735}
1736
1737/// Params of [`Request::AuditList`] (#88). All filters optional and AND-combined; every field
1738/// absent lists everything (paged). Rejects unknown fields — a typo'd filter that silently
1739/// matched everything would let a "what do you hold about X" answer overclaim.
1740#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1741#[serde(deny_unknown_fields)]
1742pub struct AuditListParams {
1743    /// Inclusive `YYYY-MM` lower bound — month-file granularity (the rotation unit), so an
1744    /// out-of-range month is skipped without parsing it.
1745    #[serde(default, skip_serializing_if = "Option::is_none")]
1746    pub since: Option<String>,
1747    /// Inclusive `YYYY-MM` upper bound.
1748    #[serde(default, skip_serializing_if = "Option::is_none")]
1749    pub until: Option<String>,
1750    /// One of the wire kind strings (`session_open` / `session_close` / `request` /
1751    /// `blob_fetch` / `trust`). An UNKNOWN string is an error, never silently-all.
1752    #[serde(default, skip_serializing_if = "Option::is_none")]
1753    pub kind: Option<String>,
1754    /// The record's attributed peer nickname.
1755    #[serde(default, skip_serializing_if = "Option::is_none")]
1756    pub peer: Option<String>,
1757    /// Page size, default 500, clamped to 1000 — a month file can be arbitrarily large and the
1758    /// response is ONE JSON frame under the transport's frame cap, so the clamp is load-bearing
1759    /// (the same lesson as `blob_list`'s, minor 20).
1760    #[serde(default, skip_serializing_if = "Option::is_none")]
1761    pub limit: Option<u32>,
1762    /// Records to skip (after filtering), for paging.
1763    #[serde(default, skip_serializing_if = "Option::is_none")]
1764    pub offset: Option<u32>,
1765}
1766
1767/// Result of [`Request::AuditList`]: one page of matching records in chronological order
1768/// (oldest month first, in-file order within a month), plus the TOTAL match count so a caller
1769/// can page without a second counting call. `total` counts ALL matches, not the page.
1770#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1771pub struct AuditListResult {
1772    pub records: Vec<AuditRecord>,
1773    pub total: u64,
1774}
1775
1776/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
1777/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
1778/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
1779/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
1780/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
1781/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
1782///
1783/// Additive-only: any future field MUST land as
1784/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1785#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1786pub struct AuditSummaryResult {
1787    /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
1788    /// peer to attribute) but IS in `total_sessions`.
1789    pub per_peer: Vec<(String, u64)>,
1790    /// Sessions opened per registered service name.
1791    pub per_service: Vec<(String, u64)>,
1792    /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
1793    #[serde(default)]
1794    pub total_sessions: u64,
1795}
1796
1797/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
1798/// (the ONE pairing artifact deliberately carved out of the
1799/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
1800/// absolute expiry in epoch seconds (≤ now + 24h).
1801///
1802/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
1803/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
1804/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
1805/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
1806/// ceremony" note in `docs/local-protocol.md` (#35).
1807///
1808/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
1809/// so older payloads still deserialize.
1810#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1811pub struct InviteResult {
1812    /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
1813    pub invite_line: String,
1814    /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
1815    pub expires_at_epoch: u64,
1816    /// How many redemptions this invite has left (#87) — **the value actually applied**, after the
1817    /// [`MAX_INVITE_USES`] clamp. `1` for an ordinary single-use invite.
1818    ///
1819    /// Reported so a caller that asked for more than the cap is told what it got rather than
1820    /// discovering it when the fourth colleague fails. Additive: `#[serde(default = "one")]`, so a
1821    /// response from an older daemon reads as single-use. `api_minor >= 35`.
1822    #[serde(default = "one_use")]
1823    pub uses_remaining: u32,
1824}
1825
1826/// The serde default for a `uses_remaining` field absent from an older payload or invite line: one
1827/// redemption, which is what every pre-#87 invite is.
1828pub fn one_use() -> u32 {
1829    1
1830}
1831
1832/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
1833/// redeemer's local name for the new peer) plus the display-only short authentication
1834/// code (SAS) — a few words the human reads aloud to a second channel to
1835/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
1836/// artifact (like the invite line), NOT a transport-vocabulary leak.
1837///
1838/// Additive-only: any future field MUST land as
1839/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
1840#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1841pub struct PairResult {
1842    /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
1843    pub peer_nickname: String,
1844    /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
1845    /// sides for the out-of-band human check. Never sent on the wire, never checked
1846    /// programmatically.
1847    pub sas_code: String,
1848    /// TRUE when this redemption was a SELF-ENROLLMENT (#86): you are now another device of the
1849    /// inviter's person, not their peer. No peer row was written and nothing was granted.
1850    ///
1851    /// Reported so a caller can tell the two outcomes apart without inspecting its own store.
1852    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
1853    pub enrolled_as_self: bool,
1854    /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
1855    /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
1856    /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
1857    /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
1858    /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
1859    #[serde(default, skip_serializing_if = "Vec::is_empty")]
1860    pub services: Vec<String>,
1861    /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
1862    /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
1863    #[serde(default, skip_serializing_if = "Option::is_none")]
1864    pub app_label: Option<String>,
1865    /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
1866    /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
1867    /// can align with its own — and the same value it may later pass to `open_session` to dial
1868    /// this peer by identity rather than by local nickname. `None` if the inviter presented no
1869    /// binding (a legacy/keyless peer). Additive.
1870    #[serde(default, skip_serializing_if = "Option::is_none")]
1871    pub peer_user_id: Option<String>,
1872}
1873
1874/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
1875/// top of the base record schema: it removes no field and makes the JSONL self-describing so
1876/// a consumer can filter by class without guessing from which optional fields are present.
1877#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1878#[serde(rename_all = "snake_case")]
1879pub enum AuditKind {
1880    /// A mesh session opened (a backend was selected for an authenticated peer).
1881    /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
1882    /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
1883    SessionOpen,
1884    /// A mesh session closed (the backend returned / the session tore down).
1885    SessionClose,
1886    /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
1887    Request,
1888    /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
1889    BlobFetch,
1890    /// A trust mutation (pair, unpair, roster install/swap, revoke).
1891    Trust,
1892}
1893
1894/// One audit record — the union of the event classes, and the `record` payload of a
1895/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
1896/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
1897/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
1898/// `bytes_out`).
1899///
1900/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
1901/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
1902/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
1903#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1904pub struct AuditRecord {
1905    /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
1906    /// prefix also selects the monthly file (the rotation boundary), so it is always present.
1907    pub ts: String,
1908    pub kind: AuditKind,
1909    /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
1910    /// local-only events with no remote peer (a manual roster install).
1911    #[serde(skip_serializing_if = "Option::is_none")]
1912    pub peer: Option<String>,
1913    #[serde(skip_serializing_if = "Option::is_none")]
1914    pub service: Option<String>,
1915    #[serde(skip_serializing_if = "Option::is_none")]
1916    pub method: Option<String>,
1917    /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
1918    #[serde(skip_serializing_if = "Option::is_none")]
1919    pub tool: Option<String>,
1920    /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
1921    #[serde(skip_serializing_if = "Option::is_none")]
1922    pub args_hash: Option<String>,
1923    /// Byte COUNT of the response sent back to the peer — a count, never the content.
1924    #[serde(skip_serializing_if = "Option::is_none")]
1925    pub bytes_out: Option<u64>,
1926    /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
1927    #[serde(skip_serializing_if = "Option::is_none")]
1928    pub status: Option<String>,
1929    #[serde(skip_serializing_if = "Option::is_none")]
1930    pub latency_ms: Option<u64>,
1931    /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
1932    #[serde(skip_serializing_if = "Option::is_none")]
1933    pub event: Option<String>,
1934    /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
1935    /// nickname or `org/serial` (`Trust`).
1936    #[serde(skip_serializing_if = "Option::is_none")]
1937    pub target: Option<String>,
1938    /// The subject's STABLE principal, from the same gate resolution that produced `peer`
1939    /// (#57, `api_minor >= 29`). `peer` is a display name and collides — two devices under one
1940    /// nickname were indistinguishable in the stream and the on-disk log. Same argument and
1941    /// shape as `PeerInfo` (#41), `PeerReachability` (#42), and `ActiveSession` (#73).
1942    ///
1943    /// TWO NAMESPACES, deliberately: session/request/blob records attribute the DEVICE
1944    /// (`eid:<hex>`, like `ActiveSession` — the exact authenticated endpoint), while the trust
1945    /// `pair` record carries the value the grant appended to the allow (`b64u:<pk>` when the
1946    /// device presented a user binding, else `eid:`, #38). Joining a bound peer's sessions to
1947    /// its allow entry therefore goes through the `status` peers list (which carries BOTH the
1948    /// device principal and the `user_id`), not string equality on this field alone.
1949    ///
1950    /// **`peer_introduce` (#65) is the one exception, deliberately:** it carries the ENDORSER, not
1951    /// the subject. An introduction's whole security question is *who vouched for this peer*, and
1952    /// the subject is already in `target`. So `audit_list --peer <endorser>` finds the
1953    /// introductions that endorser caused, which is the query an operator actually runs.
1954    ///
1955    /// Deliberately absent on: `unpair` (may tear down several devices — no single subject),
1956    /// `roster_install` (purely local), and the failed-outbound-dial session record (our own
1957    /// dial, not a gate-resolved caller). Absent on every record written before 0.24.0.
1958    #[serde(default, skip_serializing_if = "Option::is_none")]
1959    pub principal: Option<String>,
1960}
1961
1962impl AuditRecord {
1963    fn base(ts: String, kind: AuditKind) -> Self {
1964        Self {
1965            ts,
1966            kind,
1967            peer: None,
1968            service: None,
1969            method: None,
1970            tool: None,
1971            args_hash: None,
1972            bytes_out: None,
1973            status: None,
1974            latency_ms: None,
1975            event: None,
1976            target: None,
1977            principal: None,
1978        }
1979    }
1980
1981    /// `principal` is an EXPLICIT parameter on every constructor (#57, kept from the original
1982    /// #72 design): a builder would let a call site silently omit it and reintroduce the
1983    /// collapsed-identity bug for that one event class. Pass `None` only for the documented
1984    /// no-single-subject records (see the field doc).
1985    pub fn session_open(
1986        ts: String,
1987        peer: Option<String>,
1988        service: String,
1989        principal: Option<String>,
1990    ) -> Self {
1991        let mut r = Self::base(ts, AuditKind::SessionOpen);
1992        r.peer = peer;
1993        r.service = Some(service);
1994        r.principal = principal;
1995        r
1996    }
1997
1998    /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
1999    /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
2000    /// reaches no backend and so is never audited by the far side's session guard — without a
2001    /// dedicated constructor. DRY: reuses the existing optional `status` field.
2002    pub fn with_status(mut self, status: &str) -> Self {
2003        self.status = Some(status.into());
2004        self
2005    }
2006
2007    pub fn session_close(
2008        ts: String,
2009        peer: Option<String>,
2010        service: String,
2011        principal: Option<String>,
2012    ) -> Self {
2013        let mut r = Self::base(ts, AuditKind::SessionClose);
2014        r.peer = peer;
2015        r.service = Some(service);
2016        r.principal = principal;
2017        r
2018    }
2019
2020    /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
2021    /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
2022    /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
2023    #[allow(clippy::too_many_arguments)]
2024    pub fn proxied_request(
2025        ts: String,
2026        peer: Option<String>,
2027        service: String,
2028        method: String,
2029        tool: Option<String>,
2030        args_hash: String,
2031        bytes_out: u64,
2032        status: String,
2033        latency_ms: u64,
2034        principal: Option<String>,
2035    ) -> Self {
2036        let mut r = Self::base(ts, AuditKind::Request);
2037        r.peer = peer;
2038        r.service = Some(service);
2039        r.method = Some(method);
2040        r.tool = tool;
2041        r.args_hash = Some(args_hash);
2042        r.bytes_out = Some(bytes_out);
2043        r.status = Some(status);
2044        r.latency_ms = Some(latency_ms);
2045        r.principal = principal;
2046        r
2047    }
2048
2049    /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
2050    /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
2051    pub fn proxied_notification(
2052        ts: String,
2053        peer: Option<String>,
2054        service: String,
2055        method: String,
2056        tool: Option<String>,
2057        args_hash: String,
2058        principal: Option<String>,
2059    ) -> Self {
2060        let mut r = Self::base(ts, AuditKind::Request);
2061        r.peer = peer;
2062        r.service = Some(service);
2063        r.method = Some(method);
2064        r.tool = tool;
2065        r.args_hash = Some(args_hash);
2066        r.principal = principal;
2067        r
2068    }
2069
2070    pub fn blob_fetch(
2071        ts: String,
2072        peer: Option<String>,
2073        hash: String,
2074        status: String,
2075        principal: Option<String>,
2076    ) -> Self {
2077        let mut r = Self::base(ts, AuditKind::BlobFetch);
2078        r.peer = peer;
2079        r.target = Some(hash);
2080        r.status = Some(status);
2081        r.principal = principal;
2082        r
2083    }
2084
2085    pub fn trust(
2086        ts: String,
2087        event: String,
2088        target: Option<String>,
2089        principal: Option<String>,
2090    ) -> Self {
2091        let mut r = Self::base(ts, AuditKind::Trust);
2092        r.event = Some(event);
2093        r.target = target;
2094        r.principal = principal;
2095        r
2096    }
2097}
2098
2099/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
2100/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
2101#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2102pub struct ActiveSession {
2103    pub peer: String,
2104    pub service: String,
2105    pub opened_at: i64,
2106    /// The caller's STABLE device principal, `eid:<hex>` (#73).
2107    ///
2108    /// `peer` is a display nickname and collides: two devices under one nickname, or two contacts
2109    /// sharing a display name, are indistinguishable in the live-session view. So "who is using my
2110    /// service right now", per-peer session counts, and any UI that lets a user act on a live
2111    /// session (revoke, disconnect, inspect) were all keyed on a collidable string.
2112    ///
2113    /// Same argument and same shape as [`PeerInfo`] (#41) and [`PeerReachability`] (#42).
2114    /// Nicknames NEVER authorize; this is the value to key on.
2115    ///
2116    /// **Snapshot only, for now.** `ActiveSession` appears in [`StreamFrame::Snapshot`] — there is
2117    /// no `active_sessions` on `StatusResult`. A client that keeps its view current by applying
2118    /// subsequent `session_open`/`session_close` events still has a collision problem: those are
2119    /// [`AuditRecord`]s and carry no principal (#57, unmerged). So the snapshot distinguishes two
2120    /// same-nickname devices and the next `session_close` for that nickname does not say which row
2121    /// to drop. Re-subscribe for an authoritative view until #57 lands.
2122    ///
2123    /// Always present for a real row — `Option` only so an older client round-trips. Additive.
2124    #[serde(default, skip_serializing_if = "Option::is_none")]
2125    pub principal: Option<String>,
2126}
2127
2128/// Which side of an app-blob transfer a [`StreamFrame::BlobTransfer`] describes (#82).
2129#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2130#[serde(rename_all = "snake_case")]
2131pub enum BlobDirection {
2132    /// We are SERVING bytes to a peer that dialed our app-blob ALPN.
2133    Serve,
2134    /// We are FETCHING bytes from a peer, via `blob_fetch`.
2135    Fetch,
2136}
2137
2138/// Where an app-blob transfer is in its life (#82).
2139#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
2140#[serde(rename_all = "snake_case")]
2141pub enum BlobTransferState {
2142    /// The transfer began; `bytes_total` is known from here on.
2143    Started,
2144    /// Bytes advanced. COALESCED — see [`StreamFrame::BlobTransfer`].
2145    Progress,
2146    /// Finished successfully. Carries the FINAL byte count.
2147    Completed,
2148    /// Ended without completing (peer went away, refused, or the store errored).
2149    Aborted,
2150}
2151
2152/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
2153/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
2154/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
2155/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
2156/// them (see `docs/local-protocol.md` "Live event stream").
2157///
2158/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
2159/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
2160/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
2161/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
2162#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
2163#[serde(tag = "type", rename_all = "snake_case")]
2164#[non_exhaustive]
2165pub enum StreamFrame {
2166    /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
2167    /// reachability) so a fresh subscriber renders immediately without replaying history.
2168    Snapshot {
2169        active_sessions: Vec<ActiveSession>,
2170        reachability: Vec<PeerReachability>,
2171        /// THIS node's own reachability posture (#90), so a fresh subscriber renders it without
2172        /// a `status` poll. `None` in mesh-less control-only mode. Additive: default +
2173        /// skip-if-none so an older payload round-trips.
2174        #[serde(default, skip_serializing_if = "Option::is_none")]
2175        self_network: Option<SelfNetwork>,
2176    },
2177    /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
2178    /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
2179    /// `Box`, so the wire shape is the record's fields verbatim.
2180    Event { record: Box<AuditRecord> },
2181    /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
2182    /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
2183    /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
2184    /// it returns, rather than on the next poll tick.
2185    ///
2186    /// Emitted on a change of `reachable` **or of `path`**. A refresh with the same verdict AND the
2187    /// same path emits nothing, so a peer that stays up does not produce a frame per TTL refresh;
2188    /// `rtt_ms`/`meta`/`services` drift is advisory detail and is not a transition. `age_secs` is
2189    /// `0` — the observation just completed.
2190    ///
2191    /// **Do not treat this as an up/down toggle.** It carried that meaning through 0.18, and this
2192    /// doc said "on a CHANGE of `reachable` only" until 1.22 — which stopped being true in 0.19.0
2193    /// (#92 item 1), when `path` joined the transition rule. A consumer that assumed same-verdict
2194    /// frames were impossible was reading a stale guarantee.
2195    ///
2196    /// Two producers, as of API 1.22 — and since 1.30 `source` says WHICH ONE, so the distinction
2197    /// is readable rather than inferred:
2198    ///
2199    /// - [`ReachabilitySource::Probe`] — a probe completing (`status`/`subscribe` refreshing a
2200    ///   stale entry). It describes a throwaway dial, not anyone's live connection.
2201    /// - [`ReachabilitySource::Session`] — a live session whose selected path changed under it
2202    ///   (#92 item 2). A claim about the link in use.
2203    ///
2204    /// The second producer is why `path` is trustworthy for a long-lived session: a session that
2205    /// degrades Direct→Relay mid-call now says so when it happens, rather than staying silently
2206    /// mislabelled until something probes. `path` is a truth claim about where user data went, so
2207    /// `Unknown` means "we do not know" and must never be rendered as private.
2208    ///
2209    /// **`rtt_ms` is not a discriminator, and never was** (#150). Until 1.30 this doc said a
2210    /// session-sourced frame carries `rtt_ms: None` — true only of a FIRST observation, where no
2211    /// round trip was measured and none is invented. A session-sourced frame for an
2212    /// already-probed peer carries that probe's `rtt_ms: Some(..)`, because the path watcher
2213    /// deliberately leaves `rtt_ms`/`meta`/`probed_at` alone (refreshing them would stamp a stale
2214    /// RTT as fresh and suppress the corrective probe — #92 review). That is the common case for a
2215    /// peer probed at pairing time and then watched through a long call. Read `source`.
2216    Reachability {
2217        peer: PeerReachability,
2218        /// Which producer emitted this frame (#150). `api_minor >= 30`.
2219        ///
2220        /// Additive: `#[serde(default)]`, landing on [`ReachabilitySource::Unknown`] — NOT on
2221        /// `Probe`. A daemon at `api_minor` 22–29 already has both producers, so an absent field
2222        /// genuinely does not say which one ran; defaulting to `Probe` would assert the wrong
2223        /// producer for every session-sourced frame such a daemon emits, which is the exact
2224        /// ambiguity this field exists to remove.
2225        #[serde(default)]
2226        source: ReachabilitySource,
2227    },
2228    /// THIS node's own network posture CHANGED (#90): `online` flipped, the home relay moved,
2229    /// or a relay's connection state changed — pushed so an embedder learns "you just went
2230    /// unreachable" the moment it happens instead of on a poll tick, and so #53's `set_relays`
2231    /// finally has a signal telling someone to use it. `direct_addrs` drift alone does not
2232    /// emit (address churn is chatty and not a decision point; it rides the next frame).
2233    /// `api_minor >= 28`.
2234    SelfNetwork { self_network: SelfNetwork },
2235    /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
2236    /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
2237    Lagged { dropped: u64 },
2238    /// An app-blob transfer advanced (#82). Emitted on BOTH sides: `Serve` while we send bytes to
2239    /// a peer, `Fetch` while `blob_fetch` pulls them.
2240    ///
2241    /// **`Progress` is COALESCED, deliberately.** iroh-blobs reports progress per ~16 KiB chunk, so
2242    /// a 4 GiB transfer would push ~262k frames through a bounded ring and every subscriber would
2243    /// see `Lagged` — losing the audit events that share it. A frame is emitted on `Started`, on
2244    /// `Completed`/`Aborted`, and on `Progress` only after at least `max(1 MiB, total/100)` more
2245    /// bytes, so a transfer costs at most ~102 frames whatever its size.
2246    ///
2247    /// **Do not treat the last `Progress` as the total** — the final stride is usually skipped.
2248    /// `Completed` carries the final `bytes_done`.
2249    BlobTransfer {
2250        direction: BlobDirection,
2251        /// The blob's hash, hex.
2252        hash: String,
2253        bytes_done: u64,
2254        /// Known from `Started` onward; `None` only if the size was never reported.
2255        #[serde(default, skip_serializing_if = "Option::is_none")]
2256        bytes_total: Option<u64>,
2257        state: BlobTransferState,
2258        /// SERVING side only: the STABLE `eid:` device principal we are serving (#38 — never a
2259        /// display nickname). Always `eid:<hex>`: this comes from the authenticated endpoint, so it
2260        /// is NOT the same namespace as a grant written as a user_id or roster name. Absent when fetching, where the counterparty is named
2261        /// by the ticket rather than by a resolved identity.
2262        #[serde(default, skip_serializing_if = "Option::is_none")]
2263        peer: Option<String>,
2264    },
2265}
2266
2267/// Extract the `method` tag from a raw request value without deserializing the whole
2268/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
2269/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
2270/// methods (adjacent tagging rejects `params:{}` on unit variants).
2271pub fn method_of(v: &serde_json::Value) -> Option<&str> {
2272    v.get("method").and_then(serde_json::Value::as_str)
2273}
2274
2275/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
2276/// Config→BackendSpec is a hand-written match, not a serde passthrough.
2277#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2278#[serde(rename_all = "snake_case")]
2279pub enum BackendSpec {
2280    Run {
2281        cmd: Vec<String>,
2282        /// Per-service environment variables (#51) for the spawned child. Overlaid on the
2283        /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
2284        /// these (identity is not spoofable by a service definition). Default empty.
2285        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
2286        env: BTreeMap<String, String>,
2287        /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
2288        #[serde(default, skip_serializing_if = "Option::is_none")]
2289        cwd: Option<String>,
2290    },
2291    Socket {
2292        path: String,
2293    },
2294}
2295
2296/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
2297/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
2298/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
2299/// `{}` (success) for an unknown name, which silently included every ephemeral service.
2300pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
2301/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
2302/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
2303pub const ERR_NO_SUCH_BLOB: i64 = -32041;
2304/// The blob was deliberately withdrawn from this scope (#107). Distinct from
2305/// [`ERR_NO_SUCH_BLOB`]: that means "fetch it first", this means "someone un-shared this on
2306/// purpose — `blob_publish` from the file if the re-share is intended".
2307pub const ERR_BLOB_WITHDRAWN: i64 = -32042;
2308/// `pair` was refused because the redeemer's nickname is already held by a DIFFERENT paired peer
2309/// (#87), so an embedder can branch on the one refusal that has a self-service remedy — rename and
2310/// redeem the same invite again — without reading the prose (#147).
2311///
2312/// Reading the prose was the only option before this code, and it does not survive translation: the
2313/// message is generated on the INVITER's side and travels to the redeemer, so the embedder that
2314/// DISPLAYS it cannot rewrite it into its own vocabulary except by substring-matching our copy.
2315/// Branch on this and write your own sentence naming your own rename affordance.
2316///
2317/// Deliberately narrow. It rides ONLY this refusal, which is sent exclusively to a caller that
2318/// proved possession of a live invite secret. The generic refusal keeps `-32000` and its opaque
2319/// reason: distinguishing unknown-vs-expired-vs-wrong-secret would be a redemption oracle.
2320pub const ERR_NICKNAME_TAKEN: i64 = -32043;
2321
2322/// The invite line's own `expires_at_epoch` has passed (#159). Decided LOCALLY, before dialing —
2323/// this says nothing about the inviter's state. Remedy: ask for a fresh invite.
2324pub const ERR_INVITE_EXPIRED: i64 = -32044;
2325
2326/// The inviter has **no outstanding invite at all** — its accept gate fast-closed the dial (#159).
2327///
2328/// This is as close to "expired or already used" as we can safely get, and the distinction matters:
2329/// it is a fact about the INVITER, not about the secret presented. Answering per-secret would be a
2330/// redemption oracle — a prober would learn which guessed secrets were ever real — which is why
2331/// [`ERR_INVITE_REFUSED`] stays deliberately undifferentiated. Remedy: ask for a fresh invite.
2332pub const ERR_INVITE_NOT_LIVE: i64 = -32045;
2333
2334/// The inviter's address could not be dialed at all (#159) — offline, asleep, or unroutable.
2335/// Remedy: check they are running, then retry the same invite; it is untouched.
2336pub const ERR_INVITER_UNREACHABLE: i64 = -32046;
2337
2338/// **The address-swap defense fired**: the TLS-authenticated peer is not the endpoint the invite
2339/// names (#159).
2340///
2341/// The one refusal here that must NOT be rendered as "try again". Something answered in place of
2342/// the machine the invite identifies — a substituted address, or a forged invite. An embedder that
2343/// treats every pairing failure as a friendly retry papers over exactly the attack this check
2344/// exists to catch. Remedy: do not retry; get the invite again through a channel you trust.
2345pub const ERR_INVITER_MISMATCH: i64 = -32047;
2346
2347/// The invite asks to be called a name this node already uses for a DIFFERENT peer (#159).
2348///
2349/// The redeemer-side mirror of [`ERR_NICKNAME_TAKEN`], and a distinct condition: that one is the
2350/// inviter refusing the redeemer's name, this is the redeemer refusing the inviter's suggestion.
2351/// Nothing is granted either way — a name confers no access (#38) — so this protects this node's
2352/// own display and routing clarity. Remedy: ask for an invite suggesting a different name.
2353pub const ERR_INVITE_NAME_CONFLICT: i64 = -32048;
2354
2355/// The inviter refused, and the cause is **deliberately withheld** (#159).
2356///
2357/// Unknown secret, expired secret, and wrong secret are one answer on purpose: telling them apart
2358/// is a redemption oracle. The code carries exactly as much as the prose already did — "that invite
2359/// did not work" — so a consumer can branch without parsing, and without learning anything a
2360/// prober could use. Remedy: ask for a fresh invite.
2361pub const ERR_INVITE_REFUSED: i64 = -32049;
2362
2363/// The request was stopped on purpose before it finished (#172) — today, a `blob_fetch` that
2364/// [`Request::BlobFetchCancel`] tripped.
2365///
2366/// A cancelled request still ANSWERS. Cancellation is cooperative rather than a task abort
2367/// precisely so this code can be delivered: an aborted task returns nothing, and the caller waits
2368/// forever on work that already stopped. Distinct from `-32000` because it is not a failure — the
2369/// caller (or its user) asked for it. Remedy: none; retry the fetch if the cancel was a mistake.
2370///
2371/// **What it does not promise:** partial chunks already streamed into the blob store stay there,
2372/// unlisted and unreclaimable, exactly as they do when a fetch fails. That is #80's reclaim gap,
2373/// unchanged by cancellation.
2374pub const ERR_CANCELLED: i64 = -32050;
2375
2376/// This control connection already has [`MAX_INFLIGHT`] requests running, so this one was refused
2377/// without being started (#172).
2378///
2379/// **Retryable, and cheap to retry** — retry after any response lands, or spread the load over a
2380/// second control connection. It is refused rather than queued deliberately: a queue is invisible
2381/// backpressure that a caller cannot tell apart from a slow daemon, and waiting for a permit inside
2382/// the read loop would reintroduce the head-of-line blocking concurrent dispatch exists to remove.
2383///
2384/// Not a security boundary — the control socket is the daemon owner's. It bounds the work one
2385/// connection can have outstanding so a buggy client cannot spawn unboundedly.
2386pub const ERR_TOO_MANY_INFLIGHT: i64 = -32051;
2387
2388/// The invite line is a SELF-ENROLLMENT (`mcpmesh-enroll:`) and the caller did not offer that
2389/// ceremony — [`PairParams::allow_self_enroll`] was unset (#178).
2390///
2391/// Decided from the line in hand, BEFORE any dial: nothing was contacted, no secret was revealed,
2392/// and the invite is untouched. Like [`ERR_INVITE_EXPIRED`] it therefore reveals nothing about the
2393/// inviter and is safe to name precisely.
2394///
2395/// Distinct from [`ERR_INVITE_REFUSED`] in the direction it points: that one is the inviter turning
2396/// US down, this one is US declining a ceremony we were never asked to run. Remedy: if the person
2397/// meant to add another of their OWN devices, offer that explicitly and retry the SAME line with
2398/// `allow_self_enroll`; otherwise they pasted the wrong link and want an ordinary
2399/// `mcpmesh-invite:` one.
2400pub const ERR_SELF_ENROLL_NOT_OFFERED: i64 = -32052;
2401
2402/// How many requests one control connection may have in flight at once (#172), after which it
2403/// answers [`ERR_TOO_MANY_INFLIGHT`]. Per connection, not per daemon.
2404pub const MAX_INFLIGHT: usize = 32;
2405
2406pub const API_NAME: &str = "mcpmesh-local/1";
2407/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
2408///
2409/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
2410///   transport already rejects a mismatched `api`, so an equality check on that is redundant).
2411/// - **MINOR** ([`API_MINOR`]) increments on a surface change within a major — additive fields, new
2412///   methods, or a strictness change like params validation — bumped in the same change that makes
2413///   it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon older
2414///   than a minor it requires. It never resets except on a MAJOR bump.
2415///
2416///   It also bumps for a change to what a field MEANS with no change to its shape — six of the
2417///   thirty have, see [`API_MINOR`]'s history. "Every surface change" is what this line used
2418///   to claim, and it was wrong in both directions: minor 9's entry records surface changes that
2419///   shipped WITHOUT a bump, and six bumps changed no type at all. Read the history, not the rule.
2420pub const API_VERSION: &str = "1.49";
2421/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
2422/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
2423/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
2424/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
2425/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
2426/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
2427/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
2428/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
2429/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
2430/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
2431/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
2432/// observable contract did: a revoked principal's next session is refused even on a connection it
2433/// already holds, and its live connections are severed. Previously both waited for the peer to
2434/// disconnect on its own, which is unbounded (#54). A consumer can guard on
2435/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
2436/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
2437/// about an unknown service name — a name in neither the config nor the ephemeral registry now
2438/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
2439/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
2440/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
2441/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
2442/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
2443/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
2444/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
2445/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
2446/// errored on any daemon without an org root key, though their scope gate never needed one (#61);
2447/// to 17 when the service answer began coming from the LIVE registry rather than config + overlay,
2448/// so a grant the accept path would refuse is no longer advertised. Three surfaces share that
2449/// resolver and all changed together: `status`'s `services[].allow`, `peer_services`' name list,
2450/// and the `mcpmesh/ping/1` probe's `services`. No wire shape changed, only the source of truth —
2451/// exactly the class of change a downstream cannot see in a type diff (#100); to 18 with `blob_republish`, so a fetched blob can
2452/// be re-served and every recipient becomes a source (#83); to 19 with durable blob revocation — an
2453/// unpublish now survives a later republish via a per-scope withdrawal set, and
2454/// [`ERR_BLOB_WITHDRAWN`] distinguishes "deliberately withdrawn" from "never had it" (#107); to 20
2455/// with `blob_list` filters + paging AND a DEFAULT limit of 256 scopes (the clamp is 4096) — a
2456/// daemon with more scopes than that previously answered with
2457/// everything, and past the 16 MiB frame cap the CLIENT rejected the response as malformed, leaving
2458/// the caller an opaque failure with no way to page. The connection survived: the control surface
2459/// carries no strike bound. This is a behaviour change for existing callers, detectable via the new
2460/// `total`/`truncated` (#84b); to 21 when a
2461/// PATH change became a reachability transition — [`StreamFrame::Reachability`] stopped being an
2462/// up/down toggle and same-verdict frames became possible (#92); to 22 with a SECOND producer for
2463/// that frame: a live per-session watcher that pushes when a session's selected path changes,
2464/// rather than waiting for a probe, at a cadence probes never had (#92); to 23 when
2465/// [`PeerReachability::rtt_ms`] stopped including the path-settle window — a relayed peer could
2466/// previously never report under 600ms, so "relayed AND fast" was unreachable by construction
2467/// (#123); to 24 when `reachable` stopped sharing a deadline with path classification — a relayed
2468/// peer whose pong arrived after ~2.4s was reported OFFLINE while it was answering (#128); to 25
2469/// with [`ActiveSession::principal`] — the live-session view was keyed on a display nickname, so
2470/// two devices under one nickname were indistinguishable and any UI acting on a session (revoke,
2471/// disconnect, inspect) keyed on a collidable string (#73); to 26 when a
2472/// rate-limited inbound NOTIFICATION stopped being silently dropped and became a recorded audit
2473/// event — no type changed; the observable audit stream did (#76, #139); to 27 with the `audit_prune` /
2474/// `audit_list` verbs, `StatusResult::storage`, and the opt-in `[limits].audit_retain_months`
2475/// boot retention — the audit log stopped being a permanent, unbounded, unreadable record (#88);
2476/// to 28 with `StatusResult::self_network` / `StreamFrame::SelfNetwork` / the snapshot's copy —
2477/// the node's OWN reachability posture, previously unanswerable from either side of the API
2478/// (#90); to 29 with [`AuditRecord::principal`] — stable identity on the event stream and the
2479/// on-disk log, resolving #57's parked docs conflict in favour of the #41/#42/#73 line (the
2480/// audit surface bans secrets and raw hex, not the prefixed principal rendering); to 30 with
2481/// [`StreamFrame::Reachability`]'s `source` — the frame has had TWO producers since 22 with no way
2482/// to tell them apart, so an embedder could not distinguish "a throwaway dial went via a relay"
2483/// from "the link this call is on just degraded", and had to hedge every message down to the
2484/// weaker claim. `rtt_ms: None` was never the discriminator the doc implied (#150); to 31 with
2485/// [`ERR_NICKNAME_TAKEN`] — the nickname-collision `pair` refusal is branchable instead of
2486/// `-32000`, so an embedder writes its own recovery copy rather than substring-matching ours. The
2487/// prose changed with it: it named the `set_nickname` CONTROL VERB as the remedy, which a GUI user
2488/// cannot type, and the refusal is generated inviter-side so the embedder displaying it could not
2489/// rewrite it (#147); to 32 with [`SelfNetwork::identity_conflict_epoch`] — two nodes booted from
2490/// COPIES of one mesh root share an endpoint id, and the displaced one's peers went unreachable
2491/// with nothing saying why. The relay reports it and iroh only `warn!`s it, so the fact existed
2492/// and was unreadable (#134); to 33 with the `peer_diagnostics` verb — a long-lived pairing that
2493/// cannot hole-punch while a fresh identity on the same hardware can differs only in DURABLE
2494/// per-peer state, and none of it was readable from outside the daemon (#140); to 34 when
2495/// outstanding invites became DURABLE — `invite.expires_at_epoch` changed meaning from an upper
2496/// bound on the daemon's process lifetime to the real lifetime, and `invite` gained an error where
2497/// it previously always succeeded. No shape changed, which is exactly the class minor 10 records:
2498/// guard on `api_minor >= 34` before telling a user their invite will still be good tomorrow
2499/// (#87b); to 35 with `InviteParams.max_uses` + `InviteResult.uses_remaining` — a bounded
2500/// multi-use invite, so onboarding a team is one link rather than one ceremony per person. Each
2501/// redemption still runs its own SAS and writes its own peer rows; it is N pairings sharing a
2502/// secret, never a group identity (#87); to 36 with branchable codes for the rest of the ONBOARDING
2503/// refusals — expired line, no live invite, inviter unreachable, id mismatch, name conflict, and
2504/// the deliberately-opaque refusal. `ERR_NICKNAME_TAKEN` had been the only coded pairing failure,
2505/// so every other one arrived as `-32000` and an embedder could either forward our prose to end
2506/// users or substring-match it (#159); to 49 with [`StorageInfo::blobs_gc`] — app-blob GARBAGE
2507/// COLLECTION, off unless `[blobs].gc_interval` is set (#80). `blob_unpublish` and `blob_revoke`
2508/// closed the AUTHORIZATION half at 15; neither reclaimed a byte, so `<data_dir>/blobs/` grew
2509/// monotonically for the life of the node and an embedder that had told a user "this file is
2510/// deleted" could not deliver that. Opt-in, because a sweep also reclaims blobs this node FETCHED
2511/// and never republished — reclaimable in themselves (the fetch already wrote the caller's
2512/// `dest_path`) but it means `blob_republish` of a hash fetched more than one interval ago fails.
2513/// `blobs_gc` is `None` when collection is not configured, `Some` with `runs: 0` when it is
2514/// configured and has not swept yet — a distinction worth reading, because the collector sleeps a
2515/// full interval before its first run. WATCH `runs`: iroh-blobs ends collection for the process on
2516/// its first sweep error, so a counter that stops advancing is the only signal. Guard on `>= 49`;
2517/// to 48 with `user_key_export` / `user_key_import` — a
2518/// RECOVERY PHRASE for the user key, so a person's `b64u:` survives the hardware (#85 ask 2). It
2519/// lived in one file on one machine with no export, import or escrow verb anywhere, so replacing a
2520/// laptop destroyed the identity peers pin, kb audiences key on, and a roster names — recovery was
2521/// an in-person SAS ceremony with everyone you had ever paired with. **The export response carries
2522/// a PRIVATE KEY**: it is deliberately absent from the audit log, from `status`, and from every
2523/// other surface. Import refuses to overwrite an existing key unless asked, because doing so
2524/// discards a live identity irreversibly. What it does NOT do: get a device admitted. Peers
2525/// authorize per DEVICE, and a restored user key puts this endpoint in nobody's allowlist — that is
2526/// #85 ask 3, unshipped, and the reason a recovered person still pairs. Guard on `>= 48`; to 47 with `BlobFetchParams::from` — ADDITIONAL sources a
2527/// fetch falls back to when the ticket's publisher does not answer (#83). Content addressing makes
2528/// every recipient a potential source, and a one-address ticket made that unusable: a file shared
2529/// with a room became unfetchable the moment the sender closed their laptop, though others in the
2530/// room already held the identical verified bytes. Additive and absent-tolerant — an older caller's
2531/// payload reads as empty, which is the single-source behaviour — so guard on `>= 47` only before
2532/// SENDING the field (`deny_unknown_fields` rejects the whole request below it). The bytes stay
2533/// BLAKE3-verified against the ticket's hash whoever serves them, so an alternate can refuse but
2534/// never substitute; it must have republished the hash into a scope granting the caller
2535/// (`blob_republish`, `api_minor >= 18`). What did NOT land: multi-source PARALLEL fetch — sources
2536/// are tried in order, so an offline publisher costs one dial timeout; to 46 with the roster-mode embedding surface (#66, #93):
2537/// the `org_create` / `org_approve` / `org_revoke` AUTHORING verbs, the `roster_members` read,
2538/// `PresencePeer::display_name` + `groups`, `RosterStatus::groups`, and
2539/// `OrgJoinResult::restart_required`. Two gaps close together. Authoring existed only as CLI
2540/// porcelain, so an embedded node could CONSUME a roster and never author one — no "approve this
2541/// person" button without shelling out to a second binary. And the roster's own contents never
2542/// crossed the seam: an embedder had managed group membership it could not display, and the only
2543/// route to a member list was hand-parsing the daemon-owned `roster.json`. `roster_members` is a
2544/// different question from `status.presence` — that lists reachable DEVICES and omits a person
2545/// whose devices are all down. `restart_required` closes a silent partial success: `roster_mode` is
2546/// a BOOT decision fixing the bound ALPNs and whether gossip/presence/blobs exist at all, so a
2547/// pairing-mode node that ran `org_join` got working MCP sessions with permanently empty presence
2548/// and no way to detect it. Guard on `>= 46` before offering org authoring in a UI; the read fields
2549/// are additive and degrade to empty. What did NOT land: org root ROTATION (#93c) — an operator
2550/// laptop that dies still takes the org with it once the roster expires; to 45 with [`PairParams::allow_self_enroll`] +
2551/// [`ERR_SELF_ENROLL_NOT_OFFERED`] — `pair` now REFUSES a `mcpmesh-enroll:` line unless the caller
2552/// asked for that ceremony. A behaviour change for existing callers, deliberately: at 43-44 a caller
2553/// whose UI only ever offered "add a contact" completed a self-enrollment and learned which
2554/// ceremony it had run from `enrolled_as_self` afterwards — by which point the device→user binding
2555/// was written and irrevocable short of rotating the user key (#178). The refusal is decided from
2556/// the line before any dial, so the invite survives it and the same line works once the ceremony is
2557/// actually offered. Guard on `>= 45` before sending the field — below it `deny_unknown_fields`
2558/// rejects the whole request. Note what the guard means: a daemon BELOW 45 gives a caller no way to
2559/// decline, so a UI that does not offer device enrollment should require `>= 45` rather than pair
2560/// without it; to 44 when control responses stopped arriving in REQUEST
2561/// order and the `blob_fetch_cancel` verb landed (#172). The daemon now dispatches each request
2562/// CONCURRENTLY on its connection, so a `blob_fetch` no longer stalls every other verb behind it —
2563/// and responses arrive in COMPLETION order. JSON-RPC ids make that legal and the in-tree
2564/// `ControlClient` cannot observe it (one request at a time, by construction), but a hand-rolled
2565/// client that pipelines and matches responses POSITIONALLY breaks. A connection also caps
2566/// in-flight requests and refuses over it with [`ERR_TOO_MANY_INFLIGHT`], and closing a control
2567/// connection now genuinely ABORTS its in-flight work rather than letting it run to completion
2568/// unread. Guard on `>= 44` before pipelining, before sending `blob_fetch_cancel`, and before
2569/// treating [`ERR_CANCELLED`] as unexpected; to 43 with `InviteParams::as_self` — SELF-ENROLLMENT, so one
2570/// person's devices share a `user_id` instead of appearing as unrelated strangers (#86). The
2571/// ceremony is ordinary pairing; the outcome is a device→user binding rather than a peer row, and
2572/// the private key never moves. Guard on `>= 43`. What this entry did NOT say, and 45 fixed: the
2573/// distinct scheme closes the version-SKEW hazard (a pre-43 redeemer silently over-granting) and
2574/// closes nothing for a CURRENT redeemer, which had no way to decline a ceremony it never offered
2575/// (#178); to 42 with the `peer_introduce` + `peer_endorse`
2576/// verbs — install a peer from a
2577/// SIGNED endorsement by someone you are already paired with, so a small group onboards in O(N)
2578/// instead of O(N²) two-human ceremonies (#65). It installs IDENTITY only and grants nothing, which
2579/// is what bounds it. Guard on `>= 42`; to 41 with `StreamFrame::BlobTransfer` — live app-blob
2580/// transfer progress on both the serving and fetching side (#82 ask 2), so an embedder can draw a
2581/// real progress bar instead of an indeterminate spinner. Guard on `>= 41` before expecting the
2582/// frame. NOTE what it did NOT bring, and 44 did: at 41 `blob_fetch` still blocked its whole
2583/// control connection for the transfer and nothing could cancel it (#172) — progress arrived on the
2584/// SUBSCRIBE connection, which is a different one; to 40 with `[services.<name>].rate_limit_per_min` +
2585/// `RegisterServiceParams::rate_limit_per_min` — proxied-request buckets became per
2586/// `(service, endpoint)` instead of one shared per-endpoint bucket, so a noisy service can no
2587/// longer starve a quiet one (#63). `-32053` changes meaning with it: it is now per-service, so a
2588/// consumer that backs off globally on one is backing off further than it needs to. Guard on
2589/// `>= 40` before sending the field or narrowing a back-off; to 39 with `PairParams::as_nickname` +
2590/// `InviteParams::peer_nickname` — LOCAL aliases for the other party, so a nickname collision is
2591/// resolvable by the person who hit it instead of requiring the other human to rename a machine or
2592/// re-mint. #147 made the collision diagnosable; this makes it fixable. Guard on `>= 39` before
2593/// offering an alias field in a UI: below it `deny_unknown_fields` rejects the whole request
2594/// (#87); to 38 with `[network].presence_mode` + `SelfNetwork.
2595/// presence_mode` — `reachable: false` gained a new meaning ("up, paired, and deliberately not
2596/// answering"), and `peer_services` flips from "reachable, empty list" to "unreachable" for a
2597/// caller holding no grant. A consumer must guard on `api_minor >= 38` before telling a user their
2598/// peer is offline, since below it that verdict could not mean this (#89); to 37 when the reserved
2599/// `mcpmesh/*` `_meta` namespace began
2600/// being enforced on EVERY proxied frame rather than the session's first. `run_session` treats
2601/// frame 1 as the `initialize` whatever its method is, so a caller could send any other method
2602/// first and put its real `initialize` — with a forged `mcpmesh/peer` naming another principal,
2603/// forged `groups` and all — in frame 2, where nothing stripped or injected. No shape changed;
2604/// what changed is whether `_meta["mcpmesh/peer"]` can be trusted, which is the entire reason a
2605/// backend reads it. Guard on `api_minor >= 37` before keying authorization on that value (#164).
2606///
2607/// **Not every semantic change gets a minor, and that is the gap to watch (#122).** A minor marks a
2608/// change to this *surface*. A change to behaviour BEHIND the surface — same fields, same shapes,
2609/// different meaning — may not bump it, and is invisible to a type diff. 17 and 24 above happen to
2610/// be that class and did bump; do not infer from them that every such change will. When bumping
2611/// several minors at once, read this block end to end AND the release notes, not the diff.
2612///
2613/// That class is bigger than it looks: **10, 17, 21, 22, 23, 24 and 37 all shipped with no change
2614/// to any type in this file** — they moved meaning, not shape. Seven of the forty, and 37 is
2615/// a SECURITY fix, which is the case where a consumer most needs the guard. 38 adds a field, but
2616/// its REAL content is a meaning change to `reachable` — the field exists so the new meaning is
2617/// observable at all. A downstream
2618/// that diffs types across a multi-minor bump sees nothing for any of them.
2619pub const API_MINOR: u32 = 49;
2620
2621#[cfg(test)]
2622mod tests {
2623    use super::*;
2624
2625    /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
2626    /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
2627    /// privacy guarantee that daemon never made.
2628    #[test]
2629    fn peer_path_tags_and_defaults_to_unknown() {
2630        let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
2631        assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
2632        assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
2633        let relay = tagged(PeerPath::Relay {
2634            url: Some("https://relay.example/".into()),
2635        });
2636        assert_eq!(relay["kind"], "relay");
2637        assert_eq!(relay["url"], "https://relay.example/");
2638        // A relay whose URL we do not know still tags as relay, with the key elided.
2639        let bare = tagged(PeerPath::Relay { url: None });
2640        assert_eq!(bare["kind"], "relay");
2641        assert!(bare.get("url").is_none(), "elided, not null: {bare}");
2642
2643        // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
2644        // row. Without `#[serde(other)]` an unknown `kind` errors out of
2645        // `PeerReachability` entirely, so one new variant would break every `status` read an
2646        // older pinned client does.
2647        let future: PeerPath =
2648            serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
2649        assert_eq!(future, PeerPath::Unknown);
2650        let row: PeerReachability = serde_json::from_value(serde_json::json!({
2651            "name": "bob", "reachable": true, "path": {"kind": "quantum"}
2652        }))
2653        .expect("an unknown path kind must not fail the whole row");
2654        assert_eq!(row.path, PeerPath::Unknown);
2655        assert!(row.reachable, "the rest of the row survives");
2656
2657        // A pre-#64 row: no `path` key.
2658        let old = serde_json::json!({"name": "bob", "reachable": true});
2659        let parsed: PeerReachability = serde_json::from_value(old).unwrap();
2660        assert_eq!(
2661            parsed.path,
2662            PeerPath::Unknown,
2663            "an older daemon's row must never imply a direct path"
2664        );
2665    }
2666
2667    /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
2668    /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
2669    /// consumer projects both through one code path.
2670    #[test]
2671    fn reachability_frame_tags_and_round_trips() {
2672        let frame = StreamFrame::Reachability {
2673            peer: PeerReachability {
2674                name: "bob".into(),
2675                reachable: true,
2676                rtt_ms: Some(12),
2677                age_secs: Some(0),
2678                meta: String::new(),
2679                principal: Some("eid:beef".into()),
2680                path: Default::default(),
2681            },
2682            source: ReachabilitySource::Probe,
2683        };
2684        let v = serde_json::to_value(&frame).unwrap();
2685        assert_eq!(v["type"], "reachability");
2686        assert_eq!(v["peer"]["name"], "bob");
2687        assert_eq!(v["peer"]["reachable"], true);
2688        assert_eq!(
2689            v["peer"]["age_secs"], 0,
2690            "a transition frame is fresh by construction: {v}"
2691        );
2692        assert_eq!(v["source"], "probe", "#150: the producer is named: {v}");
2693        let back: StreamFrame = serde_json::from_value(v).unwrap();
2694        assert_eq!(back, frame);
2695    }
2696
2697    /// #150: the frame's `source` wire shape, and the two ways it must degrade.
2698    ///
2699    /// The default is the load-bearing part. An absent key comes from a daemon at `api_minor`
2700    /// 22–29, which ALREADY has both producers — so it must land on `Unknown`, never on `Probe`.
2701    /// Defaulting to `Probe` would tell a consumer "a throwaway dial saw this" about frames that
2702    /// were a live session degrading, which is the ambiguity the field exists to remove.
2703    #[test]
2704    fn reachability_source_tags_and_defaults_to_unknown() {
2705        let tagged = |s: ReachabilitySource| serde_json::to_value(s).unwrap();
2706        assert_eq!(tagged(ReachabilitySource::Probe), "probe");
2707        assert_eq!(tagged(ReachabilitySource::Session), "session");
2708        assert_eq!(tagged(ReachabilitySource::Unknown), "unknown");
2709        for s in [
2710            ReachabilitySource::Probe,
2711            ReachabilitySource::Session,
2712            ReachabilitySource::Unknown,
2713        ] {
2714            let back: ReachabilitySource = serde_json::from_value(tagged(s)).unwrap();
2715            assert_eq!(back, s, "round trip");
2716        }
2717
2718        let peer = serde_json::json!({"name": "bob", "reachable": true});
2719
2720        // A pre-#150 frame: no `source` key at all.
2721        let old: StreamFrame =
2722            serde_json::from_value(serde_json::json!({"type": "reachability", "peer": peer}))
2723                .expect("an older daemon's frame must still parse");
2724        let StreamFrame::Reachability { source, .. } = old else {
2725            panic!("expected a reachability frame");
2726        };
2727        assert_eq!(
2728            source,
2729            ReachabilitySource::Unknown,
2730            "an api_minor 22-29 daemon has BOTH producers, so an absent key must not claim Probe"
2731        );
2732
2733        // A producer from a NEWER daemon must degrade to Unknown, not fail the whole frame — the
2734        // same stake `PeerPath` buys with `#[serde(other)]`. Without the hand-written Deserialize
2735        // a third producer would break every Reachability frame an older pinned client reads.
2736        let future: StreamFrame = serde_json::from_value(
2737            serde_json::json!({"type": "reachability", "peer": peer, "source": "telemetry"}),
2738        )
2739        .expect("an unknown producer must not fail the whole frame");
2740        let StreamFrame::Reachability { source, peer } = future else {
2741            panic!("expected a reachability frame");
2742        };
2743        assert_eq!(source, ReachabilitySource::Unknown);
2744        assert!(peer.reachable, "the rest of the frame survives");
2745    }
2746
2747    /// #148: a defaulted status is EMPTY and honest — the fixture ergonomic an embedder gets in
2748    /// exchange for us adding fields.
2749    ///
2750    /// Its content is the load-bearing part. A downstream test that omits a field must not thereby
2751    /// assert something: no phantom peers or services, and the optional blocks absent rather than
2752    /// zeroed. `storage: Some(StorageInfo::default())` would read as "0 bytes on disk", which is a
2753    /// measurement nobody took.
2754    #[test]
2755    fn a_defaulted_status_is_empty_and_claims_nothing() {
2756        let d = StatusResult::default();
2757        assert!(d.peers.is_empty() && d.services.is_empty(), "{d:?}");
2758        assert!(d.reachability.is_empty() && d.presence.is_empty(), "{d:?}");
2759        assert!(d.recent_pairings.is_empty(), "{d:?}");
2760        assert_eq!(d.roster, None, "no roster is not an empty roster");
2761        assert_eq!(d.storage, None, "absent, not 0 bytes — nobody measured");
2762        assert_eq!(d.self_network, None, "absent, not offline — nobody looked");
2763        assert_eq!(d.self_user_id, None);
2764        assert!(
2765            d.stack_version.is_empty() && d.self_nickname.is_empty(),
2766            "{d:?}"
2767        );
2768
2769        // The pattern the issue actually asks for: additive growth stops breaking fixtures.
2770        let fixture = StatusResult {
2771            peers: vec![PeerInfo {
2772                name: "bob".into(),
2773                ..Default::default()
2774            }],
2775            ..Default::default()
2776        };
2777        assert_eq!(fixture.peers[0].name, "bob");
2778        assert!(fixture.services.is_empty());
2779
2780        // A default round-trips, so the elide-vs-null discipline holds for one too.
2781        let v = serde_json::to_value(&d).unwrap();
2782        assert!(v.get("roster").is_none(), "elided, not null: {v}");
2783        assert!(v.get("storage").is_none(), "elided, not null: {v}");
2784        let back: StatusResult = serde_json::from_value(v).unwrap();
2785        assert_eq!(back, d);
2786    }
2787
2788    /// #148: a defaulted reachability row is NOT reachable and makes NO path claim.
2789    ///
2790    /// This is the one default where a wrong choice would be a false guarantee rather than a
2791    /// harmless placeholder — the same trap `PeerPath`'s `#[default] Unknown` exists to avoid
2792    /// (#64), now reachable through a second door. A fixture that forgot to set `path` must not
2793    /// thereby assert the peer was reached directly, and one that forgot `reachable` must not
2794    /// claim it was up.
2795    #[test]
2796    fn a_defaulted_reachability_row_asserts_nothing_about_the_peer() {
2797        let d = PeerReachability::default();
2798        assert!(!d.reachable, "an unset row must not claim the peer is up");
2799        assert_eq!(
2800            d.path,
2801            PeerPath::Unknown,
2802            "an unset path must never read as Direct — that is a privacy claim no one made"
2803        );
2804        assert_eq!(d.rtt_ms, None, "no measurement was taken");
2805        assert_eq!(d.age_secs, None, "never probed");
2806        assert_eq!(d.principal, None);
2807        assert!(d.name.is_empty() && d.meta.is_empty());
2808    }
2809
2810    /// #148 gate: the REST of the new defaults, which the first pass left entirely unasserted —
2811    /// moving `BackendKind`'s `#[default]` to `Socket` failed nothing across the whole workspace.
2812    ///
2813    /// Each assertion below is the conservative reading of a field that could otherwise let a
2814    /// fixture assert something by omission.
2815    #[test]
2816    fn the_remaining_defaults_are_conservative() {
2817        let s = ServiceInfo::default();
2818        assert!(
2819            s.allow.is_empty(),
2820            "an unset allow must admit NOBODY — empty is deny (the gate's `any()` is false on an \
2821             empty list), and a permissive default here would be an authz hole reachable from a \
2822             fixture"
2823        );
2824        assert!(s.allow_display.is_empty() && s.name.is_empty());
2825        assert!(
2826            !s.ephemeral,
2827            "persistent is the conservative reading, and matches the wire default"
2828        );
2829        assert_eq!(
2830            s.backend,
2831            BackendKind::Run,
2832            "the documented choice — a convenience, not a claim; pinned so it cannot drift \
2833             silently out of step with its own rustdoc"
2834        );
2835        assert_eq!(BackendKind::default(), BackendKind::Run);
2836
2837        let p = PeerInfo::default();
2838        assert!(p.name.is_empty() && p.services.is_empty());
2839        assert_eq!(p.user_id, None, "no identity was proven");
2840        assert_eq!(p.principal, None);
2841
2842        // The gate's finding: this default is the documented "deliberately LAN-only" posture,
2843        // which the porcelain renders as healthy and NOT as a warning. It is unavoidable (a bool
2844        // has no third state) but it must stay deliberate, so it is pinned rather than left to
2845        // be rediscovered by whoever writes the next fixture.
2846        let n = SelfNetwork::default();
2847        assert!(!n.online, "no relay connection is established");
2848        assert!(
2849            n.relays.is_empty() && n.home_relay.is_none(),
2850            "and none are known — which the renderer reads as LAN-BY-CONFIGURATION, not as an \
2851             outage; say 'nobody looked' with StatusResult.self_network: None instead"
2852        );
2853        assert_eq!(n.last_change_epoch, None, "no transition was observed");
2854
2855        let r = RelayInfo::default();
2856        assert!(
2857            !r.connected,
2858            "an unset relay must not claim a live connection"
2859        );
2860
2861        let st = StorageInfo::default();
2862        assert_eq!(
2863            (st.audit_bytes, st.redb_bytes, st.blobs_bytes),
2864            (0, 0, 0),
2865            "zeros read as MEASURED-and-empty; `StatusResult.storage: None` is 'unmeasured'"
2866        );
2867
2868        let ro = RosterStatus::default();
2869        assert!(
2870            ro.state.is_empty(),
2871            "not a valid state word, deliberately — `doctor` warns on an unknown state rather \
2872             than reporting a healthy roster"
2873        );
2874        assert_eq!(ro.serial, 0);
2875
2876        let pp = PresencePeer::default();
2877        assert!(
2878            !pp.online,
2879            "an unset presence row must not claim the device is up"
2880        );
2881        assert!(pp.role.is_empty() && pp.user_id.is_empty());
2882
2883        let rp = RecentPairing::default();
2884        assert_eq!(rp.paired_at_epoch, 0);
2885        assert!(rp.sas_code.is_empty(), "no ceremony produced a code");
2886    }
2887
2888    /// #150 gate: "an unrecognized value reads as `unknown`" must hold for any VALUE, not just an
2889    /// unrecognized string.
2890    ///
2891    /// `#[serde(default)]` covers an absent key and nothing else, so `"source": null` — what a
2892    /// proxy or non-Rust daemon that normalizes optional fields produces — went through the
2893    /// deserializer and failed the WHOLE frame, silently dropping a liveness transition while the
2894    /// protocol doc promised the field could not break a parse. The container shapes matter
2895    /// separately: a visitor that answers without draining a map/seq desynchronizes the parser and
2896    /// fails the frame anyway, which looks identical from outside.
2897    #[test]
2898    fn a_malformed_source_degrades_instead_of_failing_the_frame() {
2899        let peer = serde_json::json!({"name": "bob", "reachable": true});
2900        for bad in [
2901            serde_json::Value::Null,
2902            serde_json::json!(7),
2903            serde_json::json!(-1),
2904            serde_json::json!(1.5),
2905            serde_json::json!(true),
2906            serde_json::json!({"kind": "probe", "nested": {"deep": [1, 2]}}),
2907            serde_json::json!(["probe", "session"]),
2908        ] {
2909            let frame: StreamFrame = serde_json::from_value(
2910                serde_json::json!({"type": "reachability", "peer": peer, "source": bad}),
2911            )
2912            .unwrap_or_else(|e| panic!("`source: {bad}` must not fail the whole frame: {e}"));
2913            let StreamFrame::Reachability { source, peer } = frame else {
2914                panic!("expected a reachability frame");
2915            };
2916            assert_eq!(source, ReachabilitySource::Unknown, "for source: {bad}");
2917            assert!(peer.reachable, "the rest of the frame survives: {bad}");
2918        }
2919    }
2920
2921    /// #90: the self-network frame tags as `{"type":"self_network","self_network":{…}}` — the
2922    /// SAME block `status` and the snapshot carry. Pinned explicitly (like the reachability
2923    /// tag) so a variant rename cannot slip past a suite whose two ends share the type while
2924    /// breaking every doc-following third-party client.
2925    #[test]
2926    fn self_network_frame_tags_and_round_trips() {
2927        let frame = StreamFrame::SelfNetwork {
2928            self_network: SelfNetwork {
2929                online: true,
2930                home_relay: Some("https://relay.example:443".into()),
2931                relays: vec![RelayInfo {
2932                    url: "https://relay.example:443".into(),
2933                    connected: true,
2934                }],
2935                direct_addrs: vec!["192.168.1.2:4444".into()],
2936                last_change_epoch: Some(1_753_842_000),
2937                identity_conflict_epoch: None,
2938                // #89: seeded NON-default so the round-trip actually carries it — an empty value
2939                // here would round-trip through a `skip_serializing_if` and prove nothing.
2940                presence_mode: Some("granted".into()),
2941            },
2942        };
2943        let v = serde_json::to_value(&frame).unwrap();
2944        assert_eq!(v["type"], "self_network");
2945        assert_eq!(v["self_network"]["online"], true);
2946        assert_eq!(v["self_network"]["home_relay"], "https://relay.example:443");
2947        assert_eq!(v["self_network"]["relays"][0]["connected"], true);
2948        assert_eq!(
2949            v["self_network"]["presence_mode"], "granted",
2950            "#89: the live presence mode must reach the wire — it is the only way an operator can \
2951             confirm the knob took effect, and a product's privacy switch has nothing to render \
2952             without it"
2953        );
2954        let back: StreamFrame = serde_json::from_value(v).unwrap();
2955        assert_eq!(back, frame);
2956    }
2957
2958    #[test]
2959    fn peer_reachability_serde_is_additive() {
2960        let r = PeerReachability {
2961            name: "bob".into(),
2962            reachable: true,
2963            rtt_ms: Some(42),
2964            age_secs: Some(3),
2965            meta: String::new(),
2966            principal: None,
2967            path: Default::default(),
2968        };
2969        let v = serde_json::to_value(&r).unwrap();
2970        assert_eq!(v["name"], "bob");
2971        assert_eq!(v["reachable"], true);
2972        assert_eq!(v["rtt_ms"], 42);
2973        assert_eq!(v["age_secs"], 3);
2974        // Never-probed peer: optionals elided, not null.
2975        let unknown = PeerReachability {
2976            name: "carol".into(),
2977            reachable: false,
2978            rtt_ms: None,
2979            age_secs: None,
2980            meta: String::new(),
2981            principal: None,
2982            path: Default::default(),
2983        };
2984        let uv = serde_json::to_value(&unknown).unwrap();
2985        assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
2986        // An older StatusResult (no reachability field) still deserializes.
2987        let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
2988        let s: StatusResult = serde_json::from_value(old).unwrap();
2989        assert!(s.reachability.is_empty());
2990    }
2991
2992    #[test]
2993    fn subscribe_method_tag_resolves() {
2994        let req = serde_json::to_value(Request::Subscribe).unwrap();
2995        assert_eq!(method_of(&req), Some("subscribe"));
2996    }
2997
2998    // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
2999
3000    #[test]
3001    fn invite_params_reject_singular_service_typo() {
3002        // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
3003        // `InviteParams { services: [] }` and mint a grants-nothing invite that looked
3004        // successful. With deny_unknown_fields the typo is a loud parse error instead.
3005        let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
3006        assert!(
3007            err.is_err(),
3008            "an unknown `service` key must be rejected, not silently ignored"
3009        );
3010        // The correct plural shape still parses.
3011        let ok: InviteParams =
3012            serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
3013        assert_eq!(ok.services, vec!["kb".to_string()]);
3014    }
3015
3016    #[test]
3017    fn open_session_params_reject_unknown_field() {
3018        let err = serde_json::from_value::<OpenSessionParams>(
3019            serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
3020        );
3021        assert!(err.is_err(), "unknown params keys must be rejected");
3022    }
3023
3024    #[test]
3025    fn set_app_metadata_request_carries_the_method_tag() {
3026        let r = Request::SetAppMetadata(SetAppMetadataParams {
3027            metadata: "v=1.2.3".into(),
3028        });
3029        let v = serde_json::to_value(&r).unwrap();
3030        assert_eq!(v["method"], "set_app_metadata");
3031        assert_eq!(v["params"]["metadata"], "v=1.2.3");
3032        assert_eq!(method_of(&v), Some("set_app_metadata"));
3033    }
3034
3035    #[test]
3036    fn set_app_metadata_params_reject_unknown_field() {
3037        let err = serde_json::from_value::<SetAppMetadataParams>(
3038            serde_json::json!({"metadata": "x", "nonsense": 1}),
3039        );
3040        assert!(err.is_err(), "unknown params keys must be rejected");
3041    }
3042
3043    /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
3044    /// empty meta does not serialize.
3045    #[test]
3046    fn peer_info_principal_is_additive() {
3047        // An older payload (no principal) still deserializes; empty does not serialize.
3048        let old = serde_json::json!({"name": "bob", "services": ["notes"]});
3049        let p: PeerInfo = serde_json::from_value(old).unwrap();
3050        assert_eq!(p.principal, None);
3051        assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
3052        // A bound peer carries BOTH the person user_id AND the device principal (#41).
3053        let full = PeerInfo {
3054            name: "bob".into(),
3055            services: vec!["notes".into()],
3056            user_id: Some("b64u:BOB".into()),
3057            principal: Some("eid:0707".into()),
3058        };
3059        let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
3060        assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
3061        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
3062    }
3063
3064    #[test]
3065    fn active_session_principal_is_additive() {
3066        // An OLD payload (no `principal`) must still deserialize — #73 is additive.
3067        let old: ActiveSession =
3068            serde_json::from_str(r#"{"peer":"bob","service":"notes","opened_at":7}"#).unwrap();
3069        assert_eq!(old.principal, None, "serde(default) supplies it");
3070
3071        // And a `None` must not serialize, so an old client sees the shape it expects.
3072        let json = serde_json::to_string(&old).unwrap();
3073        assert!(
3074            !json.contains("principal"),
3075            "skip_serializing_if must omit it: {json}"
3076        );
3077
3078        // A real row round-trips the principal.
3079        let new = ActiveSession {
3080            peer: "bob".into(),
3081            service: "notes".into(),
3082            opened_at: 7,
3083            principal: Some("eid:1f0a".into()),
3084        };
3085        let back: ActiveSession =
3086            serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap();
3087        assert_eq!(back.principal.as_deref(), Some("eid:1f0a"));
3088    }
3089
3090    #[test]
3091    fn peer_reachability_principal_is_additive() {
3092        // Older payload (no principal) still deserializes; empty does not serialize; a set
3093        // value round-trips alongside the #40 meta so an embedder joins on the principal.
3094        let old = serde_json::json!({"name": "bob", "reachable": true});
3095        let r: PeerReachability = serde_json::from_value(old).unwrap();
3096        assert_eq!(r.principal, None);
3097        assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
3098        let full = PeerReachability {
3099            name: "bob".into(),
3100            reachable: true,
3101            rtt_ms: Some(12),
3102            age_secs: Some(3),
3103            meta: "v=1.2.3".into(),
3104            principal: Some("eid:0707".into()),
3105            path: Default::default(),
3106        };
3107        let back: PeerReachability =
3108            serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
3109        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
3110        assert_eq!(back.meta, "v=1.2.3");
3111    }
3112
3113    #[test]
3114    fn peer_reachability_meta_is_additive() {
3115        // An older payload (no meta) still deserializes; an empty meta does not serialize.
3116        let old = serde_json::json!({"name": "bob", "reachable": true});
3117        let r: PeerReachability = serde_json::from_value(old).unwrap();
3118        assert_eq!(r.meta, "");
3119        assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
3120        // A set value round-trips.
3121        let with = PeerReachability {
3122            name: "bob".into(),
3123            reachable: true,
3124            rtt_ms: Some(12),
3125            age_secs: Some(3),
3126            meta: "v=1.2.3".into(),
3127            principal: None,
3128            path: Default::default(),
3129        };
3130        let back: PeerReachability =
3131            serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
3132        assert_eq!(back.meta, "v=1.2.3");
3133    }
3134
3135    #[test]
3136    fn presence_peer_meta_is_additive() {
3137        let old = serde_json::json!({
3138            "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
3139        });
3140        let p: PresencePeer = serde_json::from_value(old).unwrap();
3141        assert_eq!(p.meta, "");
3142        assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
3143    }
3144
3145    #[test]
3146    fn set_nickname_request_carries_the_method_tag() {
3147        let r = Request::SetNickname(SetNicknameParams {
3148            nickname: "workbench".into(),
3149        });
3150        let v = serde_json::to_value(&r).unwrap();
3151        assert_eq!(v["method"], "set_nickname");
3152        assert_eq!(v["params"]["nickname"], "workbench");
3153        assert_eq!(method_of(&v), Some("set_nickname"));
3154    }
3155
3156    #[test]
3157    fn set_nickname_params_reject_unknown_field() {
3158        let err = serde_json::from_value::<SetNicknameParams>(
3159            serde_json::json!({"nickname": "x", "nonsense": 1}),
3160        );
3161        assert!(err.is_err(), "unknown params keys must be rejected");
3162    }
3163
3164    /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
3165    /// the additive-only contract — and an empty name must not serialize at all.
3166    #[test]
3167    fn status_self_nickname_is_additive() {
3168        let old = serde_json::json!({
3169            "stack_version": "0.7.0", "services": [], "peers": []
3170        });
3171        let s: StatusResult = serde_json::from_value(old).unwrap();
3172        assert_eq!(s.self_nickname, "");
3173        let v = serde_json::to_value(&s).unwrap();
3174        assert!(v.get("self_nickname").is_none(), "empty name is skipped");
3175    }
3176
3177    #[test]
3178    fn api_minor_is_present_and_monotonic_from_hello() {
3179        // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
3180        // crate/stack version, additive on the Hello frame.
3181        let h = Hello {
3182            api: API_NAME.into(),
3183            api_version: API_VERSION.into(),
3184            api_minor: API_MINOR,
3185            stack_version: "9.9.9".into(),
3186        };
3187        let v = serde_json::to_value(&h).unwrap();
3188        assert_eq!(v["api_minor"], API_MINOR);
3189        // An OLD Hello without api_minor still deserializes (additive contract).
3190        let old = serde_json::json!({
3191            "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
3192        });
3193        let back: Hello = serde_json::from_value(old).unwrap();
3194        assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
3195    }
3196
3197    #[test]
3198    fn hello_result_roundtrips() {
3199        let h = Hello {
3200            api: "mcpmesh-local/1".into(),
3201            api_version: "1.0".into(),
3202            api_minor: 0,
3203            stack_version: "0.1.0".into(),
3204        };
3205        let v = serde_json::to_value(&h).unwrap();
3206        assert_eq!(v["api"], "mcpmesh-local/1");
3207        let back: Hello = serde_json::from_value(v).unwrap();
3208        assert_eq!(back, h);
3209    }
3210
3211    #[test]
3212    fn request_tagged_by_method() {
3213        let r = Request::Status;
3214        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
3215        let r = Request::OpenSession(OpenSessionParams {
3216            peer: "alice".into(),
3217            service: "notes".into(),
3218        });
3219        let v = serde_json::to_value(&r).unwrap();
3220        assert_eq!(v["method"], "open_session");
3221        assert_eq!(v["params"]["peer"], "alice");
3222    }
3223
3224    #[test]
3225    fn parameterless_method_tolerates_params_forms() {
3226        // Omitted and null params deserialize straight into the unit variant.
3227        let omitted: Request =
3228            serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
3229        assert_eq!(omitted, Request::Status);
3230        let null: Request =
3231            serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
3232                .unwrap();
3233        assert_eq!(null, Request::Status);
3234
3235        // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
3236        // the server MUST dispatch on the method string rather than deserialize the whole
3237        // message into `Request`. This is the pattern the daemon's dispatcher uses.
3238        let empty = serde_json::json!({"method": "status", "params": {}});
3239        assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
3240        match method_of(&empty) {
3241            Some("status") => {} // dispatcher resolves Status via the method string
3242            other => panic!("method_of failed to resolve status: {other:?}"),
3243        }
3244    }
3245
3246    #[test]
3247    fn backend_spec_roundtrips() {
3248        let run = BackendSpec::Run {
3249            cmd: vec!["notes-mcp".into(), "--stdio".into()],
3250            env: Default::default(),
3251            cwd: None,
3252        };
3253        let v = serde_json::to_value(&run).unwrap();
3254        assert_eq!(v["run"]["cmd"][0], "notes-mcp");
3255        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
3256
3257        let sock = BackendSpec::Socket {
3258            path: "/run/notes.sock".into(),
3259        };
3260        let v = serde_json::to_value(&sock).unwrap();
3261        assert_eq!(v["socket"]["path"], "/run/notes.sock");
3262        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
3263    }
3264
3265    #[test]
3266    fn register_service_wire_shape() {
3267        let r = Request::RegisterService(RegisterServiceParams {
3268            name: "notes".into(),
3269            backend: BackendSpec::Run {
3270                cmd: vec!["notes-mcp".into()],
3271                env: Default::default(),
3272                cwd: None,
3273            },
3274            allow: vec!["alice".into()],
3275            ephemeral: false,
3276            rate_limit_per_min: None,
3277        });
3278        let v = serde_json::to_value(&r).unwrap();
3279        assert_eq!(
3280            v,
3281            serde_json::json!({
3282                "method": "register_service",
3283                "params": {
3284                    "name": "notes",
3285                    "backend": {"run": {"cmd": ["notes-mcp"]}},
3286                    "allow": ["alice"],
3287                }
3288            })
3289        );
3290        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3291    }
3292
3293    #[test]
3294    fn invite_request_and_result_roundtrip() {
3295        // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
3296        let r = Request::Invite(InviteParams {
3297            services: vec!["notes".into(), "kb".into()],
3298            app_label: None,
3299            max_uses: None,
3300            // #87: seeded NON-None so the round-trip actually carries it — `None` rides
3301            // `skip_serializing_if` straight past the assertion and proves nothing.
3302            peer_nickname: Some("laptop-of-alice".into()),
3303            as_self: false,
3304        });
3305        let v = serde_json::to_value(&r).unwrap();
3306        assert_eq!(v["method"], "invite");
3307        assert_eq!(
3308            v["params"]["peer_nickname"], "laptop-of-alice",
3309            "#87: the inviter's local alias for the redeemer must reach the wire"
3310        );
3311        assert_eq!(v["params"]["services"][0], "notes");
3312        assert_eq!(v["params"]["services"][1], "kb");
3313        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3314        // method_of resolves the tag generically (no per-variant arm).
3315        assert_eq!(
3316            method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
3317            Some("invite")
3318        );
3319
3320        // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
3321        let res = InviteResult {
3322            invite_line: "mcpmesh-invite:ABCDEF".into(),
3323            expires_at_epoch: 1_800_000_000,
3324            uses_remaining: 1,
3325        };
3326        let v = serde_json::to_value(&res).unwrap();
3327        assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
3328        assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
3329        assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
3330    }
3331
3332    #[test]
3333    fn pair_request_and_result_roundtrip() {
3334        // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
3335        let r = Request::Pair(PairParams {
3336            invite_line: "mcpmesh-invite:ABCDEF".into(),
3337            as_nickname: Some("alice-mbp".into()),
3338            allow_self_enroll: true,
3339        });
3340        let v = serde_json::to_value(&r).unwrap();
3341        assert_eq!(v["method"], "pair");
3342        assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
3343        assert_eq!(
3344            v["params"]["as_nickname"], "alice-mbp",
3345            "#87: the redeemer's local alias for the inviter must reach the wire"
3346        );
3347        assert_eq!(
3348            v["params"]["allow_self_enroll"], true,
3349            "#178: the caller's consent to a self-enrollment must reach the wire — the daemon \
3350             refuses the ceremony without it"
3351        );
3352        // An OLD caller's payload — no alias — must still decode. The field is additive.
3353        let legacy: PairParams =
3354            serde_json::from_value(serde_json::json!({"invite_line": "x"})).unwrap();
3355        assert_eq!(legacy.as_nickname, None);
3356        // #178: and the consent defaults to REFUSING. A caller that predates the field, or one that
3357        // simply never set it, must not be read as having offered a device enrollment — that is the
3358        // whole guard, and a `#[serde(default)]` flipping to `true` would silently remove it.
3359        assert!(
3360            !legacy.allow_self_enroll,
3361            "an absent allow_self_enroll must default to false (refuse), never to true"
3362        );
3363        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3364        // method_of resolves the tag generically (no per-variant arm).
3365        assert_eq!(
3366            method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
3367            Some("pair")
3368        );
3369
3370        // PairResult carries the inviter's suggested nickname + the display-only SAS words +
3371        // the granted services (the porcelain renders each as `<peer>/<service>`).
3372        let res = PairResult {
3373            peer_nickname: "alice".into(),
3374            sas_code: "tango-fig-cabbage".into(),
3375            services: vec!["notes".into(), "kb".into()],
3376            app_label: None,
3377            peer_user_id: None,
3378            enrolled_as_self: false,
3379        };
3380        let v = serde_json::to_value(&res).unwrap();
3381        assert_eq!(v["peer_nickname"], "alice");
3382        assert_eq!(v["sas_code"], "tango-fig-cabbage");
3383        assert_eq!(v["services"][0], "notes");
3384        assert_eq!(v["services"][1], "kb");
3385        assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
3386
3387        // Additive-only: a PairResult minted by an older daemon (no `services` key) still
3388        // deserializes — the `#[serde(default)]` fills it with an empty list.
3389        let old_shape = serde_json::json!({
3390            "peer_nickname": "alice",
3391            "sas_code": "tango-fig-cabbage",
3392        });
3393        let back: PairResult = serde_json::from_value(old_shape).unwrap();
3394        assert_eq!(back.peer_nickname, "alice");
3395        assert!(back.services.is_empty());
3396    }
3397
3398    #[test]
3399    fn roster_install_request_and_result_roundtrip() {
3400        // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
3401        // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
3402        let r = Request::RosterInstall(RosterInstallParams {
3403            path: "/tmp/roster.json".into(),
3404            org_root_pk: Some("b64u:AAAA".into()),
3405        });
3406        let v = serde_json::to_value(&r).unwrap();
3407        assert_eq!(v["method"], "roster_install");
3408        assert_eq!(v["params"]["path"], "/tmp/roster.json");
3409        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
3410        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3411        // method_of resolves the tag generically (no per-variant arm).
3412        assert_eq!(
3413            method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
3414            Some("roster_install")
3415        );
3416
3417        // When the pk is omitted (a subsequent install using the pinned value), it is
3418        // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
3419        let omit = Request::RosterInstall(RosterInstallParams {
3420            path: "/tmp/roster.json".into(),
3421            org_root_pk: None,
3422        });
3423        let v = serde_json::to_value(&omit).unwrap();
3424        assert!(
3425            v["params"].get("org_root_pk").is_none(),
3426            "an omitted org_root_pk must not appear on the wire: {v}"
3427        );
3428        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
3429
3430        // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
3431        let res = RosterInstallResult {
3432            org_id: "acme".into(),
3433            serial: 42,
3434            severed: 1,
3435        };
3436        let v = serde_json::to_value(&res).unwrap();
3437        assert_eq!(v["org_id"], "acme");
3438        assert_eq!(v["serial"], 42u64);
3439        assert_eq!(v["severed"], 1u32);
3440        assert_eq!(
3441            serde_json::from_value::<RosterInstallResult>(v).unwrap(),
3442            res
3443        );
3444
3445        // Additive-only: a result minted by an older daemon (no `severed` key) still
3446        // deserializes — the `#[serde(default)]` fills it with 0.
3447        let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
3448        let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
3449        assert_eq!(back.serial, 7);
3450        assert_eq!(back.severed, 0);
3451    }
3452
3453    #[test]
3454    fn org_join_request_and_result_roundtrip() {
3455        // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
3456        // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
3457        let r = Request::OrgJoin(OrgJoinParams {
3458            org_id: "acme".into(),
3459            org_root_pk: "b64u:AAAA".into(),
3460            user_id: "alice".into(),
3461            user_key: "/home/alice/.config/mcpmesh/user.key".into(),
3462        });
3463        let v = serde_json::to_value(&r).unwrap();
3464        assert_eq!(v["method"], "org_join");
3465        assert_eq!(v["params"]["org_id"], "acme");
3466        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
3467        assert_eq!(v["params"]["user_id"], "alice");
3468        assert_eq!(
3469            v["params"]["user_key"],
3470            "/home/alice/.config/mcpmesh/user.key"
3471        );
3472        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3473        // method_of resolves the tag generically (no per-variant arm).
3474        assert_eq!(
3475            method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
3476            Some("org_join")
3477        );
3478
3479        // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
3480        let res = OrgJoinResult {
3481            org_id: "acme".into(),
3482            restart_required: true,
3483        };
3484        let v = serde_json::to_value(&res).unwrap();
3485        assert_eq!(v["org_id"], "acme");
3486        assert_eq!(
3487            v["restart_required"], true,
3488            "#93: a half-live join must reach the wire — the caller cannot detect it any other way"
3489        );
3490        // Additive: an older daemon omits it, and absent reads as `false` — which was that
3491        // daemon's implicit answer. Pinned so the default cannot silently flip to `true` and start
3492        // telling every caller to restart.
3493        let legacy: OrgJoinResult =
3494            serde_json::from_value(serde_json::json!({"org_id": "acme"})).unwrap();
3495        assert!(!legacy.restart_required);
3496        // …and the false case must not bloat the payload.
3497        let quiet = serde_json::to_value(OrgJoinResult {
3498            org_id: "acme".into(),
3499            restart_required: false,
3500        })
3501        .unwrap();
3502        assert!(quiet.get("restart_required").is_none());
3503        assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
3504    }
3505
3506    #[test]
3507    fn set_roster_url_request_roundtrip() {
3508        // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
3509        let r = Request::SetRosterUrl(SetRosterUrlParams {
3510            url: "https://intranet.acme.com/roster.json".into(),
3511        });
3512        let v = serde_json::to_value(&r).unwrap();
3513        assert_eq!(v["method"], "set_roster_url");
3514        assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
3515        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3516        assert_eq!(
3517            method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
3518            Some("set_roster_url")
3519        );
3520    }
3521
3522    #[test]
3523    fn peer_remove_request_roundtrip() {
3524        // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
3525        let r = Request::PeerRemove(PeerRemoveParams {
3526            nickname: "bob".into(),
3527        });
3528        let v = serde_json::to_value(&r).unwrap();
3529        assert_eq!(v["method"], "peer_remove");
3530        assert_eq!(v["params"]["nickname"], "bob");
3531        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3532        // method_of resolves the tag generically (no per-variant arm).
3533        assert_eq!(
3534            method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
3535            Some("peer_remove")
3536        );
3537    }
3538
3539    /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
3540    /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
3541    /// defaulting to empty when absent.
3542    /// #65: the wire tags for the introduction pair. The serde tag must equal the dispatch string
3543    /// the daemon matches on — nothing else checks that they agree.
3544    #[test]
3545    fn peer_introduce_and_endorse_roundtrip() {
3546        let r = Request::PeerIntroduce(PeerIntroduceParams {
3547            subject: "eid:aa".into(),
3548            endorsed_by: "b64u:carol".into(),
3549            evidence: "b64u:sig".into(),
3550            subject_user_id: Some("b64u:bob".into()),
3551            subject_binding: Some("b64u:bind".into()),
3552            nickname: "bob".into(),
3553        });
3554        let v = serde_json::to_value(&r).unwrap();
3555        assert_eq!(
3556            v["method"], "peer_introduce",
3557            "the tag must match the daemon's dispatch string exactly"
3558        );
3559        assert_eq!(v["params"]["subject"], "eid:aa");
3560        assert_eq!(v["params"]["subject_binding"], "b64u:bind");
3561        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3562
3563        // The two proof fields are OPTIONAL on the wire and omitted when absent.
3564        let minimal = Request::PeerIntroduce(PeerIntroduceParams {
3565            subject: "eid:aa".into(),
3566            endorsed_by: "b64u:carol".into(),
3567            evidence: "b64u:sig".into(),
3568            subject_user_id: None,
3569            subject_binding: None,
3570            nickname: "bob".into(),
3571        });
3572        let v = serde_json::to_value(&minimal).unwrap();
3573        assert!(v["params"].get("subject_user_id").is_none());
3574        assert!(v["params"].get("subject_binding").is_none());
3575        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), minimal);
3576
3577        let e = Request::PeerEndorse(PeerEndorseParams {
3578            subject: "eid:aa".into(),
3579            subject_user_id: None,
3580        });
3581        let v = serde_json::to_value(&e).unwrap();
3582        assert_eq!(v["method"], "peer_endorse");
3583        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), e);
3584
3585        let res = PeerEndorseResult {
3586            endorsed_by: "b64u:me".into(),
3587            evidence: "b64u:sig".into(),
3588        };
3589        let v = serde_json::to_value(&res).unwrap();
3590        assert_eq!(v["endorsed_by"], "b64u:me");
3591        assert_eq!(serde_json::from_value::<PeerEndorseResult>(v).unwrap(), res);
3592    }
3593
3594    #[test]
3595    fn peer_add_request_roundtrip() {
3596        let r = Request::PeerAdd(PeerAddParams {
3597            nickname: "bob".into(),
3598            endpoint_id: "96246d3f".into(),
3599            allow: vec!["notes".into()],
3600        });
3601        let v = serde_json::to_value(&r).unwrap();
3602        assert_eq!(v["method"], "peer_add");
3603        assert_eq!(v["params"]["nickname"], "bob");
3604        assert_eq!(v["params"]["endpoint_id"], "96246d3f");
3605        assert_eq!(v["params"]["allow"][0], "notes");
3606        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3607        // An absent allow list deserializes to empty (the server-side tolerance).
3608        let p: PeerAddParams =
3609            serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
3610                .unwrap();
3611        assert!(p.allow.is_empty());
3612    }
3613
3614    #[test]
3615    fn peer_rename_request_roundtrip() {
3616        // By user_id (renames all of a person's devices in one op).
3617        let r = Request::PeerRename(PeerRenameParams {
3618            user_id: Some("b64u:BOB".into()),
3619            nickname: None,
3620            to: "Bobby".into(),
3621        });
3622        let v = serde_json::to_value(&r).unwrap();
3623        assert_eq!(v["method"], "peer_rename");
3624        assert_eq!(v["params"]["user_id"], "b64u:BOB");
3625        assert_eq!(v["params"]["to"], "Bobby");
3626        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3627        // A provisional contact is renamed by nickname; omitted user_id defaults to None.
3628        assert_eq!(
3629            method_of(
3630                &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
3631            ),
3632            Some("peer_rename")
3633        );
3634    }
3635
3636    #[test]
3637    fn status_result_roundtrips() {
3638        // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
3639        // older payload with no `roster` key still deserializes to None (serde default).
3640        let s = StatusResult {
3641            stack_version: "0.1.0".into(),
3642            services: vec![ServiceInfo {
3643                name: "notes".into(),
3644                allow: vec!["alice".into()],
3645                allow_display: vec![],
3646                backend: BackendKind::Run,
3647                ephemeral: false,
3648            }],
3649            peers: vec![PeerInfo {
3650                name: "alice".into(),
3651                services: vec!["notes".into()],
3652                // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
3653                user_id: Some("b64u:alicepk".into()),
3654                principal: None,
3655            }],
3656            roster: None,
3657            presence: vec![],
3658            self_user_id: Some("b64u:selfpk".into()),
3659            recent_pairings: vec![],
3660            reachability: vec![],
3661            self_nickname: String::new(),
3662            storage: None,
3663            self_network: None,
3664        };
3665        let v = serde_json::to_value(&s).unwrap();
3666        assert_eq!(v["services"][0]["backend"], "run");
3667        // The additive identity fields ride the wire when present.
3668        assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
3669        assert_eq!(v["self_user_id"], "b64u:selfpk");
3670        assert!(
3671            v.get("roster").is_none(),
3672            "an absent roster must not appear on the wire: {v}"
3673        );
3674        assert!(
3675            v.get("presence").is_none(),
3676            "an empty presence must not appear on the wire: {v}"
3677        );
3678        assert!(
3679            v.get("recent_pairings").is_none(),
3680            "an empty recent_pairings must not appear on the wire: {v}"
3681        );
3682        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
3683
3684        // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
3685        // deserializes — the identity fields default to None / a nickname-only peer.
3686        let old_shape = serde_json::json!({
3687            "stack_version": "0.1.0",
3688            "services": [],
3689            "peers": [{ "name": "bob", "services": [] }],
3690        });
3691        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
3692        assert!(back.roster.is_none());
3693        assert!(back.presence.is_empty());
3694        assert!(back.self_user_id.is_none());
3695        assert!(back.peers[0].user_id.is_none());
3696        assert!(back.recent_pairings.is_empty());
3697
3698        // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
3699        // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
3700        let s = StatusResult {
3701            stack_version: "0.1.0".into(),
3702            services: vec![],
3703            peers: vec![],
3704            roster: Some(RosterStatus {
3705                org_id: "acme".into(),
3706                serial: 42,
3707                state: "approved".into(),
3708                org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
3709                groups: vec!["eng".into(), "ops".into()],
3710            }),
3711            presence: vec![
3712                PresencePeer {
3713                    user_id: "alice".into(),
3714                    display_name: "Alice Example".into(),
3715                    groups: vec!["eng".into()],
3716                    device_label: "laptop".into(),
3717                    role: "primary".into(),
3718                    online: true,
3719                    meta: String::new(),
3720                },
3721                PresencePeer {
3722                    user_id: "alice".into(),
3723                    display_name: "Alice Example".into(),
3724                    groups: vec!["eng".into()],
3725                    device_label: "desktop".into(),
3726                    role: "mirror".into(),
3727                    online: false,
3728                    meta: String::new(),
3729                },
3730            ],
3731            self_user_id: None,
3732            recent_pairings: vec![],
3733            reachability: vec![],
3734            self_nickname: String::new(),
3735            storage: None,
3736            self_network: None,
3737        };
3738        let v = serde_json::to_value(&s).unwrap();
3739        assert_eq!(v["roster"]["org_id"], "acme");
3740        assert_eq!(v["roster"]["serial"], 42u64);
3741        assert_eq!(v["roster"]["state"], "approved");
3742        assert_eq!(
3743            v["roster"]["org_root_fingerprint"],
3744            "tango-fig-cabbage-anchor"
3745        );
3746        assert_eq!(v["presence"][0]["user_id"], "alice");
3747        assert_eq!(v["presence"][0]["device_label"], "laptop");
3748        assert_eq!(v["presence"][0]["role"], "primary");
3749        assert_eq!(v["presence"][0]["online"], true);
3750        assert_eq!(v["presence"][1]["online"], false);
3751        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
3752    }
3753
3754    /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
3755    /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
3756    /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
3757    /// older daemon (no key at all) still deserializes to empty.
3758    #[test]
3759    fn recent_pairings_are_additive_on_status() {
3760        let s = StatusResult {
3761            stack_version: "0.1.0".into(),
3762            services: vec![],
3763            peers: vec![],
3764            roster: None,
3765            presence: vec![],
3766            self_user_id: None,
3767            recent_pairings: vec![RecentPairing {
3768                peer_nickname: "bob".into(),
3769                sas_code: "tango-fig-cabbage".into(),
3770                paired_at_epoch: 1_800_000_000,
3771            }],
3772            reachability: vec![],
3773            self_nickname: String::new(),
3774            storage: None,
3775            self_network: None,
3776        };
3777        let v = serde_json::to_value(&s).unwrap();
3778        assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
3779        assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
3780        assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
3781        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
3782
3783        // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
3784        // the `#[serde(default)]` fills it with an empty list.
3785        let old_shape = serde_json::json!({
3786            "stack_version": "0.1.0",
3787            "services": [],
3788            "peers": [],
3789        });
3790        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
3791        assert!(back.recent_pairings.is_empty());
3792    }
3793
3794    #[test]
3795    fn blob_requests_and_results_roundtrip() {
3796        // BlobPublish → { method, params: { scope, path } }.
3797        let r = Request::BlobPublish(BlobPublishParams {
3798            scope: "docs".into(),
3799            path: "/tmp/a.bin".into(),
3800        });
3801        let v = serde_json::to_value(&r).unwrap();
3802        assert_eq!(v["method"], "blob_publish");
3803        assert_eq!(v["params"]["scope"], "docs");
3804        assert_eq!(v["params"]["path"], "/tmp/a.bin");
3805        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3806
3807        // BlobGrant → { method, params: { scope, principal } }.
3808        // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
3809        // would otherwise ship undetected — the e2e test calls the provider directly and never
3810        // crosses JSON-RPC.
3811        let rev = Request::BlobRevoke(BlobRevokeParams {
3812            scope: "photos".into(),
3813            principals: vec!["alice".into()],
3814        });
3815        let v = serde_json::to_value(&rev).unwrap();
3816        assert_eq!(v["method"], "blob_revoke");
3817        assert_eq!(v["params"]["principals"][0], "alice");
3818        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
3819
3820        let unp = Request::BlobUnpublish(BlobUnpublishParams {
3821            scope: "photos".into(),
3822            hash: "abc123".into(),
3823        });
3824        let v = serde_json::to_value(&unp).unwrap();
3825        assert_eq!(v["method"], "blob_unpublish");
3826        assert_eq!(v["params"]["hash"], "abc123");
3827        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
3828
3829        let r = Request::BlobGrant(BlobGrantParams {
3830            scope: "docs".into(),
3831            principal: "alice".into(),
3832        });
3833        let v = serde_json::to_value(&r).unwrap();
3834        assert_eq!(v["method"], "blob_grant");
3835        assert_eq!(v["params"]["principal"], "alice");
3836        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3837
3838        // BlobList is parameterless (method_of resolves it).
3839        assert_eq!(
3840            method_of(&serde_json::json!({"method": "blob_list"})),
3841            Some("blob_list")
3842        );
3843
3844        // BlobFetch → { method, params: { ticket, dest_path, from? } }.
3845        let r = Request::BlobFetch(BlobFetchParams {
3846            ticket: "blobAAA".into(),
3847            dest_path: "/tmp/out.bin".into(),
3848            from: vec!["eid:aa".into(), "b64u:bb".into()],
3849        });
3850        let v = serde_json::to_value(&r).unwrap();
3851        assert_eq!(v["method"], "blob_fetch");
3852        assert_eq!(v["params"]["ticket"], "blobAAA");
3853        assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
3854        assert_eq!(
3855            v["params"]["from"][0], "eid:aa",
3856            "#83: the alternate sources must reach the wire IN ORDER — the publisher is tried \
3857             first and these follow, so a reordering changes which source answers"
3858        );
3859        assert_eq!(v["params"]["from"][1], "b64u:bb");
3860        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
3861        // Additive: an older caller omits it, and absent reads as EMPTY — the single-source
3862        // behaviour. A default that invented sources would dial peers the caller never named.
3863        let legacy: BlobFetchParams =
3864            serde_json::from_value(serde_json::json!({"ticket": "x", "dest_path": "/tmp/y"}))
3865                .unwrap();
3866        assert!(legacy.from.is_empty());
3867        // …and an empty list must not bloat the payload.
3868        let quiet = serde_json::to_value(Request::BlobFetch(BlobFetchParams {
3869            ticket: "x".into(),
3870            dest_path: "/tmp/y".into(),
3871            from: vec![],
3872        }))
3873        .unwrap();
3874        assert!(quiet["params"].get("from").is_none());
3875
3876        // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
3877        let res = BlobPublishResult {
3878            ticket: "blobAAA".into(),
3879            hash: "ab".repeat(32),
3880        };
3881        let v = serde_json::to_value(&res).unwrap();
3882        assert_eq!(v["ticket"], "blobAAA");
3883        assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
3884
3885        // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
3886        let res = BlobScopeList {
3887            scopes: vec![ScopeInfo {
3888                name: "docs".into(),
3889                hashes: vec!["ab".repeat(32)],
3890                grants: vec!["alice".into()],
3891                withdrawn: vec![],
3892                hash_count: 1,
3893                grant_count: 1,
3894                withdrawn_count: 0,
3895            }],
3896            total: 1,
3897            truncated: false,
3898        };
3899        let v = serde_json::to_value(&res).unwrap();
3900        assert_eq!(v["scopes"][0]["name"], "docs");
3901        assert_eq!(v["scopes"][0]["grants"][0], "alice");
3902        assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
3903
3904        // BlobFetchResult carries the verified hash + byte length.
3905        let res = BlobFetchResult {
3906            hash: "ab".repeat(32),
3907            bytes_len: 4194304,
3908        };
3909        let v = serde_json::to_value(&res).unwrap();
3910        assert_eq!(v["bytes_len"], 4194304u64);
3911        assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
3912    }
3913
3914    /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
3915    /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
3916    /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
3917    /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
3918    #[test]
3919    fn stream_frames_roundtrip_with_the_documented_tags() {
3920        let snap = StreamFrame::Snapshot {
3921            self_network: None,
3922            active_sessions: vec![ActiveSession {
3923                peer: "bob".into(),
3924                service: "notes".into(),
3925                opened_at: 1_751_760_000,
3926                principal: None,
3927            }],
3928            reachability: vec![PeerReachability {
3929                name: "bob".into(),
3930                reachable: true,
3931                rtt_ms: Some(42),
3932                age_secs: Some(3),
3933                meta: String::new(),
3934                principal: None,
3935                path: Default::default(),
3936            }],
3937        };
3938        let v = serde_json::to_value(&snap).unwrap();
3939        assert_eq!(v["type"], "snapshot");
3940        assert_eq!(v["active_sessions"][0]["peer"], "bob");
3941        assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
3942        assert_eq!(v["reachability"][0]["name"], "bob");
3943        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
3944
3945        let event = StreamFrame::Event {
3946            record: Box::new(AuditRecord::session_open(
3947                "2026-07-03T14:02:11.480Z".into(),
3948                Some("bob".into()),
3949                "notes".into(),
3950                None,
3951            )),
3952        };
3953        let v = serde_json::to_value(&event).unwrap();
3954        assert_eq!(v["type"], "event");
3955        // The record's fields ride verbatim under `record` — no Box indirection on the wire.
3956        assert_eq!(v["record"]["kind"], "session_open");
3957        assert_eq!(v["record"]["peer"], "bob");
3958        assert_eq!(v["record"]["service"], "notes");
3959        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
3960
3961        let lagged = StreamFrame::Lagged { dropped: 12 };
3962        let v = serde_json::to_value(&lagged).unwrap();
3963        assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
3964        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
3965    }
3966
3967    /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
3968    /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
3969    /// raw `Value` stream instead (`ControlClient::open_stream`).
3970    #[test]
3971    fn unknown_stream_frame_type_is_rejected() {
3972        let future = serde_json::json!({ "type": "future_kind", "x": 1 });
3973        assert!(serde_json::from_value::<StreamFrame>(future).is_err());
3974    }
3975
3976    #[test]
3977    fn audit_summary_request_and_result_roundtrip() {
3978        // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
3979        // tolerates omitted/null params; the server dispatches on the method string (method_of).
3980        let r = Request::AuditSummary;
3981        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
3982        assert_eq!(
3983            method_of(&serde_json::json!({"method": "audit_summary"})),
3984            Some("audit_summary")
3985        );
3986
3987        // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
3988        // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
3989        // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
3990        let res = AuditSummaryResult {
3991            per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
3992            per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
3993            total_sessions: 4,
3994        };
3995        let v = serde_json::to_value(&res).unwrap();
3996        assert_eq!(v["per_peer"][1][0], "bob");
3997        assert_eq!(v["per_peer"][1][1], 2u64);
3998        assert_eq!(v["per_service"][1][0], "notes");
3999        assert_eq!(v["total_sessions"], 4u64);
4000        assert_eq!(
4001            serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
4002            res
4003        );
4004
4005        // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
4006        // deserializes — the `#[serde(default)]` fills it with 0.
4007        let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
4008        let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
4009        assert_eq!(back.total_sessions, 0);
4010        assert!(back.per_peer.is_empty());
4011    }
4012}