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