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