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