Skip to main content

mcpmesh_local_api/
protocol.rs

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