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