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