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/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean:
84/// a nickname + a bool + latency/age NUMBERS — never an endpoint-id, key, or transport path.
85#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
86pub struct PeerReachability {
87    pub name: String,    // the peer's nickname
88    pub reachable: bool, // result of the last probe (false if never probed)
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub rtt_ms: Option<u64>, // last measured round-trip, if reachable
91    #[serde(default, skip_serializing_if = "Option::is_none")]
92    pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
93    /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
94    /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
95    /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
96    /// display data; never an authz input. Near-real-time when `status` is read (the probe
97    /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
98    #[serde(default, skip_serializing_if = "String::is_empty")]
99    pub meta: String,
100    /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
101    /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
102    /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
103    /// for a real row (`Option` only for additive round-trip). Machine-surface authz
104    /// vocabulary — the human `status` reachability line is unchanged. Additive:
105    /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    pub principal: Option<String>,
108}
109
110/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
111/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
112/// as-transport-vocab. Absent in a pure-pairing daemon.
113#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
114pub struct RosterStatus {
115    pub org_id: String,
116    pub serial: u64,
117    pub state: String, // "pending" | "approved" | "degraded" | "stopped"
118    pub org_root_fingerprint: String, // short-word form
119}
120
121/// One reachable roster peer device as reported by `status` (the advisory presence read).
122/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
123/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
124/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PresencePeer {
127    pub user_id: String,
128    pub device_label: String,
129    pub role: String, // "primary" | "mirror" (roster vocabulary)
130    /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
131    pub online: bool,
132    /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
133    /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
134    /// data; never an authz input. Additive: default + skip-if-empty.
135    #[serde(default, skip_serializing_if = "String::is_empty")]
136    pub meta: String,
137}
138
139/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
140/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
141/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
142/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
143/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
144/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
145/// an epoch — never an EndpointId.
146#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
147pub struct RecentPairing {
148    /// The peer's nickname as stored by the inviter (its local name for the redeemer).
149    pub peer_nickname: String,
150    /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
151    /// `PairResult.sas_code` carried. Never checked programmatically.
152    pub sas_code: String,
153    /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
154    pub paired_at_epoch: u64,
155}
156
157#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
158pub struct StatusResult {
159    pub stack_version: String,
160    pub services: Vec<ServiceInfo>,
161    pub peers: Vec<PeerInfo>,
162    /// Roster-mode status, absent in a pure-pairing daemon. Additive:
163    /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
164    #[serde(default, skip_serializing_if = "Option::is_none")]
165    pub roster: Option<RosterStatus>,
166    /// The reachable roster peer devices (the advisory presence read), each with an `online`
167    /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
168    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
169    #[serde(default, skip_serializing_if = "Vec::is_empty")]
170    pub presence: Vec<PresencePeer>,
171    /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
172    /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
173    /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
174    /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
175    #[serde(default, skip_serializing_if = "Option::is_none")]
176    pub self_user_id: Option<String>,
177    /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
178    /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
179    /// that has accepted no pairing since it started. Additive:
180    /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
181    #[serde(default, skip_serializing_if = "Vec::is_empty")]
182    pub recent_pairings: Vec<RecentPairing>,
183    /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
184    /// first probe completes. Additive: default + skip-if-empty.
185    #[serde(default, skip_serializing_if = "Vec::is_empty")]
186    pub reachability: Vec<PeerReachability>,
187    /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
188    /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
189    /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
190    /// skip-if-empty so an older payload round-trips.
191    #[serde(default, skip_serializing_if = "String::is_empty")]
192    pub self_nickname: String,
193}
194
195/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
196#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
197#[serde(deny_unknown_fields)]
198pub struct RegisterServiceParams {
199    pub name: String,
200    pub backend: BackendSpec,
201    pub allow: Vec<String>,
202    /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
203    /// to the on-disk config, and automatically unregistered when the control connection that
204    /// registered it closes (and gone on daemon restart). For an embedder that serves a
205    /// `socket` backend from a fresh path each run, this removes the need to derive a stable
206    /// socket path solely to keep a persisted registration valid, and the stale-registration
207    /// accumulation that comes with no unregister. Default false = the persistent behavior.
208    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
209    pub ephemeral: bool,
210}
211
212/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
213/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
214/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
215/// list (an invite that grants nothing is useless — #34).
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
217#[serde(deny_unknown_fields)]
218pub struct InviteParams {
219    #[serde(default)]
220    pub services: Vec<String>,
221    /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
222    /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
223    /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
224    #[serde(default, skip_serializing_if = "Option::is_none")]
225    pub app_label: Option<String>,
226}
227
228/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
229/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
230#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
231#[serde(deny_unknown_fields)]
232pub struct PairParams {
233    #[serde(default)]
234    pub invite_line: String,
235}
236
237/// Params of [`Request::PeerRemove`]: the nickname to unpair.
238#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
239#[serde(deny_unknown_fields)]
240pub struct PeerRemoveParams {
241    pub nickname: String,
242}
243
244/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
245/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
247#[serde(deny_unknown_fields)]
248pub struct PeerRenameParams {
249    #[serde(default)]
250    pub user_id: Option<String>,
251    #[serde(default)]
252    pub nickname: Option<String>,
253    pub to: String,
254}
255
256/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
257/// (iroh base32) plus the nickname and service allow list to install it under.
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(deny_unknown_fields)]
260pub struct PeerAddParams {
261    pub nickname: String,
262    pub endpoint_id: String,
263    #[serde(default)]
264    pub allow: Vec<String>,
265}
266
267/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
268/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(deny_unknown_fields)]
271pub struct OpenSessionParams {
272    #[serde(default)]
273    pub peer: String,
274    #[serde(default)]
275    pub service: String,
276}
277
278/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
279/// on FIRST install (`b64u:`; omit once pinned — config carries it).
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
281#[serde(deny_unknown_fields)]
282pub struct RosterInstallParams {
283    pub path: String,
284    #[serde(default, skip_serializing_if = "Option::is_none")]
285    pub org_root_pk: Option<String>,
286}
287
288/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
289/// never crosses the API.
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(deny_unknown_fields)]
292pub struct OrgJoinParams {
293    pub org_id: String,
294    pub org_root_pk: String,
295    pub user_id: String,
296    pub user_key: String,
297}
298
299/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
300/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
301/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
302/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304#[serde(deny_unknown_fields)]
305pub struct SetAppMetadataParams {
306    pub metadata: String,
307}
308
309/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
310/// principal, or a `b64u:` user_id.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct PeerServicesParams {
314    pub peer: String,
315}
316
317/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
318/// caller — computed authoritatively on the peer (which owns the truth), always current, only
319/// the caller's own admitted services (never the peer's full registry).
320#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
321pub struct PeerServicesResult {
322    pub services: Vec<String>,
323}
324
325/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
326/// to remove — the deregistration mirror of `register_service`.
327#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
328#[serde(deny_unknown_fields)]
329pub struct UnregisterServiceParams {
330    pub name: String,
331}
332
333/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
334/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
335/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(deny_unknown_fields)]
338pub struct ServiceAllowParams {
339    pub service: String,
340    pub principal: String,
341}
342
343/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
344/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
345/// they stored at pairing time until a re-invite.
346#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
347#[serde(deny_unknown_fields)]
348pub struct SetNicknameParams {
349    pub nickname: String,
350}
351
352/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(deny_unknown_fields)]
355pub struct SetRosterUrlParams {
356    pub url: String,
357}
358
359/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
360/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
361/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
362/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
363/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
364/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
365/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
366/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct SetRelaysParams {
370    pub relay_urls: Vec<String>,
371}
372
373/// Result of [`Request::SetRelays`] (#53).
374#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
375pub struct SetRelaysResult {
376    /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
377    pub changed: bool,
378    /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
379    /// but NOT applied live — a node restart is required for it to take effect. `false` on the
380    /// live custom→custom path (already applied to the running endpoint).
381    pub restart_required: bool,
382}
383
384/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
385#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
386#[serde(deny_unknown_fields)]
387pub struct BlobPublishParams {
388    pub scope: String,
389    pub path: String,
390}
391
392/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394#[serde(deny_unknown_fields)]
395pub struct BlobGrantParams {
396    pub scope: String,
397    pub principal: String,
398}
399
400/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
401#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
402#[serde(deny_unknown_fields)]
403pub struct BlobFetchParams {
404    pub ticket: String,
405    pub dest_path: String,
406}
407
408/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
409/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
410///
411/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
412/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
413/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
414/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
415/// identical to inline variant bodies.
416///
417/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
418/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
419/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
420/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
421/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
422#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
423#[serde(tag = "method", content = "params", rename_all = "snake_case")]
424pub enum Request {
425    /// Register/update a `[services.*]` entry idempotently.
426    RegisterService(RegisterServiceParams),
427    Status,
428    /// Mint a one-time pairing invite granting `services`. The daemon
429    /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
430    /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
431    /// `method` string generically; the tag comes from `rename_all`.
432    Invite(InviteParams),
433    /// Redeem a pairing invite. The daemon dials the inviter named by
434    /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
435    /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
436    /// (snake_case); `method_of` reads the `method` string generically.
437    ///
438    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
439    Pair(PairParams),
440    /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
441    /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
442    /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
443    /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
444    /// NOT severed here: existing sessions run to completion; the peer only loses the
445    /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
446    /// `method_of` reads the `method` string generically (no per-variant arm).
447    ///
448    /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
449    PeerRemove(PeerRemoveParams),
450    /// Rename a contact's nickname (nickname) authoritatively. Renames the
451    /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
452    /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
453    /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
454    /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
455    /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
456    /// host-privileged like the other pair ops.
457    PeerRename(PeerRenameParams),
458    /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
459    /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
460    /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
461    /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
462    /// vocabulary — do not build on it. Tag `"peer_add"`.
463    PeerAdd(PeerAddParams),
464    /// Open a mesh session to `peer/service`; the daemon dials and pipes.
465    /// Distinct from the proxy's job: this returns a session the client streams.
466    /// Named `open_session` rather than `connect` to avoid colliding
467    /// with the `connect` porcelain.
468    OpenSession(OpenSessionParams),
469    /// Install a signed roster from a local file (the manual `internal roster install` path).
470    /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
471    /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
472    /// pins the org root on FIRST install (`b64u:`); omit it
473    /// once pinned (config carries it). Tag `"roster_install"`.
474    RosterInstall(RosterInstallParams),
475    /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
476    /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
477    /// `user_key` is a LOCAL path
478    /// (the key never crosses the API). Tag `"org_join"`.
479    OrgJoin(OrgJoinParams),
480    /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
481    /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
482    /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
483    /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
484    /// `"set_roster_url"`.
485    SetRosterUrl(SetRosterUrlParams),
486    /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
487    /// daemon's own serialized config-write path (no lost-update window against a
488    /// concurrent grant/registration) and update the in-memory name future invites
489    /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
490    SetNickname(SetNicknameParams),
491    /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
492    /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
493    /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
494    /// on restart; the embedder re-sets on startup).
495    SetAppMetadata(SetAppMetadataParams),
496    /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
497    /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
498    /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
499    /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
500    /// is currently `default`/`disabled`, the config is persisted but the live mode transition
501    /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
502    /// [`SetRelaysResult`]. Tag `"set_relays"`.
503    SetRelays(SetRelaysParams),
504    /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
505    /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
506    /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
507    /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
508    /// hot-reloads. Idempotent. Ack result.
509    UnregisterService(UnregisterServiceParams),
510    /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
511    /// and returns the service names whose allow admits the caller's principal. Answers
512    /// [`PeerServicesResult`].
513    PeerServices(PeerServicesParams),
514    ServiceAllowGrant(ServiceAllowParams),
515    /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
516    /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
517    /// Idempotent. Ack result.
518    ServiceAllowRevoke(ServiceAllowParams),
519    /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
520    /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
521    /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
522    /// Tag `"blob_publish"`.
523    BlobPublish(BlobPublishParams),
524    /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
525    /// nickname (the shared `principal_set` expansion). Tag
526    /// `"blob_grant"`.
527    BlobGrant(BlobGrantParams),
528    /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
529    BlobList,
530    /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
531    /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
532    /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
533    BlobFetch(BlobFetchParams),
534    /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
535    /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
536    /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
537    /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
538    /// `method_of` reads the `method` string generically (no per-variant arm).
539    AuditSummary,
540    /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
541    /// connection STOPS being request/response after this call and becomes a one-way push stream
542    /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
543    Subscribe,
544}
545
546/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
547/// computed porcelain-side from the invite's org_root_pk). Additive-only.
548#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
549pub struct OrgJoinResult {
550    pub org_id: String,
551}
552
553/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
554/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
555/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
556///
557/// Additive-only: any future field MUST land as
558/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
559#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
560pub struct RosterInstallResult {
561    pub org_id: String,
562    pub serial: u64,
563    /// How many live sessions were severed, for the porcelain's confirmation line.
564    #[serde(default)]
565    pub severed: u32,
566}
567
568/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
569/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
570/// carve-out as the pairing invite line). Additive-only.
571#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
572pub struct BlobPublishResult {
573    pub ticket: String,
574    pub hash: String, // bare blake3 hex
575}
576
577/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
578/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
579#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
580pub struct ScopeInfo {
581    pub name: String,
582    pub hashes: Vec<String>,
583    pub grants: Vec<String>,
584}
585
586/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
587#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
588pub struct BlobScopeList {
589    pub scopes: Vec<ScopeInfo>,
590}
591
592/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
593/// Additive-only.
594#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
595pub struct BlobFetchResult {
596    pub hash: String,
597    pub bytes_len: u64,
598}
599
600/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
601/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
602/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
603/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
604/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
605/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
606///
607/// Additive-only: any future field MUST land as
608/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
609#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
610pub struct AuditSummaryResult {
611    /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
612    /// peer to attribute) but IS in `total_sessions`.
613    pub per_peer: Vec<(String, u64)>,
614    /// Sessions opened per registered service name.
615    pub per_service: Vec<(String, u64)>,
616    /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
617    #[serde(default)]
618    pub total_sessions: u64,
619}
620
621/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
622/// (the ONE pairing artifact deliberately carved out of the
623/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
624/// absolute expiry in epoch seconds (≤ now + 24h).
625///
626/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
627/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
628/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
629/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
630/// ceremony" note in `docs/local-protocol.md` (#35).
631///
632/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
633/// so older payloads still deserialize.
634#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
635pub struct InviteResult {
636    /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
637    pub invite_line: String,
638    /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
639    pub expires_at_epoch: u64,
640}
641
642/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
643/// redeemer's local name for the new peer) plus the display-only short authentication
644/// code (SAS) — a few words the human reads aloud to a second channel to
645/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
646/// artifact (like the invite line), NOT a transport-vocabulary leak.
647///
648/// Additive-only: any future field MUST land as
649/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
650#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
651pub struct PairResult {
652    /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
653    pub peer_nickname: String,
654    /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
655    /// sides for the out-of-band human check. Never sent on the wire, never checked
656    /// programmatically.
657    pub sas_code: String,
658    /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
659    /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
660    /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
661    /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
662    /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
663    #[serde(default, skip_serializing_if = "Vec::is_empty")]
664    pub services: Vec<String>,
665    /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
666    /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
667    #[serde(default, skip_serializing_if = "Option::is_none")]
668    pub app_label: Option<String>,
669    /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
670    /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
671    /// can align with its own — and the same value it may later pass to `open_session` to dial
672    /// this peer by identity rather than by local nickname. `None` if the inviter presented no
673    /// binding (a legacy/keyless peer). Additive.
674    #[serde(default, skip_serializing_if = "Option::is_none")]
675    pub peer_user_id: Option<String>,
676}
677
678/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
679/// top of the base record schema: it removes no field and makes the JSONL self-describing so
680/// a consumer can filter by class without guessing from which optional fields are present.
681#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
682#[serde(rename_all = "snake_case")]
683pub enum AuditKind {
684    /// A mesh session opened (a backend was selected for an authenticated peer).
685    /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
686    /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
687    SessionOpen,
688    /// A mesh session closed (the backend returned / the session tore down).
689    SessionClose,
690    /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
691    Request,
692    /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
693    BlobFetch,
694    /// A trust mutation (pair, unpair, roster install/swap, revoke).
695    Trust,
696}
697
698/// One audit record — the union of the event classes, and the `record` payload of a
699/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
700/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
701/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
702/// `bytes_out`).
703///
704/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
705/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
706/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
707#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
708pub struct AuditRecord {
709    /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
710    /// prefix also selects the monthly file (the rotation boundary), so it is always present.
711    pub ts: String,
712    pub kind: AuditKind,
713    /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
714    /// local-only events with no remote peer (a manual roster install).
715    #[serde(skip_serializing_if = "Option::is_none")]
716    pub peer: Option<String>,
717    #[serde(skip_serializing_if = "Option::is_none")]
718    pub service: Option<String>,
719    #[serde(skip_serializing_if = "Option::is_none")]
720    pub method: Option<String>,
721    /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
722    #[serde(skip_serializing_if = "Option::is_none")]
723    pub tool: Option<String>,
724    /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
725    #[serde(skip_serializing_if = "Option::is_none")]
726    pub args_hash: Option<String>,
727    /// Byte COUNT of the response sent back to the peer — a count, never the content.
728    #[serde(skip_serializing_if = "Option::is_none")]
729    pub bytes_out: Option<u64>,
730    /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
731    #[serde(skip_serializing_if = "Option::is_none")]
732    pub status: Option<String>,
733    #[serde(skip_serializing_if = "Option::is_none")]
734    pub latency_ms: Option<u64>,
735    /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
736    #[serde(skip_serializing_if = "Option::is_none")]
737    pub event: Option<String>,
738    /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
739    /// nickname or `org/serial` (`Trust`).
740    #[serde(skip_serializing_if = "Option::is_none")]
741    pub target: Option<String>,
742}
743
744impl AuditRecord {
745    fn base(ts: String, kind: AuditKind) -> Self {
746        Self {
747            ts,
748            kind,
749            peer: None,
750            service: None,
751            method: None,
752            tool: None,
753            args_hash: None,
754            bytes_out: None,
755            status: None,
756            latency_ms: None,
757            event: None,
758            target: None,
759        }
760    }
761
762    pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
763        let mut r = Self::base(ts, AuditKind::SessionOpen);
764        r.peer = peer;
765        r.service = Some(service);
766        r
767    }
768
769    /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
770    /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
771    /// reaches no backend and so is never audited by the far side's session guard — without a
772    /// dedicated constructor. DRY: reuses the existing optional `status` field.
773    pub fn with_status(mut self, status: &str) -> Self {
774        self.status = Some(status.into());
775        self
776    }
777
778    pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
779        let mut r = Self::base(ts, AuditKind::SessionClose);
780        r.peer = peer;
781        r.service = Some(service);
782        r
783    }
784
785    /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
786    /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
787    /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
788    #[allow(clippy::too_many_arguments)]
789    pub fn proxied_request(
790        ts: String,
791        peer: Option<String>,
792        service: String,
793        method: String,
794        tool: Option<String>,
795        args_hash: String,
796        bytes_out: u64,
797        status: String,
798        latency_ms: u64,
799    ) -> Self {
800        let mut r = Self::base(ts, AuditKind::Request);
801        r.peer = peer;
802        r.service = Some(service);
803        r.method = Some(method);
804        r.tool = tool;
805        r.args_hash = Some(args_hash);
806        r.bytes_out = Some(bytes_out);
807        r.status = Some(status);
808        r.latency_ms = Some(latency_ms);
809        r
810    }
811
812    /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
813    /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
814    pub fn proxied_notification(
815        ts: String,
816        peer: Option<String>,
817        service: String,
818        method: String,
819        tool: Option<String>,
820        args_hash: String,
821    ) -> Self {
822        let mut r = Self::base(ts, AuditKind::Request);
823        r.peer = peer;
824        r.service = Some(service);
825        r.method = Some(method);
826        r.tool = tool;
827        r.args_hash = Some(args_hash);
828        r
829    }
830
831    pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
832        let mut r = Self::base(ts, AuditKind::BlobFetch);
833        r.peer = peer;
834        r.target = Some(hash);
835        r.status = Some(status);
836        r
837    }
838
839    pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
840        let mut r = Self::base(ts, AuditKind::Trust);
841        r.event = Some(event);
842        r.target = target;
843        r
844    }
845}
846
847/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
848/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
849#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
850pub struct ActiveSession {
851    pub peer: String,
852    pub service: String,
853    pub opened_at: i64,
854}
855
856/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
857/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
858/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
859/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
860/// them (see `docs/local-protocol.md` "Live event stream").
861#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
862#[serde(tag = "type", rename_all = "snake_case")]
863pub enum StreamFrame {
864    /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
865    /// reachability) so a fresh subscriber renders immediately without replaying history.
866    Snapshot {
867        active_sessions: Vec<ActiveSession>,
868        reachability: Vec<PeerReachability>,
869    },
870    /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
871    /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
872    /// `Box`, so the wire shape is the record's fields verbatim.
873    Event { record: Box<AuditRecord> },
874    /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
875    /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
876    Lagged { dropped: u64 },
877}
878
879/// Extract the `method` tag from a raw request value without deserializing the whole
880/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
881/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
882/// methods (adjacent tagging rejects `params:{}` on unit variants).
883pub fn method_of(v: &serde_json::Value) -> Option<&str> {
884    v.get("method").and_then(serde_json::Value::as_str)
885}
886
887/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
888/// Config→BackendSpec is a hand-written match, not a serde passthrough.
889#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
890#[serde(rename_all = "snake_case")]
891pub enum BackendSpec {
892    Run {
893        cmd: Vec<String>,
894        /// Per-service environment variables (#51) for the spawned child. Overlaid on the
895        /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
896        /// these (identity is not spoofable by a service definition). Default empty.
897        #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
898        env: BTreeMap<String, String>,
899        /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
900        #[serde(default, skip_serializing_if = "Option::is_none")]
901        cwd: Option<String>,
902    },
903    Socket {
904        path: String,
905    },
906}
907
908pub const API_NAME: &str = "mcpmesh-local/1";
909/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
910///
911/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
912///   transport already rejects a mismatched `api`, so an equality check on that is redundant).
913/// - **MINOR** ([`API_MINOR`]) increments on EVERY surface change within a major — additive fields,
914///   new methods, or a strictness change like params validation — bumped in the same change that
915///   makes it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon
916///   older than a minor it requires. It never resets except on a MAJOR bump.
917pub const API_VERSION: &str = "1.9";
918/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
919/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
920/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
921/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
922/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
923/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
924/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
925/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
926/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
927/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53).
928pub const API_MINOR: u32 = 9;
929
930#[cfg(test)]
931mod tests {
932    use super::*;
933
934    #[test]
935    fn peer_reachability_serde_is_additive() {
936        let r = PeerReachability {
937            name: "bob".into(),
938            reachable: true,
939            rtt_ms: Some(42),
940            age_secs: Some(3),
941            meta: String::new(),
942            principal: None,
943        };
944        let v = serde_json::to_value(&r).unwrap();
945        assert_eq!(v["name"], "bob");
946        assert_eq!(v["reachable"], true);
947        assert_eq!(v["rtt_ms"], 42);
948        assert_eq!(v["age_secs"], 3);
949        // Never-probed peer: optionals elided, not null.
950        let unknown = PeerReachability {
951            name: "carol".into(),
952            reachable: false,
953            rtt_ms: None,
954            age_secs: None,
955            meta: String::new(),
956            principal: None,
957        };
958        let uv = serde_json::to_value(&unknown).unwrap();
959        assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
960        // An older StatusResult (no reachability field) still deserializes.
961        let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
962        let s: StatusResult = serde_json::from_value(old).unwrap();
963        assert!(s.reachability.is_empty());
964    }
965
966    #[test]
967    fn subscribe_method_tag_resolves() {
968        let req = serde_json::to_value(Request::Subscribe).unwrap();
969        assert_eq!(method_of(&req), Some("subscribe"));
970    }
971
972    // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
973
974    #[test]
975    fn invite_params_reject_singular_service_typo() {
976        // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
977        // InviteParams { services: [] } and mint a grants-nothing invite that looked
978        // successful. With deny_unknown_fields the typo is a loud parse error instead.
979        let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
980        assert!(
981            err.is_err(),
982            "an unknown `service` key must be rejected, not silently ignored"
983        );
984        // The correct plural shape still parses.
985        let ok: InviteParams =
986            serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
987        assert_eq!(ok.services, vec!["kb".to_string()]);
988    }
989
990    #[test]
991    fn open_session_params_reject_unknown_field() {
992        let err = serde_json::from_value::<OpenSessionParams>(
993            serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
994        );
995        assert!(err.is_err(), "unknown params keys must be rejected");
996    }
997
998    #[test]
999    fn set_app_metadata_request_carries_the_method_tag() {
1000        let r = Request::SetAppMetadata(SetAppMetadataParams {
1001            metadata: "v=1.2.3".into(),
1002        });
1003        let v = serde_json::to_value(&r).unwrap();
1004        assert_eq!(v["method"], "set_app_metadata");
1005        assert_eq!(v["params"]["metadata"], "v=1.2.3");
1006        assert_eq!(method_of(&v), Some("set_app_metadata"));
1007    }
1008
1009    #[test]
1010    fn set_app_metadata_params_reject_unknown_field() {
1011        let err = serde_json::from_value::<SetAppMetadataParams>(
1012            serde_json::json!({"metadata": "x", "nonsense": 1}),
1013        );
1014        assert!(err.is_err(), "unknown params keys must be rejected");
1015    }
1016
1017    /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1018    /// empty meta does not serialize.
1019    #[test]
1020    fn peer_info_principal_is_additive() {
1021        // An older payload (no principal) still deserializes; empty does not serialize.
1022        let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1023        let p: PeerInfo = serde_json::from_value(old).unwrap();
1024        assert_eq!(p.principal, None);
1025        assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1026        // A bound peer carries BOTH the person user_id AND the device principal (#41).
1027        let full = PeerInfo {
1028            name: "bob".into(),
1029            services: vec!["notes".into()],
1030            user_id: Some("b64u:BOB".into()),
1031            principal: Some("eid:0707".into()),
1032        };
1033        let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1034        assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1035        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1036    }
1037
1038    #[test]
1039    fn peer_reachability_principal_is_additive() {
1040        // Older payload (no principal) still deserializes; empty does not serialize; a set
1041        // value round-trips alongside the #40 meta so an embedder joins on the principal.
1042        let old = serde_json::json!({"name": "bob", "reachable": true});
1043        let r: PeerReachability = serde_json::from_value(old).unwrap();
1044        assert_eq!(r.principal, None);
1045        assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1046        let full = PeerReachability {
1047            name: "bob".into(),
1048            reachable: true,
1049            rtt_ms: Some(12),
1050            age_secs: Some(3),
1051            meta: "v=1.2.3".into(),
1052            principal: Some("eid:0707".into()),
1053        };
1054        let back: PeerReachability =
1055            serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1056        assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1057        assert_eq!(back.meta, "v=1.2.3");
1058    }
1059
1060    #[test]
1061    fn peer_reachability_meta_is_additive() {
1062        // An older payload (no meta) still deserializes; an empty meta does not serialize.
1063        let old = serde_json::json!({"name": "bob", "reachable": true});
1064        let r: PeerReachability = serde_json::from_value(old).unwrap();
1065        assert_eq!(r.meta, "");
1066        assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1067        // A set value round-trips.
1068        let with = PeerReachability {
1069            name: "bob".into(),
1070            reachable: true,
1071            rtt_ms: Some(12),
1072            age_secs: Some(3),
1073            meta: "v=1.2.3".into(),
1074            principal: None,
1075        };
1076        let back: PeerReachability =
1077            serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1078        assert_eq!(back.meta, "v=1.2.3");
1079    }
1080
1081    #[test]
1082    fn presence_peer_meta_is_additive() {
1083        let old = serde_json::json!({
1084            "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1085        });
1086        let p: PresencePeer = serde_json::from_value(old).unwrap();
1087        assert_eq!(p.meta, "");
1088        assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1089    }
1090
1091    #[test]
1092    fn set_nickname_request_carries_the_method_tag() {
1093        let r = Request::SetNickname(SetNicknameParams {
1094            nickname: "workbench".into(),
1095        });
1096        let v = serde_json::to_value(&r).unwrap();
1097        assert_eq!(v["method"], "set_nickname");
1098        assert_eq!(v["params"]["nickname"], "workbench");
1099        assert_eq!(method_of(&v), Some("set_nickname"));
1100    }
1101
1102    #[test]
1103    fn set_nickname_params_reject_unknown_field() {
1104        let err = serde_json::from_value::<SetNicknameParams>(
1105            serde_json::json!({"nickname": "x", "nonsense": 1}),
1106        );
1107        assert!(err.is_err(), "unknown params keys must be rejected");
1108    }
1109
1110    /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1111    /// the additive-only contract — and an empty name must not serialize at all.
1112    #[test]
1113    fn status_self_nickname_is_additive() {
1114        let old = serde_json::json!({
1115            "stack_version": "0.7.0", "services": [], "peers": []
1116        });
1117        let s: StatusResult = serde_json::from_value(old).unwrap();
1118        assert_eq!(s.self_nickname, "");
1119        let v = serde_json::to_value(&s).unwrap();
1120        assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1121    }
1122
1123    #[test]
1124    fn api_minor_is_present_and_monotonic_from_hello() {
1125        // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1126        // crate/stack version, additive on the Hello frame.
1127        let h = Hello {
1128            api: API_NAME.into(),
1129            api_version: API_VERSION.into(),
1130            api_minor: API_MINOR,
1131            stack_version: "9.9.9".into(),
1132        };
1133        let v = serde_json::to_value(&h).unwrap();
1134        assert_eq!(v["api_minor"], API_MINOR);
1135        // An OLD Hello without api_minor still deserializes (additive contract).
1136        let old = serde_json::json!({
1137            "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1138        });
1139        let back: Hello = serde_json::from_value(old).unwrap();
1140        assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1141    }
1142
1143    #[test]
1144    fn hello_result_roundtrips() {
1145        let h = Hello {
1146            api: "mcpmesh-local/1".into(),
1147            api_version: "1.0".into(),
1148            api_minor: 0,
1149            stack_version: "0.1.0".into(),
1150        };
1151        let v = serde_json::to_value(&h).unwrap();
1152        assert_eq!(v["api"], "mcpmesh-local/1");
1153        let back: Hello = serde_json::from_value(v).unwrap();
1154        assert_eq!(back, h);
1155    }
1156
1157    #[test]
1158    fn request_tagged_by_method() {
1159        let r = Request::Status;
1160        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1161        let r = Request::OpenSession(OpenSessionParams {
1162            peer: "alice".into(),
1163            service: "notes".into(),
1164        });
1165        let v = serde_json::to_value(&r).unwrap();
1166        assert_eq!(v["method"], "open_session");
1167        assert_eq!(v["params"]["peer"], "alice");
1168    }
1169
1170    #[test]
1171    fn parameterless_method_tolerates_params_forms() {
1172        // Omitted and null params deserialize straight into the unit variant.
1173        let omitted: Request =
1174            serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1175        assert_eq!(omitted, Request::Status);
1176        let null: Request =
1177            serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1178                .unwrap();
1179        assert_eq!(null, Request::Status);
1180
1181        // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1182        // the server MUST dispatch on the method string rather than deserialize the whole
1183        // message into `Request`. This is the pattern the daemon's dispatcher uses.
1184        let empty = serde_json::json!({"method": "status", "params": {}});
1185        assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1186        match method_of(&empty) {
1187            Some("status") => {} // dispatcher resolves Status via the method string
1188            other => panic!("method_of failed to resolve status: {other:?}"),
1189        }
1190    }
1191
1192    #[test]
1193    fn backend_spec_roundtrips() {
1194        let run = BackendSpec::Run {
1195            cmd: vec!["notes-mcp".into(), "--stdio".into()],
1196            env: Default::default(),
1197            cwd: None,
1198        };
1199        let v = serde_json::to_value(&run).unwrap();
1200        assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1201        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1202
1203        let sock = BackendSpec::Socket {
1204            path: "/run/notes.sock".into(),
1205        };
1206        let v = serde_json::to_value(&sock).unwrap();
1207        assert_eq!(v["socket"]["path"], "/run/notes.sock");
1208        assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1209    }
1210
1211    #[test]
1212    fn register_service_wire_shape() {
1213        let r = Request::RegisterService(RegisterServiceParams {
1214            name: "notes".into(),
1215            backend: BackendSpec::Run {
1216                cmd: vec!["notes-mcp".into()],
1217                env: Default::default(),
1218                cwd: None,
1219            },
1220            allow: vec!["alice".into()],
1221            ephemeral: false,
1222        });
1223        let v = serde_json::to_value(&r).unwrap();
1224        assert_eq!(
1225            v,
1226            serde_json::json!({
1227                "method": "register_service",
1228                "params": {
1229                    "name": "notes",
1230                    "backend": {"run": {"cmd": ["notes-mcp"]}},
1231                    "allow": ["alice"],
1232                }
1233            })
1234        );
1235        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1236    }
1237
1238    #[test]
1239    fn invite_request_and_result_roundtrip() {
1240        // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1241        let r = Request::Invite(InviteParams {
1242            services: vec!["notes".into(), "kb".into()],
1243            app_label: None,
1244        });
1245        let v = serde_json::to_value(&r).unwrap();
1246        assert_eq!(v["method"], "invite");
1247        assert_eq!(v["params"]["services"][0], "notes");
1248        assert_eq!(v["params"]["services"][1], "kb");
1249        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1250        // method_of resolves the tag generically (no per-variant arm).
1251        assert_eq!(
1252            method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1253            Some("invite")
1254        );
1255
1256        // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1257        let res = InviteResult {
1258            invite_line: "mcpmesh-invite:ABCDEF".into(),
1259            expires_at_epoch: 1_800_000_000,
1260        };
1261        let v = serde_json::to_value(&res).unwrap();
1262        assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1263        assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1264        assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1265    }
1266
1267    #[test]
1268    fn pair_request_and_result_roundtrip() {
1269        // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1270        let r = Request::Pair(PairParams {
1271            invite_line: "mcpmesh-invite:ABCDEF".into(),
1272        });
1273        let v = serde_json::to_value(&r).unwrap();
1274        assert_eq!(v["method"], "pair");
1275        assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1276        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1277        // method_of resolves the tag generically (no per-variant arm).
1278        assert_eq!(
1279            method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1280            Some("pair")
1281        );
1282
1283        // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1284        // the granted services (the porcelain renders each as `<peer>/<service>`).
1285        let res = PairResult {
1286            peer_nickname: "alice".into(),
1287            sas_code: "tango-fig-cabbage".into(),
1288            services: vec!["notes".into(), "kb".into()],
1289            app_label: None,
1290            peer_user_id: None,
1291        };
1292        let v = serde_json::to_value(&res).unwrap();
1293        assert_eq!(v["peer_nickname"], "alice");
1294        assert_eq!(v["sas_code"], "tango-fig-cabbage");
1295        assert_eq!(v["services"][0], "notes");
1296        assert_eq!(v["services"][1], "kb");
1297        assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1298
1299        // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1300        // deserializes — the `#[serde(default)]` fills it with an empty list.
1301        let old_shape = serde_json::json!({
1302            "peer_nickname": "alice",
1303            "sas_code": "tango-fig-cabbage",
1304        });
1305        let back: PairResult = serde_json::from_value(old_shape).unwrap();
1306        assert_eq!(back.peer_nickname, "alice");
1307        assert!(back.services.is_empty());
1308    }
1309
1310    #[test]
1311    fn roster_install_request_and_result_roundtrip() {
1312        // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1313        // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1314        let r = Request::RosterInstall(RosterInstallParams {
1315            path: "/tmp/roster.json".into(),
1316            org_root_pk: Some("b64u:AAAA".into()),
1317        });
1318        let v = serde_json::to_value(&r).unwrap();
1319        assert_eq!(v["method"], "roster_install");
1320        assert_eq!(v["params"]["path"], "/tmp/roster.json");
1321        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1322        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1323        // method_of resolves the tag generically (no per-variant arm).
1324        assert_eq!(
1325            method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1326            Some("roster_install")
1327        );
1328
1329        // When the pk is omitted (a subsequent install using the pinned value), it is
1330        // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1331        let omit = Request::RosterInstall(RosterInstallParams {
1332            path: "/tmp/roster.json".into(),
1333            org_root_pk: None,
1334        });
1335        let v = serde_json::to_value(&omit).unwrap();
1336        assert!(
1337            v["params"].get("org_root_pk").is_none(),
1338            "an omitted org_root_pk must not appear on the wire: {v}"
1339        );
1340        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1341
1342        // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1343        let res = RosterInstallResult {
1344            org_id: "acme".into(),
1345            serial: 42,
1346            severed: 1,
1347        };
1348        let v = serde_json::to_value(&res).unwrap();
1349        assert_eq!(v["org_id"], "acme");
1350        assert_eq!(v["serial"], 42u64);
1351        assert_eq!(v["severed"], 1u32);
1352        assert_eq!(
1353            serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1354            res
1355        );
1356
1357        // Additive-only: a result minted by an older daemon (no `severed` key) still
1358        // deserializes — the `#[serde(default)]` fills it with 0.
1359        let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1360        let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1361        assert_eq!(back.serial, 7);
1362        assert_eq!(back.severed, 0);
1363    }
1364
1365    #[test]
1366    fn org_join_request_and_result_roundtrip() {
1367        // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1368        // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1369        let r = Request::OrgJoin(OrgJoinParams {
1370            org_id: "acme".into(),
1371            org_root_pk: "b64u:AAAA".into(),
1372            user_id: "alice".into(),
1373            user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1374        });
1375        let v = serde_json::to_value(&r).unwrap();
1376        assert_eq!(v["method"], "org_join");
1377        assert_eq!(v["params"]["org_id"], "acme");
1378        assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1379        assert_eq!(v["params"]["user_id"], "alice");
1380        assert_eq!(
1381            v["params"]["user_key"],
1382            "/home/alice/.config/mcpmesh/user.key"
1383        );
1384        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1385        // method_of resolves the tag generically (no per-variant arm).
1386        assert_eq!(
1387            method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1388            Some("org_join")
1389        );
1390
1391        // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1392        let res = OrgJoinResult {
1393            org_id: "acme".into(),
1394        };
1395        let v = serde_json::to_value(&res).unwrap();
1396        assert_eq!(v["org_id"], "acme");
1397        assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1398    }
1399
1400    #[test]
1401    fn set_roster_url_request_roundtrip() {
1402        // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1403        let r = Request::SetRosterUrl(SetRosterUrlParams {
1404            url: "https://intranet.acme.com/roster.json".into(),
1405        });
1406        let v = serde_json::to_value(&r).unwrap();
1407        assert_eq!(v["method"], "set_roster_url");
1408        assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1409        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1410        assert_eq!(
1411            method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1412            Some("set_roster_url")
1413        );
1414    }
1415
1416    #[test]
1417    fn peer_remove_request_roundtrip() {
1418        // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1419        let r = Request::PeerRemove(PeerRemoveParams {
1420            nickname: "bob".into(),
1421        });
1422        let v = serde_json::to_value(&r).unwrap();
1423        assert_eq!(v["method"], "peer_remove");
1424        assert_eq!(v["params"]["nickname"], "bob");
1425        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1426        // method_of resolves the tag generically (no per-variant arm).
1427        assert_eq!(
1428            method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1429            Some("peer_remove")
1430        );
1431    }
1432
1433    /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1434    /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1435    /// defaulting to empty when absent.
1436    #[test]
1437    fn peer_add_request_roundtrip() {
1438        let r = Request::PeerAdd(PeerAddParams {
1439            nickname: "bob".into(),
1440            endpoint_id: "96246d3f".into(),
1441            allow: vec!["notes".into()],
1442        });
1443        let v = serde_json::to_value(&r).unwrap();
1444        assert_eq!(v["method"], "peer_add");
1445        assert_eq!(v["params"]["nickname"], "bob");
1446        assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1447        assert_eq!(v["params"]["allow"][0], "notes");
1448        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1449        // An absent allow list deserializes to empty (the server-side tolerance).
1450        let p: PeerAddParams =
1451            serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1452                .unwrap();
1453        assert!(p.allow.is_empty());
1454    }
1455
1456    #[test]
1457    fn peer_rename_request_roundtrip() {
1458        // By user_id (renames all of a person's devices in one op).
1459        let r = Request::PeerRename(PeerRenameParams {
1460            user_id: Some("b64u:BOB".into()),
1461            nickname: None,
1462            to: "Bobby".into(),
1463        });
1464        let v = serde_json::to_value(&r).unwrap();
1465        assert_eq!(v["method"], "peer_rename");
1466        assert_eq!(v["params"]["user_id"], "b64u:BOB");
1467        assert_eq!(v["params"]["to"], "Bobby");
1468        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1469        // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1470        assert_eq!(
1471            method_of(
1472                &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1473            ),
1474            Some("peer_rename")
1475        );
1476    }
1477
1478    #[test]
1479    fn status_result_roundtrips() {
1480        // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1481        // older payload with no `roster` key still deserializes to None (serde default).
1482        let s = StatusResult {
1483            stack_version: "0.1.0".into(),
1484            services: vec![ServiceInfo {
1485                name: "notes".into(),
1486                allow: vec!["alice".into()],
1487                allow_display: vec![],
1488                backend: BackendKind::Run,
1489                ephemeral: false,
1490            }],
1491            peers: vec![PeerInfo {
1492                name: "alice".into(),
1493                services: vec!["notes".into()],
1494                // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1495                user_id: Some("b64u:alicepk".into()),
1496                principal: None,
1497            }],
1498            roster: None,
1499            presence: vec![],
1500            self_user_id: Some("b64u:selfpk".into()),
1501            recent_pairings: vec![],
1502            reachability: vec![],
1503            self_nickname: String::new(),
1504        };
1505        let v = serde_json::to_value(&s).unwrap();
1506        assert_eq!(v["services"][0]["backend"], "run");
1507        // The additive identity fields ride the wire when present.
1508        assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1509        assert_eq!(v["self_user_id"], "b64u:selfpk");
1510        assert!(
1511            v.get("roster").is_none(),
1512            "an absent roster must not appear on the wire: {v}"
1513        );
1514        assert!(
1515            v.get("presence").is_none(),
1516            "an empty presence must not appear on the wire: {v}"
1517        );
1518        assert!(
1519            v.get("recent_pairings").is_none(),
1520            "an empty recent_pairings must not appear on the wire: {v}"
1521        );
1522        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1523
1524        // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1525        // deserializes — the identity fields default to None / a nickname-only peer.
1526        let old_shape = serde_json::json!({
1527            "stack_version": "0.1.0",
1528            "services": [],
1529            "peers": [{ "name": "bob", "services": [] }],
1530        });
1531        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1532        assert!(back.roster.is_none());
1533        assert!(back.presence.is_empty());
1534        assert!(back.self_user_id.is_none());
1535        assert!(back.peers[0].user_id.is_none());
1536        assert!(back.recent_pairings.is_empty());
1537
1538        // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1539        // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1540        let s = StatusResult {
1541            stack_version: "0.1.0".into(),
1542            services: vec![],
1543            peers: vec![],
1544            roster: Some(RosterStatus {
1545                org_id: "acme".into(),
1546                serial: 42,
1547                state: "approved".into(),
1548                org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1549            }),
1550            presence: vec![
1551                PresencePeer {
1552                    user_id: "alice".into(),
1553                    device_label: "laptop".into(),
1554                    role: "primary".into(),
1555                    online: true,
1556                    meta: String::new(),
1557                },
1558                PresencePeer {
1559                    user_id: "alice".into(),
1560                    device_label: "desktop".into(),
1561                    role: "mirror".into(),
1562                    online: false,
1563                    meta: String::new(),
1564                },
1565            ],
1566            self_user_id: None,
1567            recent_pairings: vec![],
1568            reachability: vec![],
1569            self_nickname: String::new(),
1570        };
1571        let v = serde_json::to_value(&s).unwrap();
1572        assert_eq!(v["roster"]["org_id"], "acme");
1573        assert_eq!(v["roster"]["serial"], 42u64);
1574        assert_eq!(v["roster"]["state"], "approved");
1575        assert_eq!(
1576            v["roster"]["org_root_fingerprint"],
1577            "tango-fig-cabbage-anchor"
1578        );
1579        assert_eq!(v["presence"][0]["user_id"], "alice");
1580        assert_eq!(v["presence"][0]["device_label"], "laptop");
1581        assert_eq!(v["presence"][0]["role"], "primary");
1582        assert_eq!(v["presence"][0]["online"], true);
1583        assert_eq!(v["presence"][1]["online"], false);
1584        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1585    }
1586
1587    /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1588    /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1589    /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1590    /// older daemon (no key at all) still deserializes to empty.
1591    #[test]
1592    fn recent_pairings_are_additive_on_status() {
1593        let s = StatusResult {
1594            stack_version: "0.1.0".into(),
1595            services: vec![],
1596            peers: vec![],
1597            roster: None,
1598            presence: vec![],
1599            self_user_id: None,
1600            recent_pairings: vec![RecentPairing {
1601                peer_nickname: "bob".into(),
1602                sas_code: "tango-fig-cabbage".into(),
1603                paired_at_epoch: 1_800_000_000,
1604            }],
1605            reachability: vec![],
1606            self_nickname: String::new(),
1607        };
1608        let v = serde_json::to_value(&s).unwrap();
1609        assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1610        assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1611        assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1612        assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1613
1614        // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1615        // the `#[serde(default)]` fills it with an empty list.
1616        let old_shape = serde_json::json!({
1617            "stack_version": "0.1.0",
1618            "services": [],
1619            "peers": [],
1620        });
1621        let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1622        assert!(back.recent_pairings.is_empty());
1623    }
1624
1625    #[test]
1626    fn blob_requests_and_results_roundtrip() {
1627        // BlobPublish → { method, params: { scope, path } }.
1628        let r = Request::BlobPublish(BlobPublishParams {
1629            scope: "docs".into(),
1630            path: "/tmp/a.bin".into(),
1631        });
1632        let v = serde_json::to_value(&r).unwrap();
1633        assert_eq!(v["method"], "blob_publish");
1634        assert_eq!(v["params"]["scope"], "docs");
1635        assert_eq!(v["params"]["path"], "/tmp/a.bin");
1636        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1637
1638        // BlobGrant → { method, params: { scope, principal } }.
1639        let r = Request::BlobGrant(BlobGrantParams {
1640            scope: "docs".into(),
1641            principal: "alice".into(),
1642        });
1643        let v = serde_json::to_value(&r).unwrap();
1644        assert_eq!(v["method"], "blob_grant");
1645        assert_eq!(v["params"]["principal"], "alice");
1646        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1647
1648        // BlobList is parameterless (method_of resolves it).
1649        assert_eq!(
1650            method_of(&serde_json::json!({"method": "blob_list"})),
1651            Some("blob_list")
1652        );
1653
1654        // BlobFetch → { method, params: { ticket, dest_path } }.
1655        let r = Request::BlobFetch(BlobFetchParams {
1656            ticket: "blobAAA".into(),
1657            dest_path: "/tmp/out.bin".into(),
1658        });
1659        let v = serde_json::to_value(&r).unwrap();
1660        assert_eq!(v["method"], "blob_fetch");
1661        assert_eq!(v["params"]["ticket"], "blobAAA");
1662        assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
1663        assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1664
1665        // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
1666        let res = BlobPublishResult {
1667            ticket: "blobAAA".into(),
1668            hash: "ab".repeat(32),
1669        };
1670        let v = serde_json::to_value(&res).unwrap();
1671        assert_eq!(v["ticket"], "blobAAA");
1672        assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
1673
1674        // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
1675        let res = BlobScopeList {
1676            scopes: vec![ScopeInfo {
1677                name: "docs".into(),
1678                hashes: vec!["ab".repeat(32)],
1679                grants: vec!["alice".into()],
1680            }],
1681        };
1682        let v = serde_json::to_value(&res).unwrap();
1683        assert_eq!(v["scopes"][0]["name"], "docs");
1684        assert_eq!(v["scopes"][0]["grants"][0], "alice");
1685        assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
1686
1687        // BlobFetchResult carries the verified hash + byte length.
1688        let res = BlobFetchResult {
1689            hash: "ab".repeat(32),
1690            bytes_len: 4194304,
1691        };
1692        let v = serde_json::to_value(&res).unwrap();
1693        assert_eq!(v["bytes_len"], 4194304u64);
1694        assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
1695    }
1696
1697    /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
1698    /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
1699    /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
1700    /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
1701    #[test]
1702    fn stream_frames_roundtrip_with_the_documented_tags() {
1703        let snap = StreamFrame::Snapshot {
1704            active_sessions: vec![ActiveSession {
1705                peer: "bob".into(),
1706                service: "notes".into(),
1707                opened_at: 1_751_760_000,
1708            }],
1709            reachability: vec![PeerReachability {
1710                name: "bob".into(),
1711                reachable: true,
1712                rtt_ms: Some(42),
1713                age_secs: Some(3),
1714                meta: String::new(),
1715                principal: None,
1716            }],
1717        };
1718        let v = serde_json::to_value(&snap).unwrap();
1719        assert_eq!(v["type"], "snapshot");
1720        assert_eq!(v["active_sessions"][0]["peer"], "bob");
1721        assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
1722        assert_eq!(v["reachability"][0]["name"], "bob");
1723        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
1724
1725        let event = StreamFrame::Event {
1726            record: Box::new(AuditRecord::session_open(
1727                "2026-07-03T14:02:11.480Z".into(),
1728                Some("bob".into()),
1729                "notes".into(),
1730            )),
1731        };
1732        let v = serde_json::to_value(&event).unwrap();
1733        assert_eq!(v["type"], "event");
1734        // The record's fields ride verbatim under `record` — no Box indirection on the wire.
1735        assert_eq!(v["record"]["kind"], "session_open");
1736        assert_eq!(v["record"]["peer"], "bob");
1737        assert_eq!(v["record"]["service"], "notes");
1738        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
1739
1740        let lagged = StreamFrame::Lagged { dropped: 12 };
1741        let v = serde_json::to_value(&lagged).unwrap();
1742        assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
1743        assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
1744    }
1745
1746    /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
1747    /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
1748    /// raw `Value` stream instead (`ControlClient::open_stream`).
1749    #[test]
1750    fn unknown_stream_frame_type_is_rejected() {
1751        let future = serde_json::json!({ "type": "future_kind", "x": 1 });
1752        assert!(serde_json::from_value::<StreamFrame>(future).is_err());
1753    }
1754
1755    #[test]
1756    fn audit_summary_request_and_result_roundtrip() {
1757        // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
1758        // tolerates omitted/null params; the server dispatches on the method string (method_of).
1759        let r = Request::AuditSummary;
1760        assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
1761        assert_eq!(
1762            method_of(&serde_json::json!({"method": "audit_summary"})),
1763            Some("audit_summary")
1764        );
1765
1766        // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
1767        // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
1768        // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
1769        let res = AuditSummaryResult {
1770            per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
1771            per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
1772            total_sessions: 4,
1773        };
1774        let v = serde_json::to_value(&res).unwrap();
1775        assert_eq!(v["per_peer"][1][0], "bob");
1776        assert_eq!(v["per_peer"][1][1], 2u64);
1777        assert_eq!(v["per_service"][1][0], "notes");
1778        assert_eq!(v["total_sessions"], 4u64);
1779        assert_eq!(
1780            serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
1781            res
1782        );
1783
1784        // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
1785        // deserializes — the `#[serde(default)]` fills it with 0.
1786        let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
1787        let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
1788        assert_eq!(back.total_sessions, 0);
1789        assert!(back.per_peer.is_empty());
1790    }
1791}