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