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