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