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#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum BackendKind {
37    Run,
38    Socket,
39}
40
41/// A registered service as reported by `status` (no transport vocabulary).
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct ServiceInfo {
44    pub name: String,
45    pub allow: Vec<String>, // STABLE principals (b64u:/eid:) or roster names (#38) — never nicknames
46    /// The HUMAN rendering of `allow`, index-aligned: each principal resolved to its peer's
47    /// display nickname by the daemon (which owns the store); an unresolvable stable
48    /// principal renders as a neutral placeholder — porcelain must show THESE, never raw
49    /// ids (surface discipline). Additive: default + skip-if-empty.
50    #[serde(default, skip_serializing_if = "Vec::is_empty")]
51    pub allow_display: Vec<String>,
52    pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
53    /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
54    /// control connection's lifetime, absent from config, gone on restart. Additive — an older
55    /// daemon omits it and it reads as `false` (the persistent default).
56    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57    pub ephemeral: bool,
58}
59
60/// A known peer as reported by `status` (nickname only — never the EndpointId).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct PeerInfo {
63    pub name: String,
64    pub services: Vec<String>,
65    /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
66    /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
67    /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
68    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
69    #[serde(default, skip_serializing_if = "Option::is_none")]
70    pub user_id: Option<String>,
71    /// The peer's stable DEVICE principal `eid:<hex>` (#41) — the SAME rendering the socket
72    /// backend injects into `_meta["mcpmesh/peer"]` and that appears in `[services.*].allow`.
73    /// Always present for a real peer (`Option` only for additive round-trip). Distinct from
74    /// `user_id` (the person-level `b64u:`, present only when the peer proved a binding): a
75    /// nickname is not unique, so an embedder keys caller-scoped decisions (dial the caller
76    /// back, "the requester's own data") on THIS, the authenticated endpoint. Machine-surface
77    /// authz vocabulary (like the allow lists) — human porcelain still shows the nickname.
78    /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub principal: Option<String>,
81}
82
83/// HOW a peer is reached (#64): a direct/hole-punched QUIC path, or through a relay.
84///
85/// `rtt_ms` is NOT a proxy for this — a fast relay beats a slow direct path — and iroh's own
86/// distinction was being dropped at the mcpmesh boundary. Three things depend on it: a truthful
87/// locality claim ("this traffic never left the building"), honest disclosure that a relayed path
88/// depends on third-party infrastructure, and diagnostics, since "slow" has a different cause and
89/// fix in each case.
90///
91/// **Only `Direct` supports a locality claim.** `Unknown` means "we do not know", NOT "private" —
92/// rendering it as private is the one misuse that turns this field into a false privacy statement.
93/// The daemon errs the same way: when a relay path is active it reports [`Relay`](Self::Relay) even
94/// if a direct path is live too, because overstating privacy is worse than understating it.
95///
96/// `#[non_exhaustive]`: iroh already has a third address kind (a custom transport) that could
97/// warrant a variant, and adding one to a public enum later breaks every downstream exhaustive
98/// `match` — the lesson #58 paid for.
99#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
100#[serde(tag = "kind", rename_all = "snake_case")]
101#[non_exhaustive]
102pub enum PeerPath {
103    /// A direct or hole-punched QUIC path: the bytes did not transit a relay.
104    Direct,
105    /// Through a relay server. `url` is the relay in use when known.
106    Relay {
107        #[serde(default, skip_serializing_if = "Option::is_none")]
108        url: Option<String>,
109    },
110    /// Not known: never probed, no selected path, or a transport mcpmesh does not model.
111    ///
112    /// `#[serde(other)]` makes this the landing spot for a `kind` a client has never heard of. That
113    /// is what actually buys wire-additivity: `#[non_exhaustive]` only protects the Rust `match`,
114    /// and without this an older client hits `unknown variant` and fails to deserialize the WHOLE
115    /// `PeerReachability` — one new path kind would break every `status` response it reads.
116    #[default]
117    #[serde(other)]
118    Unknown,
119}
120
121/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean: a nickname, a
122/// bool, latency/age NUMBERS, the stable `eid:` principal (#42), and since #64 the PATH KIND —
123/// direct vs relay, plus the relay URL when relayed. Never a socket address, an IP, or a key: the
124/// path field says WHICH KIND of route is in use, never where the peer is.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PeerReachability {
127    pub name: String,    // the peer's nickname
128    pub reachable: bool, // result of the last probe (false if never probed)
129    #[serde(default, skip_serializing_if = "Option::is_none")]
130    /// Last measured round-trip, if reachable: dial + ping/pong, stamped AT THE PONG.
131    ///
132    /// It EXCLUDES the window the daemon spends afterwards determining which path the connection
133    /// settled on. Before 0.20.1 it included that window, so a relayed peer could never report
134    /// under 600ms and most of the figure was a deliberate wait rather than time on the wire —
135    /// an embedder read ~820ms across one LAN hop and reported it as a 66x latency regression
136    /// (#123). It is a wire-latency measurement now, so "relayed AND low rtt_ms" is a reachable
137    /// state and a usable diagnostic.
138    pub rtt_ms: Option<u64>,
139    #[serde(default, skip_serializing_if = "Option::is_none")]
140    pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
141    /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
142    /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
143    /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
144    /// display data; never an authz input. Near-real-time when `status` is read (the probe
145    /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
146    #[serde(default, skip_serializing_if = "String::is_empty")]
147    pub meta: String,
148    /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
149    /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
150    /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
151    /// for a real row (`Option` only for additive round-trip). Machine-surface authz
152    /// vocabulary — the human `status` reachability line is unchanged. Additive:
153    /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub principal: Option<String>,
156    /// HOW this peer is reached (#64) — see [`PeerPath`]. Captured by the same probe that sets
157    /// `reachable`/`rtt_ms`, so it shares their freshness: one TTL, one `age_secs`. `Unknown` for a
158    /// peer never probed. Additive (`#[serde(default)]`), so older rows and clients are unaffected.
159    #[serde(default)]
160    pub path: PeerPath,
161}
162
163/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
164/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
165/// as-transport-vocab. Absent in a pure-pairing daemon.
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct RosterStatus {
168    pub org_id: String,
169    pub serial: u64,
170    pub state: String, // "pending" | "approved" | "degraded" | "stopped"
171    pub org_root_fingerprint: String, // short-word form
172}
173
174/// One reachable roster peer device as reported by `status` (the advisory presence read).
175/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
176/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
177/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179pub struct PresencePeer {
180    pub user_id: String,
181    pub device_label: String,
182    pub role: String, // "primary" | "mirror" (roster vocabulary)
183    /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
184    pub online: bool,
185    /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
186    /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
187    /// data; never an authz input. Additive: default + skip-if-empty.
188    #[serde(default, skip_serializing_if = "String::is_empty")]
189    pub meta: String,
190}
191
192/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
193/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
194/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
195/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
196/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
197/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
198/// an epoch — never an EndpointId.
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200pub struct RecentPairing {
201    /// The peer's nickname as stored by the inviter (its local name for the redeemer).
202    pub peer_nickname: String,
203    /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
204    /// `PairResult.sas_code` carried. Never checked programmatically.
205    pub sas_code: String,
206    /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
207    pub paired_at_epoch: u64,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211pub struct StatusResult {
212    pub stack_version: String,
213    pub services: Vec<ServiceInfo>,
214    pub peers: Vec<PeerInfo>,
215    /// Roster-mode status, absent in a pure-pairing daemon. Additive:
216    /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
217    #[serde(default, skip_serializing_if = "Option::is_none")]
218    pub roster: Option<RosterStatus>,
219    /// The reachable roster peer devices (the advisory presence read), each with an `online`
220    /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
221    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
222    #[serde(default, skip_serializing_if = "Vec::is_empty")]
223    pub presence: Vec<PresencePeer>,
224    /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
225    /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
226    /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
227    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
228    #[serde(default, skip_serializing_if = "Option::is_none")]
229    pub self_user_id: Option<String>,
230    /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
231    /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
232    /// that has accepted no pairing since it started. Additive:
233    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
234    #[serde(default, skip_serializing_if = "Vec::is_empty")]
235    pub recent_pairings: Vec<RecentPairing>,
236    /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
237    /// first probe completes. Additive: default + skip-if-empty.
238    #[serde(default, skip_serializing_if = "Vec::is_empty")]
239    pub reachability: Vec<PeerReachability>,
240    /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
241    /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
242    /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
243    /// skip-if-empty so an older payload round-trips.
244    #[serde(default, skip_serializing_if = "String::is_empty")]
245    pub self_nickname: String,
246    /// On-disk footprint of this node's own state (#88), so an embedder can warn a user before
247    /// ENOSPC rather than after — the audit log's write rate is driven by inbound peer traffic,
248    /// and it shares a filesystem with `state.redb` and the device key. A LIVE read (computed
249    /// per `status` call), not a boot-time snapshot. `None` only in mesh-less control-only mode.
250    /// Additive: default + skip-if-none so an older payload round-trips.
251    #[serde(default, skip_serializing_if = "Option::is_none")]
252    pub storage: Option<StorageInfo>,
253}
254
255/// The `status.storage` block (#88): bytes actually on disk, by subsystem. Counts, never
256/// content. Additive-only.
257#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
258pub struct StorageInfo {
259    /// Summed sizes of the monthly audit files (`<state>/audit/*.jsonl`).
260    pub audit_bytes: u64,
261    /// Size of the peer/trust state store (`state.redb`).
262    pub redb_bytes: u64,
263    /// Total size under the app-blob store directory; 0 when no blob store exists.
264    pub blobs_bytes: u64,
265}
266
267/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
268#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
269#[serde(deny_unknown_fields)]
270pub struct RegisterServiceParams {
271    pub name: String,
272    pub backend: BackendSpec,
273    pub allow: Vec<String>,
274    /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
275    /// to the on-disk config, and automatically unregistered when the control connection that
276    /// registered it closes (and gone on daemon restart). For an embedder that serves a
277    /// `socket` backend from a fresh path each run, this removes the need to derive a stable
278    /// socket path solely to keep a persisted registration valid, and the stale-registration
279    /// accumulation that comes with no unregister. Default false = the persistent behavior.
280    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
281    pub ephemeral: bool,
282}
283
284/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
285/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
286/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
287/// list (an invite that grants nothing is useless — #34).
288#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
289#[serde(deny_unknown_fields)]
290pub struct InviteParams {
291    #[serde(default)]
292    pub services: Vec<String>,
293    /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
294    /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
295    /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
296    #[serde(default, skip_serializing_if = "Option::is_none")]
297    pub app_label: Option<String>,
298}
299
300/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
301/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
302#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
303#[serde(deny_unknown_fields)]
304pub struct PairParams {
305    #[serde(default)]
306    pub invite_line: String,
307}
308
309/// Params of [`Request::PeerRemove`]: the nickname to unpair.
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(deny_unknown_fields)]
312pub struct PeerRemoveParams {
313    pub nickname: String,
314}
315
316/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
317/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319#[serde(deny_unknown_fields)]
320pub struct PeerRenameParams {
321    #[serde(default)]
322    pub user_id: Option<String>,
323    #[serde(default)]
324    pub nickname: Option<String>,
325    pub to: String,
326}
327
328/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
329/// (iroh base32) plus the nickname and service allow list to install it under.
330#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
331#[serde(deny_unknown_fields)]
332pub struct PeerAddParams {
333    pub nickname: String,
334    pub endpoint_id: String,
335    #[serde(default)]
336    pub allow: Vec<String>,
337}
338
339/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
340/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
341#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
342#[serde(deny_unknown_fields)]
343pub struct OpenSessionParams {
344    #[serde(default)]
345    pub peer: String,
346    #[serde(default)]
347    pub service: String,
348}
349
350/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
351/// on FIRST install (`b64u:`; omit once pinned — config carries it).
352#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(deny_unknown_fields)]
354pub struct RosterInstallParams {
355    pub path: String,
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub org_root_pk: Option<String>,
358}
359
360/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
361/// never crosses the API.
362#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
363#[serde(deny_unknown_fields)]
364pub struct OrgJoinParams {
365    pub org_id: String,
366    pub org_root_pk: String,
367    pub user_id: String,
368    pub user_key: String,
369}
370
371/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
372/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
373/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
374/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
375#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(deny_unknown_fields)]
377pub struct SetAppMetadataParams {
378    pub metadata: String,
379}
380
381/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
382/// principal, or a `b64u:` user_id.
383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
384#[serde(deny_unknown_fields)]
385pub struct PeerServicesParams {
386    pub peer: String,
387}
388
389/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
390/// caller — computed authoritatively on the peer (which owns the truth), always current, only
391/// the caller's own admitted services (never the peer's full registry).
392#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
393pub struct PeerServicesResult {
394    pub services: Vec<String>,
395}
396
397/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
398/// to remove — the deregistration mirror of `register_service`.
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(deny_unknown_fields)]
401pub struct UnregisterServiceParams {
402    pub name: String,
403}
404
405/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
406/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
407/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
408#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
409#[serde(deny_unknown_fields)]
410pub struct ServiceAllowParams {
411    pub service: String,
412    pub principal: String,
413}
414
415/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
416/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
417/// they stored at pairing time until a re-invite.
418#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
419#[serde(deny_unknown_fields)]
420pub struct SetNicknameParams {
421    pub nickname: String,
422}
423
424/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
426#[serde(deny_unknown_fields)]
427pub struct SetRosterUrlParams {
428    pub url: String,
429}
430
431/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
432/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
433/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
434/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
435/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
436/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
437/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
438/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
439#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
440#[serde(deny_unknown_fields)]
441pub struct SetRelaysParams {
442    pub relay_urls: Vec<String>,
443}
444
445/// Result of [`Request::SetRelays`] (#53).
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
447pub struct SetRelaysResult {
448    /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
449    pub changed: bool,
450    /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
451    /// but NOT applied live — a node restart is required for it to take effect. `false` on the
452    /// live custom→custom path (already applied to the running endpoint).
453    pub restart_required: bool,
454}
455
456/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
457#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
458#[serde(deny_unknown_fields)]
459pub struct BlobPublishParams {
460    pub scope: String,
461    pub path: String,
462}
463
464/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
466#[serde(deny_unknown_fields)]
467pub struct BlobGrantParams {
468    pub scope: String,
469    pub principal: String,
470}
471
472/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
473///
474/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
475/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
476/// access to everything else.
477#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
478#[serde(deny_unknown_fields)]
479pub struct BlobRevokeParams {
480    pub scope: String,
481    pub principals: Vec<String>,
482}
483
484/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
485///
486/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
487/// this takes effect immediately for authorization — but the bytes stay in the local store, and
488/// there is no reclaim verb yet. Do not surface this to a user as deletion.
489#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
490#[serde(deny_unknown_fields)]
491pub struct BlobUnpublishParams {
492    pub scope: String,
493    pub hash: String,
494}
495
496/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
497///
498/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
499/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
500/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
501/// turn the original publisher going offline into a hang at every fetcher.
502///
503/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
504/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
505#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
506#[serde(deny_unknown_fields)]
507pub struct BlobRepublishParams {
508    pub scope: String,
509    pub hash: String,
510}
511
512/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
513#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
514#[serde(deny_unknown_fields)]
515pub struct BlobFetchParams {
516    pub ticket: String,
517    pub dest_path: String,
518}
519
520/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
521/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
522///
523/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
524/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
525/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
526/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
527/// identical to inline variant bodies.
528///
529/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
530/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
531/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
532/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
533/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
534#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
535#[serde(tag = "method", content = "params", rename_all = "snake_case")]
536pub enum Request {
537    /// Register/update a `[services.*]` entry idempotently.
538    RegisterService(RegisterServiceParams),
539    Status,
540    /// Mint a one-time pairing invite granting `services`. The daemon
541    /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
542    /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
543    /// `method` string generically; the tag comes from `rename_all`.
544    Invite(InviteParams),
545    /// Redeem a pairing invite. The daemon dials the inviter named by
546    /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
547    /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
548    /// (snake_case); `method_of` reads the `method` string generically.
549    ///
550    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
551    Pair(PairParams),
552    /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
553    /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
554    /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
555    /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
556    /// NOT severed here: existing sessions run to completion; the peer only loses the
557    /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
558    /// `method_of` reads the `method` string generically (no per-variant arm).
559    ///
560    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
561    PeerRemove(PeerRemoveParams),
562    /// Rename a contact's nickname (nickname) authoritatively. Renames the
563    /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
564    /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
565    /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
566    /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
567    /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
568    /// host-privileged like the other pair ops.
569    PeerRename(PeerRenameParams),
570    /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
571    /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
572    /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
573    /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
574    /// vocabulary — do not build on it. Tag `"peer_add"`.
575    PeerAdd(PeerAddParams),
576    /// Open a mesh session to `peer/service`; the daemon dials and pipes.
577    /// Distinct from the proxy's job: this returns a session the client streams.
578    /// Named `open_session` rather than `connect` to avoid colliding
579    /// with the `connect` porcelain.
580    OpenSession(OpenSessionParams),
581    /// Install a signed roster from a local file (the manual `internal roster install` path).
582    /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
583    /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
584    /// pins the org root on FIRST install (`b64u:`); omit it
585    /// once pinned (config carries it). Tag `"roster_install"`.
586    RosterInstall(RosterInstallParams),
587    /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
588    /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
589    /// `user_key` is a LOCAL path
590    /// (the key never crosses the API). Tag `"org_join"`.
591    OrgJoin(OrgJoinParams),
592    /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
593    /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
594    /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
595    /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
596    /// `"set_roster_url"`.
597    SetRosterUrl(SetRosterUrlParams),
598    /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
599    /// daemon's own serialized config-write path (no lost-update window against a
600    /// concurrent grant/registration) and update the in-memory name future invites
601    /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
602    SetNickname(SetNicknameParams),
603    /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
604    /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
605    /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
606    /// on restart; the embedder re-sets on startup).
607    SetAppMetadata(SetAppMetadataParams),
608    /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
609    /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
610    /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
611    /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
612    /// is currently `default`/`disabled`, the config is persisted but the live mode transition
613    /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
614    /// [`SetRelaysResult`]. Tag `"set_relays"`.
615    SetRelays(SetRelaysParams),
616    /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
617    /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
618    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
619    /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
620    /// hot-reloads. Idempotent. Ack result.
621    UnregisterService(UnregisterServiceParams),
622    /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
623    /// and returns the service names whose allow admits the caller's principal. Answers
624    /// [`PeerServicesResult`].
625    PeerServices(PeerServicesParams),
626    ServiceAllowGrant(ServiceAllowParams),
627    /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
628    /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
629    /// Idempotent. Ack result.
630    ServiceAllowRevoke(ServiceAllowParams),
631    /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
632    /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
633    /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
634    /// Tag `"blob_publish"`.
635    BlobPublish(BlobPublishParams),
636    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
637    /// nickname (the shared `principal_set` expansion). Tag
638    /// `"blob_grant"`.
639    BlobGrant(BlobGrantParams),
640    /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
641    BlobRevoke(BlobRevokeParams),
642    /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
643    /// bytes.
644    BlobUnpublish(BlobUnpublishParams),
645    /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
646    /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
647    /// two interchangeably after a fetch.
648    BlobRepublish(BlobRepublishParams),
649    /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
650    BlobList(BlobListParams),
651    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
652    /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
653    /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
654    BlobFetch(BlobFetchParams),
655    /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
656    /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
657    /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
658    /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
659    /// `method_of` reads the `method` string generically (no per-variant arm).
660    AuditSummary,
661    /// Delete audit months strictly older than `before` (#88) — the retention lever the log
662    /// never had. Local-only and owner-only (the control socket is the daemon owner's). Answers
663    /// [`AuditPruneResult`]. Tag `"audit_prune"`.
664    AuditPrune(AuditPruneParams),
665    /// Read this node's LOCAL audit records, filtered and paged (#88) — the "show me everything
666    /// you hold about me" verb. Local-only; nothing is transmitted. Answers
667    /// [`AuditListResult`]. Tag `"audit_list"`.
668    AuditList(AuditListParams),
669    /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
670    /// connection STOPS being request/response after this call and becomes a one-way push stream
671    /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
672    Subscribe,
673}
674
675/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
676/// computed porcelain-side from the invite's org_root_pk). Additive-only.
677#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
678pub struct OrgJoinResult {
679    pub org_id: String,
680}
681
682/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
683/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
684/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
685///
686/// Additive-only: any future field MUST land as
687/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
688#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
689pub struct RosterInstallResult {
690    pub org_id: String,
691    pub serial: u64,
692    /// How many live sessions were severed, for the porcelain's confirmation line.
693    #[serde(default)]
694    pub severed: u32,
695}
696
697/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
698/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
699/// carve-out as the pairing invite line). Additive-only.
700#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
701pub struct BlobPublishResult {
702    pub ticket: String,
703    pub hash: String, // bare blake3 hex
704}
705
706/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
707/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
708#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
709pub struct ScopeInfo {
710    pub name: String,
711    pub hashes: Vec<String>,
712    pub grants: Vec<String>,
713    /// Hashes deliberately WITHDRAWN from this scope (#107): `blob_unpublish` was called, and
714    /// `blob_republish` of these into THIS scope is refused with [`ERR_BLOB_WITHDRAWN`]. Cleared
715    /// only by a deliberate `blob_publish {scope, path}`. Additive — omitted when empty, so a
716    /// pre-`api_minor` 19 client sees exactly what it saw before.
717    #[serde(default, skip_serializing_if = "Vec::is_empty")]
718    pub withdrawn: Vec<String>,
719    /// Size of `hashes` — always present, even when `counts_only` empties the vector (#84b).
720    #[serde(default)]
721    pub hash_count: usize,
722    /// Size of `grants`.
723    #[serde(default)]
724    pub grant_count: usize,
725    /// Size of `withdrawn`.
726    #[serde(default)]
727    pub withdrawn_count: usize,
728}
729
730/// Params of [`Request::BlobList`] (#84b). ALL optional — `blob_list {}` still works, which
731/// matters because the verb took no params before `api_minor` 20.
732///
733/// A DEFAULT LIMIT applies when `limit` is absent. Deliberate: unpaged, `blob_list` renders every
734/// scope into one frame against the 16 MiB cap; past it the CLIENT rejects the frame as malformed.
735/// The control surface carries no strike bound, so the connection survives — but the caller gets an
736/// opaque failure with no way to page, which is unusable rather than merely large.
737#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
738#[serde(default, deny_unknown_fields)]
739pub struct BlobListParams {
740    /// EXACT scope name, never a prefix.
741    pub scope: Option<String>,
742    /// Only scopes containing this hash; the rendering you send is normalized first.
743    pub hash: Option<String>,
744    pub limit: Option<usize>,
745    pub offset: Option<usize>,
746    /// Omit `hashes`/`grants`/`withdrawn`, keep the counts.
747    pub counts_only: bool,
748}
749
750/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
751#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
752pub struct BlobScopeList {
753    pub scopes: Vec<ScopeInfo>,
754    /// Scopes matching the filter BEFORE `limit`/`offset` (#84b). Without this you cannot tell a
755    /// complete answer from a clipped one.
756    #[serde(default)]
757    pub total: usize,
758    /// True when more scopes matched than were returned. Page with `offset` to see the rest.
759    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
760    pub truncated: bool,
761}
762
763/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
764/// Additive-only.
765#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
766pub struct BlobFetchResult {
767    pub hash: String,
768    pub bytes_len: u64,
769}
770
771/// Params of [`Request::AuditPrune`] (#88): delete monthly audit files STRICTLY older than
772/// `before` (that month itself is kept — delete-before, not delete-including). Rejects unknown
773/// fields, and the daemon validates the `YYYY-MM` shape up front: a malformed month errors
774/// loudly instead of string-comparing to nothing and reporting a clean no-op.
775#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
776#[serde(deny_unknown_fields)]
777pub struct AuditPruneParams {
778    /// A zero-padded `YYYY-MM` month key.
779    pub before: String,
780}
781
782/// Result of [`Request::AuditPrune`]: the month keys actually deleted, ascending. Empty when
783/// nothing was older than `before` (idempotent).
784#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
785pub struct AuditPruneResult {
786    pub deleted_months: Vec<String>,
787}
788
789/// Params of [`Request::AuditList`] (#88). All filters optional and AND-combined; every field
790/// absent lists everything (paged). Rejects unknown fields — a typo'd filter that silently
791/// matched everything would let a "what do you hold about X" answer overclaim.
792#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
793#[serde(deny_unknown_fields)]
794pub struct AuditListParams {
795    /// Inclusive `YYYY-MM` lower bound — month-file granularity (the rotation unit), so an
796    /// out-of-range month is skipped without parsing it.
797    #[serde(default, skip_serializing_if = "Option::is_none")]
798    pub since: Option<String>,
799    /// Inclusive `YYYY-MM` upper bound.
800    #[serde(default, skip_serializing_if = "Option::is_none")]
801    pub until: Option<String>,
802    /// One of the wire kind strings (`session_open` / `session_close` / `request` /
803    /// `blob_fetch` / `trust`). An UNKNOWN string is an error, never silently-all.
804    #[serde(default, skip_serializing_if = "Option::is_none")]
805    pub kind: Option<String>,
806    /// The record's attributed peer nickname.
807    #[serde(default, skip_serializing_if = "Option::is_none")]
808    pub peer: Option<String>,
809    /// Page size, default 500, clamped to 1000 — a month file can be arbitrarily large and the
810    /// response is ONE JSON frame under the transport's frame cap, so the clamp is load-bearing
811    /// (the same lesson as `blob_list`'s, minor 20).
812    #[serde(default, skip_serializing_if = "Option::is_none")]
813    pub limit: Option<u32>,
814    /// Records to skip (after filtering), for paging.
815    #[serde(default, skip_serializing_if = "Option::is_none")]
816    pub offset: Option<u32>,
817}
818
819/// Result of [`Request::AuditList`]: one page of matching records in chronological order
820/// (oldest month first, in-file order within a month), plus the TOTAL match count so a caller
821/// can page without a second counting call. `total` counts ALL matches, not the page.
822#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
823pub struct AuditListResult {
824    pub records: Vec<AuditRecord>,
825    pub total: u64,
826}
827
828/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
829/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
830/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
831/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
832/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
833/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
834///
835/// Additive-only: any future field MUST land as
836/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
837#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
838pub struct AuditSummaryResult {
839    /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
840    /// peer to attribute) but IS in `total_sessions`.
841    pub per_peer: Vec<(String, u64)>,
842    /// Sessions opened per registered service name.
843    pub per_service: Vec<(String, u64)>,
844    /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
845    #[serde(default)]
846    pub total_sessions: u64,
847}
848
849/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
850/// (the ONE pairing artifact deliberately carved out of the
851/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
852/// absolute expiry in epoch seconds (≤ now + 24h).
853///
854/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
855/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
856/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
857/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
858/// ceremony" note in `docs/local-protocol.md` (#35).
859///
860/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
861/// so older payloads still deserialize.
862#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
863pub struct InviteResult {
864    /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
865    pub invite_line: String,
866    /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
867    pub expires_at_epoch: u64,
868}
869
870/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
871/// redeemer's local name for the new peer) plus the display-only short authentication
872/// code (SAS) — a few words the human reads aloud to a second channel to
873/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
874/// artifact (like the invite line), NOT a transport-vocabulary leak.
875///
876/// Additive-only: any future field MUST land as
877/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
878#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
879pub struct PairResult {
880    /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
881    pub peer_nickname: String,
882    /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
883    /// sides for the out-of-band human check. Never sent on the wire, never checked
884    /// programmatically.
885    pub sas_code: String,
886    /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
887    /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
888    /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
889    /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
890    /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
891    #[serde(default, skip_serializing_if = "Vec::is_empty")]
892    pub services: Vec<String>,
893    /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
894    /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
895    #[serde(default, skip_serializing_if = "Option::is_none")]
896    pub app_label: Option<String>,
897    /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
898    /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
899    /// can align with its own — and the same value it may later pass to `open_session` to dial
900    /// this peer by identity rather than by local nickname. `None` if the inviter presented no
901    /// binding (a legacy/keyless peer). Additive.
902    #[serde(default, skip_serializing_if = "Option::is_none")]
903    pub peer_user_id: Option<String>,
904}
905
906/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
907/// top of the base record schema: it removes no field and makes the JSONL self-describing so
908/// a consumer can filter by class without guessing from which optional fields are present.
909#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
910#[serde(rename_all = "snake_case")]
911pub enum AuditKind {
912    /// A mesh session opened (a backend was selected for an authenticated peer).
913    /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
914    /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
915    SessionOpen,
916    /// A mesh session closed (the backend returned / the session tore down).
917    SessionClose,
918    /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
919    Request,
920    /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
921    BlobFetch,
922    /// A trust mutation (pair, unpair, roster install/swap, revoke).
923    Trust,
924}
925
926/// One audit record — the union of the event classes, and the `record` payload of a
927/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
928/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
929/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
930/// `bytes_out`).
931///
932/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
933/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
934/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
935#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
936pub struct AuditRecord {
937    /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
938    /// prefix also selects the monthly file (the rotation boundary), so it is always present.
939    pub ts: String,
940    pub kind: AuditKind,
941    /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
942    /// local-only events with no remote peer (a manual roster install).
943    #[serde(skip_serializing_if = "Option::is_none")]
944    pub peer: Option<String>,
945    #[serde(skip_serializing_if = "Option::is_none")]
946    pub service: Option<String>,
947    #[serde(skip_serializing_if = "Option::is_none")]
948    pub method: Option<String>,
949    /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
950    #[serde(skip_serializing_if = "Option::is_none")]
951    pub tool: Option<String>,
952    /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
953    #[serde(skip_serializing_if = "Option::is_none")]
954    pub args_hash: Option<String>,
955    /// Byte COUNT of the response sent back to the peer — a count, never the content.
956    #[serde(skip_serializing_if = "Option::is_none")]
957    pub bytes_out: Option<u64>,
958    /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
959    #[serde(skip_serializing_if = "Option::is_none")]
960    pub status: Option<String>,
961    #[serde(skip_serializing_if = "Option::is_none")]
962    pub latency_ms: Option<u64>,
963    /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
964    #[serde(skip_serializing_if = "Option::is_none")]
965    pub event: Option<String>,
966    /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
967    /// nickname or `org/serial` (`Trust`).
968    #[serde(skip_serializing_if = "Option::is_none")]
969    pub target: Option<String>,
970}
971
972impl AuditRecord {
973    fn base(ts: String, kind: AuditKind) -> Self {
974        Self {
975            ts,
976            kind,
977            peer: None,
978            service: None,
979            method: None,
980            tool: None,
981            args_hash: None,
982            bytes_out: None,
983            status: None,
984            latency_ms: None,
985            event: None,
986            target: None,
987        }
988    }
989
990    pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
991        let mut r = Self::base(ts, AuditKind::SessionOpen);
992        r.peer = peer;
993        r.service = Some(service);
994        r
995    }
996
997    /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
998    /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
999    /// reaches no backend and so is never audited by the far side's session guard — without a
1000    /// dedicated constructor. DRY: reuses the existing optional `status` field.
1001    pub fn with_status(mut self, status: &str) -> Self {
1002        self.status = Some(status.into());
1003        self
1004    }
1005
1006    pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
1007        let mut r = Self::base(ts, AuditKind::SessionClose);
1008        r.peer = peer;
1009        r.service = Some(service);
1010        r
1011    }
1012
1013    /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
1014    /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
1015    /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
1016    #[allow(clippy::too_many_arguments)]
1017    pub fn proxied_request(
1018        ts: String,
1019        peer: Option<String>,
1020        service: String,
1021        method: String,
1022        tool: Option<String>,
1023        args_hash: String,
1024        bytes_out: u64,
1025        status: String,
1026        latency_ms: u64,
1027    ) -> Self {
1028        let mut r = Self::base(ts, AuditKind::Request);
1029        r.peer = peer;
1030        r.service = Some(service);
1031        r.method = Some(method);
1032        r.tool = tool;
1033        r.args_hash = Some(args_hash);
1034        r.bytes_out = Some(bytes_out);
1035        r.status = Some(status);
1036        r.latency_ms = Some(latency_ms);
1037        r
1038    }
1039
1040    /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
1041    /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
1042    pub fn proxied_notification(
1043        ts: String,
1044        peer: Option<String>,
1045        service: String,
1046        method: String,
1047        tool: Option<String>,
1048        args_hash: String,
1049    ) -> Self {
1050        let mut r = Self::base(ts, AuditKind::Request);
1051        r.peer = peer;
1052        r.service = Some(service);
1053        r.method = Some(method);
1054        r.tool = tool;
1055        r.args_hash = Some(args_hash);
1056        r
1057    }
1058
1059    pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
1060        let mut r = Self::base(ts, AuditKind::BlobFetch);
1061        r.peer = peer;
1062        r.target = Some(hash);
1063        r.status = Some(status);
1064        r
1065    }
1066
1067    pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
1068        let mut r = Self::base(ts, AuditKind::Trust);
1069        r.event = Some(event);
1070        r.target = target;
1071        r
1072    }
1073}
1074
1075/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
1076/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
1077#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1078pub struct ActiveSession {
1079    pub peer: String,
1080    pub service: String,
1081    pub opened_at: i64,
1082    /// The caller's STABLE device principal, `eid:<hex>` (#73).
1083    ///
1084    /// `peer` is a display nickname and collides: two devices under one nickname, or two contacts
1085    /// sharing a display name, are indistinguishable in the live-session view. So "who is using my
1086    /// service right now", per-peer session counts, and any UI that lets a user act on a live
1087    /// session (revoke, disconnect, inspect) were all keyed on a collidable string.
1088    ///
1089    /// Same argument and same shape as [`PeerInfo`] (#41) and [`PeerReachability`] (#42).
1090    /// Nicknames NEVER authorize; this is the value to key on.
1091    ///
1092    /// **Snapshot only, for now.** `ActiveSession` appears in [`StreamFrame::Snapshot`] — there is
1093    /// no `active_sessions` on `StatusResult`. A client that keeps its view current by applying
1094    /// subsequent `session_open`/`session_close` events still has a collision problem: those are
1095    /// [`AuditRecord`]s and carry no principal (#57, unmerged). So the snapshot distinguishes two
1096    /// same-nickname devices and the next `session_close` for that nickname does not say which row
1097    /// to drop. Re-subscribe for an authoritative view until #57 lands.
1098    ///
1099    /// Always present for a real row — `Option` only so an older client round-trips. Additive.
1100    #[serde(default, skip_serializing_if = "Option::is_none")]
1101    pub principal: Option<String>,
1102}
1103
1104/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
1105/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
1106/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
1107/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
1108/// them (see `docs/local-protocol.md` "Live event stream").
1109/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
1110/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
1111/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
1112/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
1113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1114#[serde(tag = "type", rename_all = "snake_case")]
1115#[non_exhaustive]
1116pub enum StreamFrame {
1117    /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
1118    /// reachability) so a fresh subscriber renders immediately without replaying history.
1119    Snapshot {
1120        active_sessions: Vec<ActiveSession>,
1121        reachability: Vec<PeerReachability>,
1122    },
1123    /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
1124    /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
1125    /// `Box`, so the wire shape is the record's fields verbatim.
1126    Event { record: Box<AuditRecord> },
1127    /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
1128    /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
1129    /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
1130    /// it returns, rather than on the next poll tick.
1131    ///
1132    /// Emitted on a change of `reachable` **or of `path`**. A refresh with the same verdict AND the
1133    /// same path emits nothing, so a peer that stays up does not produce a frame per TTL refresh;
1134    /// `rtt_ms`/`meta`/`services` drift is advisory detail and is not a transition. `age_secs` is
1135    /// `0` — the observation just completed.
1136    ///
1137    /// **Do not treat this as an up/down toggle.** It carried that meaning through 0.18, and this
1138    /// doc said "on a CHANGE of `reachable` only" until 1.22 — which stopped being true in 0.19.0
1139    /// (#92 item 1), when `path` joined the transition rule. A consumer that assumed same-verdict
1140    /// frames were impossible was reading a stale guarantee.
1141    ///
1142    /// Two producers, as of API 1.22:
1143    ///
1144    /// - a **probe** completing (`status`/`subscribe` refreshing a stale entry), which carries a
1145    ///   measured `rtt_ms`; and
1146    /// - a **live session** whose selected path changed under it (#92 item 2), which carries
1147    ///   `rtt_ms: None` on a first observation — no round trip was measured and none is invented.
1148    ///
1149    /// The second producer is why `path` is trustworthy for a long-lived session: a session that
1150    /// degrades Direct→Relay mid-call now says so when it happens, rather than staying silently
1151    /// mislabelled until something probes. `path` is a truth claim about where user data went, so
1152    /// `Unknown` means "we do not know" and must never be rendered as private.
1153    Reachability { peer: PeerReachability },
1154    /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
1155    /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
1156    Lagged { dropped: u64 },
1157}
1158
1159/// Extract the `method` tag from a raw request value without deserializing the whole
1160/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
1161/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
1162/// methods (adjacent tagging rejects `params:{}` on unit variants).
1163pub fn method_of(v: &serde_json::Value) -> Option<&str> {
1164    v.get("method").and_then(serde_json::Value::as_str)
1165}
1166
1167/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
1168/// Config→BackendSpec is a hand-written match, not a serde passthrough.
1169#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1170#[serde(rename_all = "snake_case")]
1171pub enum BackendSpec {
1172    Run {
1173        cmd: Vec<String>,
1174        /// Per-service environment variables (#51) for the spawned child. Overlaid on the
1175        /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
1176        /// these (identity is not spoofable by a service definition). Default empty.
1177        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1178        env: BTreeMap<String, String>,
1179        /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
1180        #[serde(default, skip_serializing_if = "Option::is_none")]
1181        cwd: Option<String>,
1182    },
1183    Socket {
1184        path: String,
1185    },
1186}
1187
1188/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
1189/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
1190/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
1191/// `{}` (success) for an unknown name, which silently included every ephemeral service.
1192pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
1193/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
1194/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
1195pub const ERR_NO_SUCH_BLOB: i64 = -32041;
1196/// The blob was deliberately withdrawn from this scope (#107). Distinct from
1197/// [`ERR_NO_SUCH_BLOB`]: that means "fetch it first", this means "someone un-shared this on
1198/// purpose — `blob_publish` from the file if the re-share is intended".
1199pub const ERR_BLOB_WITHDRAWN: i64 = -32042;
1200
1201pub const API_NAME: &str = "mcpmesh-local/1";
1202/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
1203///
1204/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
1205///   transport already rejects a mismatched `api`, so an equality check on that is redundant).
1206/// - **MINOR** ([`API_MINOR`]) increments on a surface change within a major — additive fields, new
1207///   methods, or a strictness change like params validation — bumped in the same change that makes
1208///   it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon older
1209///   than a minor it requires. It never resets except on a MAJOR bump.
1210///
1211///   It also bumps for a change to what a field MEANS with no change to its shape — six of the
1212///   twenty-four have, see [`API_MINOR`]'s history. "Every surface change" is what this line used
1213///   to claim, and it was wrong in both directions: minor 9's entry records surface changes that
1214///   shipped WITHOUT a bump, and six bumps changed no type at all. Read the history, not the rule.
1215pub const API_VERSION: &str = "1.27";
1216/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
1217/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
1218/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
1219/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
1220/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
1221/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
1222/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
1223/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
1224/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
1225/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
1226/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
1227/// observable contract did: a revoked principal's next session is refused even on a connection it
1228/// already holds, and its live connections are severed. Previously both waited for the peer to
1229/// disconnect on its own, which is unbounded (#54). A consumer can guard on
1230/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
1231/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
1232/// about an unknown service name — a name in neither the config nor the ephemeral registry now
1233/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
1234/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
1235/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
1236/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
1237/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
1238/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
1239/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
1240/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
1241/// errored on any daemon without an org root key, though their scope gate never needed one (#61);
1242/// to 17 when the service answer began coming from the LIVE registry rather than config + overlay,
1243/// so a grant the accept path would refuse is no longer advertised. Three surfaces share that
1244/// resolver and all changed together: `status`'s `services[].allow`, `peer_services`' name list,
1245/// and the `mcpmesh/ping/1` probe's `services`. No wire shape changed, only the source of truth —
1246/// exactly the class of change a downstream cannot see in a type diff (#100); to 18 with `blob_republish`, so a fetched blob can
1247/// be re-served and every recipient becomes a source (#83); to 19 with durable blob revocation — an
1248/// unpublish now survives a later republish via a per-scope withdrawal set, and
1249/// [`ERR_BLOB_WITHDRAWN`] distinguishes "deliberately withdrawn" from "never had it" (#107); to 20
1250/// with `blob_list` filters + paging AND a DEFAULT limit of 256 scopes (the clamp is 4096) — a
1251/// daemon with more scopes than that previously answered with
1252/// everything, and past the 16 MiB frame cap the CLIENT rejected the response as malformed, leaving
1253/// the caller an opaque failure with no way to page. The connection survived: the control surface
1254/// carries no strike bound. This is a behaviour change for existing callers, detectable via the new
1255/// `total`/`truncated` (#84b); to 21 when a
1256/// PATH change became a reachability transition — [`StreamFrame::Reachability`] stopped being an
1257/// up/down toggle and same-verdict frames became possible (#92); to 22 with a SECOND producer for
1258/// that frame: a live per-session watcher that pushes when a session's selected path changes,
1259/// rather than waiting for a probe, at a cadence probes never had (#92); to 23 when
1260/// [`PeerReachability::rtt_ms`] stopped including the path-settle window — a relayed peer could
1261/// previously never report under 600ms, so "relayed AND fast" was unreachable by construction
1262/// (#123); to 24 when `reachable` stopped sharing a deadline with path classification — a relayed
1263/// peer whose pong arrived after ~2.4s was reported OFFLINE while it was answering (#128); to 25
1264/// with [`ActiveSession::principal`] — the live-session view was keyed on a display nickname, so
1265/// two devices under one nickname were indistinguishable and any UI acting on a session (revoke,
1266/// disconnect, inspect) keyed on a collidable string (#73); to 26 when a
1267/// rate-limited inbound NOTIFICATION stopped being silently dropped and became a recorded audit
1268/// event — no type changed; the observable audit stream did (#76, #139); to 27 with the `audit_prune` /
1269/// `audit_list` verbs, `StatusResult::storage`, and the opt-in `[limits].audit_retain_months`
1270/// boot retention — the audit log stopped being a permanent, unbounded, unreadable record (#88).
1271///
1272/// **Not every semantic change gets a minor, and that is the gap to watch (#122).** A minor marks a
1273/// change to this *surface*. A change to behaviour BEHIND the surface — same fields, same shapes,
1274/// different meaning — may not bump it, and is invisible to a type diff. 17 and 24 above happen to
1275/// be that class and did bump; do not infer from them that every such change will. When bumping
1276/// several minors at once, read this block end to end AND the release notes, not the diff.
1277///
1278/// That class is bigger than it looks: **10, 17, 21, 22, 23 and 24 all shipped with no change to
1279/// any type in this file** — they moved meaning, not shape. Six of the twenty-four. A downstream
1280/// that diffs types across a multi-minor bump sees nothing for any of them.
1281pub const API_MINOR: u32 = 27;
1282
1283#[cfg(test)]
1284mod tests {
1285    use super::*;
1286
1287    /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
1288    /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
1289    /// privacy guarantee that daemon never made.
1290    #[test]
1291    fn peer_path_tags_and_defaults_to_unknown() {
1292        let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
1293        assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
1294        assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
1295        let relay = tagged(PeerPath::Relay {
1296            url: Some("https://relay.example/".into()),
1297        });
1298        assert_eq!(relay["kind"], "relay");
1299        assert_eq!(relay["url"], "https://relay.example/");
1300        // A relay whose URL we do not know still tags as relay, with the key elided.
1301        let bare = tagged(PeerPath::Relay { url: None });
1302        assert_eq!(bare["kind"], "relay");
1303        assert!(bare.get("url").is_none(), "elided, not null: {bare}");
1304
1305        // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
1306        // row. Without `#[serde(other)]` an unknown `kind` errors out of
1307        // `PeerReachability` entirely, so one new variant would break every `status` read an
1308        // older pinned client does.
1309        let future: PeerPath =
1310            serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
1311        assert_eq!(future, PeerPath::Unknown);
1312        let row: PeerReachability = serde_json::from_value(serde_json::json!({
1313            "name": "bob", "reachable": true, "path": {"kind": "quantum"}
1314        }))
1315        .expect("an unknown path kind must not fail the whole row");
1316        assert_eq!(row.path, PeerPath::Unknown);
1317        assert!(row.reachable, "the rest of the row survives");
1318
1319        // A pre-#64 row: no `path` key.
1320        let old = serde_json::json!({"name": "bob", "reachable": true});
1321        let parsed: PeerReachability = serde_json::from_value(old).unwrap();
1322        assert_eq!(
1323            parsed.path,
1324            PeerPath::Unknown,
1325            "an older daemon's row must never imply a direct path"
1326        );
1327    }
1328
1329    /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
1330    /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
1331    /// consumer projects both through one code path.
1332    #[test]
1333    fn reachability_frame_tags_and_round_trips() {
1334        let frame = StreamFrame::Reachability {
1335            peer: PeerReachability {
1336                name: "bob".into(),
1337                reachable: true,
1338                rtt_ms: Some(12),
1339                age_secs: Some(0),
1340                meta: String::new(),
1341                principal: Some("eid:beef".into()),
1342                path: Default::default(),
1343            },
1344        };
1345        let v = serde_json::to_value(&frame).unwrap();
1346        assert_eq!(v["type"], "reachability");
1347        assert_eq!(v["peer"]["name"], "bob");
1348        assert_eq!(v["peer"]["reachable"], true);
1349        assert_eq!(
1350            v["peer"]["age_secs"], 0,
1351            "a transition frame is fresh by construction: {v}"
1352        );
1353        let back: StreamFrame = serde_json::from_value(v).unwrap();
1354        assert_eq!(back, frame);
1355    }
1356
1357    #[test]
1358    fn peer_reachability_serde_is_additive() {
1359        let r = PeerReachability {
1360            name: "bob".into(),
1361            reachable: true,
1362            rtt_ms: Some(42),
1363            age_secs: Some(3),
1364            meta: String::new(),
1365            principal: None,
1366            path: Default::default(),
1367        };
1368        let v = serde_json::to_value(&r).unwrap();
1369        assert_eq!(v["name"], "bob");
1370        assert_eq!(v["reachable"], true);
1371        assert_eq!(v["rtt_ms"], 42);
1372        assert_eq!(v["age_secs"], 3);
1373        // Never-probed peer: optionals elided, not null.
1374        let unknown = PeerReachability {
1375            name: "carol".into(),
1376            reachable: false,
1377            rtt_ms: None,
1378            age_secs: None,
1379            meta: String::new(),
1380            principal: None,
1381            path: Default::default(),
1382        };
1383        let uv = serde_json::to_value(&unknown).unwrap();
1384        assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
1385        // An older StatusResult (no reachability field) still deserializes.
1386        let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
1387        let s: StatusResult = serde_json::from_value(old).unwrap();
1388        assert!(s.reachability.is_empty());
1389    }
1390
1391    #[test]
1392    fn subscribe_method_tag_resolves() {
1393        let req = serde_json::to_value(Request::Subscribe).unwrap();
1394        assert_eq!(method_of(&req), Some("subscribe"));
1395    }
1396
1397    // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
1398
1399    #[test]
1400    fn invite_params_reject_singular_service_typo() {
1401        // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
1402        // InviteParams { services: [] } and mint a grants-nothing invite that looked
1403        // successful. With deny_unknown_fields the typo is a loud parse error instead.
1404        let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
1405        assert!(
1406            err.is_err(),
1407            "an unknown `service` key must be rejected, not silently ignored"
1408        );
1409        // The correct plural shape still parses.
1410        let ok: InviteParams =
1411            serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
1412        assert_eq!(ok.services, vec!["kb".to_string()]);
1413    }
1414
1415    #[test]
1416    fn open_session_params_reject_unknown_field() {
1417        let err = serde_json::from_value::<OpenSessionParams>(
1418            serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
1419        );
1420        assert!(err.is_err(), "unknown params keys must be rejected");
1421    }
1422
1423    #[test]
1424    fn set_app_metadata_request_carries_the_method_tag() {
1425        let r = Request::SetAppMetadata(SetAppMetadataParams {
1426            metadata: "v=1.2.3".into(),
1427        });
1428        let v = serde_json::to_value(&r).unwrap();
1429        assert_eq!(v["method"], "set_app_metadata");
1430        assert_eq!(v["params"]["metadata"], "v=1.2.3");
1431        assert_eq!(method_of(&v), Some("set_app_metadata"));
1432    }
1433
1434    #[test]
1435    fn set_app_metadata_params_reject_unknown_field() {
1436        let err = serde_json::from_value::<SetAppMetadataParams>(
1437            serde_json::json!({"metadata": "x", "nonsense": 1}),
1438        );
1439        assert!(err.is_err(), "unknown params keys must be rejected");
1440    }
1441
1442    /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1443    /// empty meta does not serialize.
1444    #[test]
1445    fn peer_info_principal_is_additive() {
1446        // An older payload (no principal) still deserializes; empty does not serialize.
1447        let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1448        let p: PeerInfo = serde_json::from_value(old).unwrap();
1449        assert_eq!(p.principal, None);
1450        assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1451        // A bound peer carries BOTH the person user_id AND the device principal (#41).
1452        let full = PeerInfo {
1453            name: "bob".into(),
1454            services: vec!["notes".into()],
1455            user_id: Some("b64u:BOB".into()),
1456            principal: Some("eid:0707".into()),
1457        };
1458        let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1459        assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1460        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1461    }
1462
1463    #[test]
1464    fn active_session_principal_is_additive() {
1465        // An OLD payload (no `principal`) must still deserialize — #73 is additive.
1466        let old: ActiveSession =
1467            serde_json::from_str(r#"{"peer":"bob","service":"notes","opened_at":7}"#).unwrap();
1468        assert_eq!(old.principal, None, "serde(default) supplies it");
1469
1470        // And a `None` must not serialize, so an old client sees the shape it expects.
1471        let json = serde_json::to_string(&old).unwrap();
1472        assert!(
1473            !json.contains("principal"),
1474            "skip_serializing_if must omit it: {json}"
1475        );
1476
1477        // A real row round-trips the principal.
1478        let new = ActiveSession {
1479            peer: "bob".into(),
1480            service: "notes".into(),
1481            opened_at: 7,
1482            principal: Some("eid:1f0a".into()),
1483        };
1484        let back: ActiveSession =
1485            serde_json::from_str(&serde_json::to_string(&new).unwrap()).unwrap();
1486        assert_eq!(back.principal.as_deref(), Some("eid:1f0a"));
1487    }
1488
1489    #[test]
1490    fn peer_reachability_principal_is_additive() {
1491        // Older payload (no principal) still deserializes; empty does not serialize; a set
1492        // value round-trips alongside the #40 meta so an embedder joins on the principal.
1493        let old = serde_json::json!({"name": "bob", "reachable": true});
1494        let r: PeerReachability = serde_json::from_value(old).unwrap();
1495        assert_eq!(r.principal, None);
1496        assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1497        let full = PeerReachability {
1498            name: "bob".into(),
1499            reachable: true,
1500            rtt_ms: Some(12),
1501            age_secs: Some(3),
1502            meta: "v=1.2.3".into(),
1503            principal: Some("eid:0707".into()),
1504            path: Default::default(),
1505        };
1506        let back: PeerReachability =
1507            serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1508        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1509        assert_eq!(back.meta, "v=1.2.3");
1510    }
1511
1512    #[test]
1513    fn peer_reachability_meta_is_additive() {
1514        // An older payload (no meta) still deserializes; an empty meta does not serialize.
1515        let old = serde_json::json!({"name": "bob", "reachable": true});
1516        let r: PeerReachability = serde_json::from_value(old).unwrap();
1517        assert_eq!(r.meta, "");
1518        assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1519        // A set value round-trips.
1520        let with = PeerReachability {
1521            name: "bob".into(),
1522            reachable: true,
1523            rtt_ms: Some(12),
1524            age_secs: Some(3),
1525            meta: "v=1.2.3".into(),
1526            principal: None,
1527            path: Default::default(),
1528        };
1529        let back: PeerReachability =
1530            serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1531        assert_eq!(back.meta, "v=1.2.3");
1532    }
1533
1534    #[test]
1535    fn presence_peer_meta_is_additive() {
1536        let old = serde_json::json!({
1537            "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1538        });
1539        let p: PresencePeer = serde_json::from_value(old).unwrap();
1540        assert_eq!(p.meta, "");
1541        assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1542    }
1543
1544    #[test]
1545    fn set_nickname_request_carries_the_method_tag() {
1546        let r = Request::SetNickname(SetNicknameParams {
1547            nickname: "workbench".into(),
1548        });
1549        let v = serde_json::to_value(&r).unwrap();
1550        assert_eq!(v["method"], "set_nickname");
1551        assert_eq!(v["params"]["nickname"], "workbench");
1552        assert_eq!(method_of(&v), Some("set_nickname"));
1553    }
1554
1555    #[test]
1556    fn set_nickname_params_reject_unknown_field() {
1557        let err = serde_json::from_value::<SetNicknameParams>(
1558            serde_json::json!({"nickname": "x", "nonsense": 1}),
1559        );
1560        assert!(err.is_err(), "unknown params keys must be rejected");
1561    }
1562
1563    /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1564    /// the additive-only contract — and an empty name must not serialize at all.
1565    #[test]
1566    fn status_self_nickname_is_additive() {
1567        let old = serde_json::json!({
1568            "stack_version": "0.7.0", "services": [], "peers": []
1569        });
1570        let s: StatusResult = serde_json::from_value(old).unwrap();
1571        assert_eq!(s.self_nickname, "");
1572        let v = serde_json::to_value(&s).unwrap();
1573        assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1574    }
1575
1576    #[test]
1577    fn api_minor_is_present_and_monotonic_from_hello() {
1578        // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1579        // crate/stack version, additive on the Hello frame.
1580        let h = Hello {
1581            api: API_NAME.into(),
1582            api_version: API_VERSION.into(),
1583            api_minor: API_MINOR,
1584            stack_version: "9.9.9".into(),
1585        };
1586        let v = serde_json::to_value(&h).unwrap();
1587        assert_eq!(v["api_minor"], API_MINOR);
1588        // An OLD Hello without api_minor still deserializes (additive contract).
1589        let old = serde_json::json!({
1590            "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1591        });
1592        let back: Hello = serde_json::from_value(old).unwrap();
1593        assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1594    }
1595
1596    #[test]
1597    fn hello_result_roundtrips() {
1598        let h = Hello {
1599            api: "mcpmesh-local/1".into(),
1600            api_version: "1.0".into(),
1601            api_minor: 0,
1602            stack_version: "0.1.0".into(),
1603        };
1604        let v = serde_json::to_value(&h).unwrap();
1605        assert_eq!(v["api"], "mcpmesh-local/1");
1606        let back: Hello = serde_json::from_value(v).unwrap();
1607        assert_eq!(back, h);
1608    }
1609
1610    #[test]
1611    fn request_tagged_by_method() {
1612        let r = Request::Status;
1613        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1614        let r = Request::OpenSession(OpenSessionParams {
1615            peer: "alice".into(),
1616            service: "notes".into(),
1617        });
1618        let v = serde_json::to_value(&r).unwrap();
1619        assert_eq!(v["method"], "open_session");
1620        assert_eq!(v["params"]["peer"], "alice");
1621    }
1622
1623    #[test]
1624    fn parameterless_method_tolerates_params_forms() {
1625        // Omitted and null params deserialize straight into the unit variant.
1626        let omitted: Request =
1627            serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1628        assert_eq!(omitted, Request::Status);
1629        let null: Request =
1630            serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1631                .unwrap();
1632        assert_eq!(null, Request::Status);
1633
1634        // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1635        // the server MUST dispatch on the method string rather than deserialize the whole
1636        // message into `Request`. This is the pattern the daemon's dispatcher uses.
1637        let empty = serde_json::json!({"method": "status", "params": {}});
1638        assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1639        match method_of(&empty) {
1640            Some("status") => {} // dispatcher resolves Status via the method string
1641            other => panic!("method_of failed to resolve status: {other:?}"),
1642        }
1643    }
1644
1645    #[test]
1646    fn backend_spec_roundtrips() {
1647        let run = BackendSpec::Run {
1648            cmd: vec!["notes-mcp".into(), "--stdio".into()],
1649            env: Default::default(),
1650            cwd: None,
1651        };
1652        let v = serde_json::to_value(&run).unwrap();
1653        assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1654        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1655
1656        let sock = BackendSpec::Socket {
1657            path: "/run/notes.sock".into(),
1658        };
1659        let v = serde_json::to_value(&sock).unwrap();
1660        assert_eq!(v["socket"]["path"], "/run/notes.sock");
1661        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1662    }
1663
1664    #[test]
1665    fn register_service_wire_shape() {
1666        let r = Request::RegisterService(RegisterServiceParams {
1667            name: "notes".into(),
1668            backend: BackendSpec::Run {
1669                cmd: vec!["notes-mcp".into()],
1670                env: Default::default(),
1671                cwd: None,
1672            },
1673            allow: vec!["alice".into()],
1674            ephemeral: false,
1675        });
1676        let v = serde_json::to_value(&r).unwrap();
1677        assert_eq!(
1678            v,
1679            serde_json::json!({
1680                "method": "register_service",
1681                "params": {
1682                    "name": "notes",
1683                    "backend": {"run": {"cmd": ["notes-mcp"]}},
1684                    "allow": ["alice"],
1685                }
1686            })
1687        );
1688        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1689    }
1690
1691    #[test]
1692    fn invite_request_and_result_roundtrip() {
1693        // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1694        let r = Request::Invite(InviteParams {
1695            services: vec!["notes".into(), "kb".into()],
1696            app_label: None,
1697        });
1698        let v = serde_json::to_value(&r).unwrap();
1699        assert_eq!(v["method"], "invite");
1700        assert_eq!(v["params"]["services"][0], "notes");
1701        assert_eq!(v["params"]["services"][1], "kb");
1702        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1703        // method_of resolves the tag generically (no per-variant arm).
1704        assert_eq!(
1705            method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1706            Some("invite")
1707        );
1708
1709        // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1710        let res = InviteResult {
1711            invite_line: "mcpmesh-invite:ABCDEF".into(),
1712            expires_at_epoch: 1_800_000_000,
1713        };
1714        let v = serde_json::to_value(&res).unwrap();
1715        assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1716        assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1717        assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1718    }
1719
1720    #[test]
1721    fn pair_request_and_result_roundtrip() {
1722        // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1723        let r = Request::Pair(PairParams {
1724            invite_line: "mcpmesh-invite:ABCDEF".into(),
1725        });
1726        let v = serde_json::to_value(&r).unwrap();
1727        assert_eq!(v["method"], "pair");
1728        assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1729        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1730        // method_of resolves the tag generically (no per-variant arm).
1731        assert_eq!(
1732            method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1733            Some("pair")
1734        );
1735
1736        // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1737        // the granted services (the porcelain renders each as `<peer>/<service>`).
1738        let res = PairResult {
1739            peer_nickname: "alice".into(),
1740            sas_code: "tango-fig-cabbage".into(),
1741            services: vec!["notes".into(), "kb".into()],
1742            app_label: None,
1743            peer_user_id: None,
1744        };
1745        let v = serde_json::to_value(&res).unwrap();
1746        assert_eq!(v["peer_nickname"], "alice");
1747        assert_eq!(v["sas_code"], "tango-fig-cabbage");
1748        assert_eq!(v["services"][0], "notes");
1749        assert_eq!(v["services"][1], "kb");
1750        assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1751
1752        // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1753        // deserializes — the `#[serde(default)]` fills it with an empty list.
1754        let old_shape = serde_json::json!({
1755            "peer_nickname": "alice",
1756            "sas_code": "tango-fig-cabbage",
1757        });
1758        let back: PairResult = serde_json::from_value(old_shape).unwrap();
1759        assert_eq!(back.peer_nickname, "alice");
1760        assert!(back.services.is_empty());
1761    }
1762
1763    #[test]
1764    fn roster_install_request_and_result_roundtrip() {
1765        // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1766        // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1767        let r = Request::RosterInstall(RosterInstallParams {
1768            path: "/tmp/roster.json".into(),
1769            org_root_pk: Some("b64u:AAAA".into()),
1770        });
1771        let v = serde_json::to_value(&r).unwrap();
1772        assert_eq!(v["method"], "roster_install");
1773        assert_eq!(v["params"]["path"], "/tmp/roster.json");
1774        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1775        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1776        // method_of resolves the tag generically (no per-variant arm).
1777        assert_eq!(
1778            method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1779            Some("roster_install")
1780        );
1781
1782        // When the pk is omitted (a subsequent install using the pinned value), it is
1783        // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1784        let omit = Request::RosterInstall(RosterInstallParams {
1785            path: "/tmp/roster.json".into(),
1786            org_root_pk: None,
1787        });
1788        let v = serde_json::to_value(&omit).unwrap();
1789        assert!(
1790            v["params"].get("org_root_pk").is_none(),
1791            "an omitted org_root_pk must not appear on the wire: {v}"
1792        );
1793        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1794
1795        // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1796        let res = RosterInstallResult {
1797            org_id: "acme".into(),
1798            serial: 42,
1799            severed: 1,
1800        };
1801        let v = serde_json::to_value(&res).unwrap();
1802        assert_eq!(v["org_id"], "acme");
1803        assert_eq!(v["serial"], 42u64);
1804        assert_eq!(v["severed"], 1u32);
1805        assert_eq!(
1806            serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1807            res
1808        );
1809
1810        // Additive-only: a result minted by an older daemon (no `severed` key) still
1811        // deserializes — the `#[serde(default)]` fills it with 0.
1812        let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1813        let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1814        assert_eq!(back.serial, 7);
1815        assert_eq!(back.severed, 0);
1816    }
1817
1818    #[test]
1819    fn org_join_request_and_result_roundtrip() {
1820        // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1821        // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1822        let r = Request::OrgJoin(OrgJoinParams {
1823            org_id: "acme".into(),
1824            org_root_pk: "b64u:AAAA".into(),
1825            user_id: "alice".into(),
1826            user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1827        });
1828        let v = serde_json::to_value(&r).unwrap();
1829        assert_eq!(v["method"], "org_join");
1830        assert_eq!(v["params"]["org_id"], "acme");
1831        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1832        assert_eq!(v["params"]["user_id"], "alice");
1833        assert_eq!(
1834            v["params"]["user_key"],
1835            "/home/alice/.config/mcpmesh/user.key"
1836        );
1837        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1838        // method_of resolves the tag generically (no per-variant arm).
1839        assert_eq!(
1840            method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1841            Some("org_join")
1842        );
1843
1844        // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1845        let res = OrgJoinResult {
1846            org_id: "acme".into(),
1847        };
1848        let v = serde_json::to_value(&res).unwrap();
1849        assert_eq!(v["org_id"], "acme");
1850        assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1851    }
1852
1853    #[test]
1854    fn set_roster_url_request_roundtrip() {
1855        // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1856        let r = Request::SetRosterUrl(SetRosterUrlParams {
1857            url: "https://intranet.acme.com/roster.json".into(),
1858        });
1859        let v = serde_json::to_value(&r).unwrap();
1860        assert_eq!(v["method"], "set_roster_url");
1861        assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1862        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1863        assert_eq!(
1864            method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1865            Some("set_roster_url")
1866        );
1867    }
1868
1869    #[test]
1870    fn peer_remove_request_roundtrip() {
1871        // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1872        let r = Request::PeerRemove(PeerRemoveParams {
1873            nickname: "bob".into(),
1874        });
1875        let v = serde_json::to_value(&r).unwrap();
1876        assert_eq!(v["method"], "peer_remove");
1877        assert_eq!(v["params"]["nickname"], "bob");
1878        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1879        // method_of resolves the tag generically (no per-variant arm).
1880        assert_eq!(
1881            method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1882            Some("peer_remove")
1883        );
1884    }
1885
1886    /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1887    /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1888    /// defaulting to empty when absent.
1889    #[test]
1890    fn peer_add_request_roundtrip() {
1891        let r = Request::PeerAdd(PeerAddParams {
1892            nickname: "bob".into(),
1893            endpoint_id: "96246d3f".into(),
1894            allow: vec!["notes".into()],
1895        });
1896        let v = serde_json::to_value(&r).unwrap();
1897        assert_eq!(v["method"], "peer_add");
1898        assert_eq!(v["params"]["nickname"], "bob");
1899        assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1900        assert_eq!(v["params"]["allow"][0], "notes");
1901        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1902        // An absent allow list deserializes to empty (the server-side tolerance).
1903        let p: PeerAddParams =
1904            serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1905                .unwrap();
1906        assert!(p.allow.is_empty());
1907    }
1908
1909    #[test]
1910    fn peer_rename_request_roundtrip() {
1911        // By user_id (renames all of a person's devices in one op).
1912        let r = Request::PeerRename(PeerRenameParams {
1913            user_id: Some("b64u:BOB".into()),
1914            nickname: None,
1915            to: "Bobby".into(),
1916        });
1917        let v = serde_json::to_value(&r).unwrap();
1918        assert_eq!(v["method"], "peer_rename");
1919        assert_eq!(v["params"]["user_id"], "b64u:BOB");
1920        assert_eq!(v["params"]["to"], "Bobby");
1921        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1922        // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1923        assert_eq!(
1924            method_of(
1925                &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1926            ),
1927            Some("peer_rename")
1928        );
1929    }
1930
1931    #[test]
1932    fn status_result_roundtrips() {
1933        // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1934        // older payload with no `roster` key still deserializes to None (serde default).
1935        let s = StatusResult {
1936            stack_version: "0.1.0".into(),
1937            services: vec![ServiceInfo {
1938                name: "notes".into(),
1939                allow: vec!["alice".into()],
1940                allow_display: vec![],
1941                backend: BackendKind::Run,
1942                ephemeral: false,
1943            }],
1944            peers: vec![PeerInfo {
1945                name: "alice".into(),
1946                services: vec!["notes".into()],
1947                // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1948                user_id: Some("b64u:alicepk".into()),
1949                principal: None,
1950            }],
1951            roster: None,
1952            presence: vec![],
1953            self_user_id: Some("b64u:selfpk".into()),
1954            recent_pairings: vec![],
1955            reachability: vec![],
1956            self_nickname: String::new(),
1957            storage: None,
1958        };
1959        let v = serde_json::to_value(&s).unwrap();
1960        assert_eq!(v["services"][0]["backend"], "run");
1961        // The additive identity fields ride the wire when present.
1962        assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1963        assert_eq!(v["self_user_id"], "b64u:selfpk");
1964        assert!(
1965            v.get("roster").is_none(),
1966            "an absent roster must not appear on the wire: {v}"
1967        );
1968        assert!(
1969            v.get("presence").is_none(),
1970            "an empty presence must not appear on the wire: {v}"
1971        );
1972        assert!(
1973            v.get("recent_pairings").is_none(),
1974            "an empty recent_pairings must not appear on the wire: {v}"
1975        );
1976        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1977
1978        // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1979        // deserializes — the identity fields default to None / a nickname-only peer.
1980        let old_shape = serde_json::json!({
1981            "stack_version": "0.1.0",
1982            "services": [],
1983            "peers": [{ "name": "bob", "services": [] }],
1984        });
1985        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1986        assert!(back.roster.is_none());
1987        assert!(back.presence.is_empty());
1988        assert!(back.self_user_id.is_none());
1989        assert!(back.peers[0].user_id.is_none());
1990        assert!(back.recent_pairings.is_empty());
1991
1992        // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1993        // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1994        let s = StatusResult {
1995            stack_version: "0.1.0".into(),
1996            services: vec![],
1997            peers: vec![],
1998            roster: Some(RosterStatus {
1999                org_id: "acme".into(),
2000                serial: 42,
2001                state: "approved".into(),
2002                org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
2003            }),
2004            presence: vec![
2005                PresencePeer {
2006                    user_id: "alice".into(),
2007                    device_label: "laptop".into(),
2008                    role: "primary".into(),
2009                    online: true,
2010                    meta: String::new(),
2011                },
2012                PresencePeer {
2013                    user_id: "alice".into(),
2014                    device_label: "desktop".into(),
2015                    role: "mirror".into(),
2016                    online: false,
2017                    meta: String::new(),
2018                },
2019            ],
2020            self_user_id: None,
2021            recent_pairings: vec![],
2022            reachability: vec![],
2023            self_nickname: String::new(),
2024            storage: None,
2025        };
2026        let v = serde_json::to_value(&s).unwrap();
2027        assert_eq!(v["roster"]["org_id"], "acme");
2028        assert_eq!(v["roster"]["serial"], 42u64);
2029        assert_eq!(v["roster"]["state"], "approved");
2030        assert_eq!(
2031            v["roster"]["org_root_fingerprint"],
2032            "tango-fig-cabbage-anchor"
2033        );
2034        assert_eq!(v["presence"][0]["user_id"], "alice");
2035        assert_eq!(v["presence"][0]["device_label"], "laptop");
2036        assert_eq!(v["presence"][0]["role"], "primary");
2037        assert_eq!(v["presence"][0]["online"], true);
2038        assert_eq!(v["presence"][1]["online"], false);
2039        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
2040    }
2041
2042    /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
2043    /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
2044    /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
2045    /// older daemon (no key at all) still deserializes to empty.
2046    #[test]
2047    fn recent_pairings_are_additive_on_status() {
2048        let s = StatusResult {
2049            stack_version: "0.1.0".into(),
2050            services: vec![],
2051            peers: vec![],
2052            roster: None,
2053            presence: vec![],
2054            self_user_id: None,
2055            recent_pairings: vec![RecentPairing {
2056                peer_nickname: "bob".into(),
2057                sas_code: "tango-fig-cabbage".into(),
2058                paired_at_epoch: 1_800_000_000,
2059            }],
2060            reachability: vec![],
2061            self_nickname: String::new(),
2062            storage: None,
2063        };
2064        let v = serde_json::to_value(&s).unwrap();
2065        assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
2066        assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
2067        assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
2068        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
2069
2070        // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
2071        // the `#[serde(default)]` fills it with an empty list.
2072        let old_shape = serde_json::json!({
2073            "stack_version": "0.1.0",
2074            "services": [],
2075            "peers": [],
2076        });
2077        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
2078        assert!(back.recent_pairings.is_empty());
2079    }
2080
2081    #[test]
2082    fn blob_requests_and_results_roundtrip() {
2083        // BlobPublish → { method, params: { scope, path } }.
2084        let r = Request::BlobPublish(BlobPublishParams {
2085            scope: "docs".into(),
2086            path: "/tmp/a.bin".into(),
2087        });
2088        let v = serde_json::to_value(&r).unwrap();
2089        assert_eq!(v["method"], "blob_publish");
2090        assert_eq!(v["params"]["scope"], "docs");
2091        assert_eq!(v["params"]["path"], "/tmp/a.bin");
2092        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2093
2094        // BlobGrant → { method, params: { scope, principal } }.
2095        // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
2096        // would otherwise ship undetected — the e2e test calls the provider directly and never
2097        // crosses JSON-RPC.
2098        let rev = Request::BlobRevoke(BlobRevokeParams {
2099            scope: "photos".into(),
2100            principals: vec!["alice".into()],
2101        });
2102        let v = serde_json::to_value(&rev).unwrap();
2103        assert_eq!(v["method"], "blob_revoke");
2104        assert_eq!(v["params"]["principals"][0], "alice");
2105        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
2106
2107        let unp = Request::BlobUnpublish(BlobUnpublishParams {
2108            scope: "photos".into(),
2109            hash: "abc123".into(),
2110        });
2111        let v = serde_json::to_value(&unp).unwrap();
2112        assert_eq!(v["method"], "blob_unpublish");
2113        assert_eq!(v["params"]["hash"], "abc123");
2114        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
2115
2116        let r = Request::BlobGrant(BlobGrantParams {
2117            scope: "docs".into(),
2118            principal: "alice".into(),
2119        });
2120        let v = serde_json::to_value(&r).unwrap();
2121        assert_eq!(v["method"], "blob_grant");
2122        assert_eq!(v["params"]["principal"], "alice");
2123        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2124
2125        // BlobList is parameterless (method_of resolves it).
2126        assert_eq!(
2127            method_of(&serde_json::json!({"method": "blob_list"})),
2128            Some("blob_list")
2129        );
2130
2131        // BlobFetch → { method, params: { ticket, dest_path } }.
2132        let r = Request::BlobFetch(BlobFetchParams {
2133            ticket: "blobAAA".into(),
2134            dest_path: "/tmp/out.bin".into(),
2135        });
2136        let v = serde_json::to_value(&r).unwrap();
2137        assert_eq!(v["method"], "blob_fetch");
2138        assert_eq!(v["params"]["ticket"], "blobAAA");
2139        assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
2140        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2141
2142        // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
2143        let res = BlobPublishResult {
2144            ticket: "blobAAA".into(),
2145            hash: "ab".repeat(32),
2146        };
2147        let v = serde_json::to_value(&res).unwrap();
2148        assert_eq!(v["ticket"], "blobAAA");
2149        assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
2150
2151        // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
2152        let res = BlobScopeList {
2153            scopes: vec![ScopeInfo {
2154                name: "docs".into(),
2155                hashes: vec!["ab".repeat(32)],
2156                grants: vec!["alice".into()],
2157                withdrawn: vec![],
2158                hash_count: 1,
2159                grant_count: 1,
2160                withdrawn_count: 0,
2161            }],
2162            total: 1,
2163            truncated: false,
2164        };
2165        let v = serde_json::to_value(&res).unwrap();
2166        assert_eq!(v["scopes"][0]["name"], "docs");
2167        assert_eq!(v["scopes"][0]["grants"][0], "alice");
2168        assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
2169
2170        // BlobFetchResult carries the verified hash + byte length.
2171        let res = BlobFetchResult {
2172            hash: "ab".repeat(32),
2173            bytes_len: 4194304,
2174        };
2175        let v = serde_json::to_value(&res).unwrap();
2176        assert_eq!(v["bytes_len"], 4194304u64);
2177        assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
2178    }
2179
2180    /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
2181    /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
2182    /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
2183    /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
2184    #[test]
2185    fn stream_frames_roundtrip_with_the_documented_tags() {
2186        let snap = StreamFrame::Snapshot {
2187            active_sessions: vec![ActiveSession {
2188                peer: "bob".into(),
2189                service: "notes".into(),
2190                opened_at: 1_751_760_000,
2191                principal: None,
2192            }],
2193            reachability: vec![PeerReachability {
2194                name: "bob".into(),
2195                reachable: true,
2196                rtt_ms: Some(42),
2197                age_secs: Some(3),
2198                meta: String::new(),
2199                principal: None,
2200                path: Default::default(),
2201            }],
2202        };
2203        let v = serde_json::to_value(&snap).unwrap();
2204        assert_eq!(v["type"], "snapshot");
2205        assert_eq!(v["active_sessions"][0]["peer"], "bob");
2206        assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
2207        assert_eq!(v["reachability"][0]["name"], "bob");
2208        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
2209
2210        let event = StreamFrame::Event {
2211            record: Box::new(AuditRecord::session_open(
2212                "2026-07-03T14:02:11.480Z".into(),
2213                Some("bob".into()),
2214                "notes".into(),
2215            )),
2216        };
2217        let v = serde_json::to_value(&event).unwrap();
2218        assert_eq!(v["type"], "event");
2219        // The record's fields ride verbatim under `record` — no Box indirection on the wire.
2220        assert_eq!(v["record"]["kind"], "session_open");
2221        assert_eq!(v["record"]["peer"], "bob");
2222        assert_eq!(v["record"]["service"], "notes");
2223        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
2224
2225        let lagged = StreamFrame::Lagged { dropped: 12 };
2226        let v = serde_json::to_value(&lagged).unwrap();
2227        assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
2228        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
2229    }
2230
2231    /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
2232    /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
2233    /// raw `Value` stream instead (`ControlClient::open_stream`).
2234    #[test]
2235    fn unknown_stream_frame_type_is_rejected() {
2236        let future = serde_json::json!({ "type": "future_kind", "x": 1 });
2237        assert!(serde_json::from_value::<StreamFrame>(future).is_err());
2238    }
2239
2240    #[test]
2241    fn audit_summary_request_and_result_roundtrip() {
2242        // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
2243        // tolerates omitted/null params; the server dispatches on the method string (method_of).
2244        let r = Request::AuditSummary;
2245        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
2246        assert_eq!(
2247            method_of(&serde_json::json!({"method": "audit_summary"})),
2248            Some("audit_summary")
2249        );
2250
2251        // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
2252        // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
2253        // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
2254        let res = AuditSummaryResult {
2255            per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
2256            per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
2257            total_sessions: 4,
2258        };
2259        let v = serde_json::to_value(&res).unwrap();
2260        assert_eq!(v["per_peer"][1][0], "bob");
2261        assert_eq!(v["per_peer"][1][1], 2u64);
2262        assert_eq!(v["per_service"][1][0], "notes");
2263        assert_eq!(v["total_sessions"], 4u64);
2264        assert_eq!(
2265            serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
2266            res
2267        );
2268
2269        // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
2270        // deserializes — the `#[serde(default)]` fills it with 0.
2271        let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
2272        let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
2273        assert_eq!(back.total_sessions, 0);
2274        assert!(back.per_peer.is_empty());
2275    }
2276}