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