mcpmesh_local_api/protocol.rs
1//! mcpmesh-local/1 protocol types. Shared vocabulary between the daemon
2//! and its clients (porcelain, connect proxy, later the host shell). Wire framing
3//! is the family NDJSON codec — carried by the caller, not defined here.
4//!
5//! Request/response asymmetry: requests are one typed, closed enum (`Request`);
6//! responses are per-method typed structs deserialized from the JSON-RPC `result`
7//! Value — `Status` → [`StatusResult`], `RegisterService` → an ack, `OpenSession` →
8//! no JSON-RPC result at all: the socket STOPS being JSON-RPC and becomes a raw
9//! byte pipe.
10//!
11//! Additive-only: new fields (capabilities on `Hello`, groups/user_id on
12//! `PeerInfo`, device on `OpenSession`) MUST land as
13//! `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
14use std::collections::BTreeMap;
15
16use serde::{Deserialize, Serialize};
17
18/// The first exchange on any `*-local/N` socket (the family's hello convention).
19#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
20pub struct Hello {
21 pub api: String, // "mcpmesh-local/1"
22 pub api_version: String, // "MAJOR.MINOR" of the protocol surface (see API_MINOR)
23 /// The protocol-compatibility MINOR as an integer, for a trivial machine comparison
24 /// (`api_minor >= N`) without string parsing. Distinct from `stack_version` (the crate
25 /// release train). Additive: an older daemon omits it and it defaults to 0.
26 #[serde(default)]
27 pub api_minor: u32,
28 pub stack_version: String,
29}
30
31/// The kind of backend answering a service — the two valid values, enforced at the
32/// type level and kept in lockstep with `BackendSpec`'s variants. Status reports the
33/// kind only, never the command/path (no transport vocabulary).
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum BackendKind {
37 Run,
38 Socket,
39}
40
41/// A registered service as reported by `status` (no transport vocabulary).
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
43pub struct ServiceInfo {
44 pub name: String,
45 pub allow: Vec<String>, // STABLE principals (b64u:/eid:) or roster names (#38) — never nicknames
46 /// The HUMAN rendering of `allow`, index-aligned: each principal resolved to its peer's
47 /// display nickname by the daemon (which owns the store); an unresolvable stable
48 /// principal renders as a neutral placeholder — porcelain must show THESE, never raw
49 /// ids (surface discipline). Additive: default + skip-if-empty.
50 #[serde(default, skip_serializing_if = "Vec::is_empty")]
51 pub allow_display: Vec<String>,
52 pub backend: BackendKind, // "run" | "socket" (kind only, never the command/path)
53 /// True if this registration is ephemeral (#36): in-memory only, tied to the registering
54 /// control connection's lifetime, absent from config, gone on restart. Additive — an older
55 /// daemon omits it and it reads as `false` (the persistent default).
56 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
57 pub ephemeral: bool,
58}
59
60/// A known peer as reported by `status` (nickname only — never the EndpointId).
61#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
62pub struct PeerInfo {
63 pub name: String,
64 pub services: Vec<String>,
65 /// The peer's PROVEN self-sovereign `user_id` (`b64u:<user_pk>`) if it presented a verified
66 /// device->user binding at pairing (roster peers carry it too), else `None` (nickname-only). This
67 /// is a surface-clean identity (an opaque user id, NOT an EndpointId). Additive:
68 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so older payloads round-trip.
69 #[serde(default, skip_serializing_if = "Option::is_none")]
70 pub user_id: Option<String>,
71 /// The peer's stable DEVICE principal `eid:<hex>` (#41) — the SAME rendering the socket
72 /// backend injects into `_meta["mcpmesh/peer"]` and that appears in `[services.*].allow`.
73 /// Always present for a real peer (`Option` only for additive round-trip). Distinct from
74 /// `user_id` (the person-level `b64u:`, present only when the peer proved a binding): a
75 /// nickname is not unique, so an embedder keys caller-scoped decisions (dial the caller
76 /// back, "the requester's own data") on THIS, the authenticated endpoint. Machine-surface
77 /// authz vocabulary (like the allow lists) — human porcelain still shows the nickname.
78 /// Additive: `#[serde(default, skip_serializing_if = "Option::is_none")]`.
79 #[serde(default, skip_serializing_if = "Option::is_none")]
80 pub principal: Option<String>,
81}
82
83/// HOW a peer is reached (#64): a direct/hole-punched QUIC path, or through a relay.
84///
85/// `rtt_ms` is NOT a proxy for this — a fast relay beats a slow direct path — and iroh's own
86/// distinction was being dropped at the mcpmesh boundary. Three things depend on it: a truthful
87/// locality claim ("this traffic never left the building"), honest disclosure that a relayed path
88/// depends on third-party infrastructure, and diagnostics, since "slow" has a different cause and
89/// fix in each case.
90///
91/// **Only `Direct` supports a locality claim.** `Unknown` means "we do not know", NOT "private" —
92/// rendering it as private is the one misuse that turns this field into a false privacy statement.
93/// The daemon errs the same way: when a relay path is active it reports [`Relay`](Self::Relay) even
94/// if a direct path is live too, because overstating privacy is worse than understating it.
95///
96/// `#[non_exhaustive]`: iroh already has a third address kind (a custom transport) that could
97/// warrant a variant, and adding one to a public enum later breaks every downstream exhaustive
98/// `match` — the lesson #58 paid for.
99#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
100#[serde(tag = "kind", rename_all = "snake_case")]
101#[non_exhaustive]
102pub enum PeerPath {
103 /// A direct or hole-punched QUIC path: the bytes did not transit a relay.
104 Direct,
105 /// Through a relay server. `url` is the relay in use when known.
106 Relay {
107 #[serde(default, skip_serializing_if = "Option::is_none")]
108 url: Option<String>,
109 },
110 /// Not known: never probed, no selected path, or a transport mcpmesh does not model.
111 ///
112 /// `#[serde(other)]` makes this the landing spot for a `kind` a client has never heard of. That
113 /// is what actually buys wire-additivity: `#[non_exhaustive]` only protects the Rust `match`,
114 /// and without this an older client hits `unknown variant` and fails to deserialize the WHOLE
115 /// `PeerReachability` — one new path kind would break every `status` response it reads.
116 #[default]
117 #[serde(other)]
118 Unknown,
119}
120
121/// Advisory reachability of a paired peer (pairing-mode liveness). Surface-clean: a nickname, a
122/// bool, latency/age NUMBERS, the stable `eid:` principal (#42), and since #64 the PATH KIND —
123/// direct vs relay, plus the relay URL when relayed. Never a socket address, an IP, or a key: the
124/// path field says WHICH KIND of route is in use, never where the peer is.
125#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
126pub struct PeerReachability {
127 pub name: String, // the peer's nickname
128 pub reachable: bool, // result of the last probe (false if never probed)
129 #[serde(default, skip_serializing_if = "Option::is_none")]
130 /// Last measured round-trip, if reachable: dial + ping/pong, stamped AT THE PONG.
131 ///
132 /// It EXCLUDES the window the daemon spends afterwards determining which path the connection
133 /// settled on. Before 0.20.1 it included that window, so a relayed peer could never report
134 /// under 600ms and most of the figure was a deliberate wait rather than time on the wire —
135 /// an embedder read ~820ms across one LAN hop and reported it as a 66x latency regression
136 /// (#123). It is a wire-latency measurement now, so "relayed AND low rtt_ms" is a reachable
137 /// state and a usable diagnostic.
138 pub rtt_ms: Option<u64>,
139 #[serde(default, skip_serializing_if = "Option::is_none")]
140 pub age_secs: Option<u64>, // None = never probed (consumer shows "checking…")
141 /// The peer's OPTIONAL app metadata (#40) — the same opaque ≤256B blob #39 exposes via
142 /// presence, here carried on the pairing-mode `mcpmesh/ping/1` probe pong so PAIRED peers
143 /// (which have no presence gossip) see it too. Empty when the peer set none. Advisory
144 /// display data; never an authz input. Near-real-time when `status` is read (the probe
145 /// cache has a ~20s TTL), not a steady push. Additive: default + skip-if-empty.
146 #[serde(default, skip_serializing_if = "String::is_empty")]
147 pub meta: String,
148 /// The peer's stable DEVICE principal `eid:<hex>` (#42) — the SAME rendering as
149 /// [`PeerInfo::principal`], so an embedder joins probe result + `meta` (app version) to a
150 /// peer by the AUTHENTICATED endpoint rather than the non-unique nickname. Always present
151 /// for a real row (`Option` only for additive round-trip). Machine-surface authz
152 /// vocabulary — the human `status` reachability line is unchanged. Additive:
153 /// `#[serde(default, skip_serializing_if = "Option::is_none")]`.
154 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub principal: Option<String>,
156 /// HOW this peer is reached (#64) — see [`PeerPath`]. Captured by the same probe that sets
157 /// `reachable`/`rtt_ms`, so it shares their freshness: one TTL, one `age_secs`. `Unknown` for a
158 /// peer never probed. Additive (`#[serde(default)]`), so older rows and clients are unaffected.
159 #[serde(default)]
160 pub path: PeerPath,
161}
162
163/// Roster-mode status. Surface-clean roster VOCABULARY only: org_id, serial, a plain
164/// state word, and the pinned org-root FINGERPRINT in short words — never raw keys/EndpointIds/serials-
165/// as-transport-vocab. Absent in a pure-pairing daemon.
166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
167pub struct RosterStatus {
168 pub org_id: String,
169 pub serial: u64,
170 pub state: String, // "pending" | "approved" | "degraded" | "stopped"
171 pub org_root_fingerprint: String, // short-word form
172}
173
174/// One reachable roster peer device as reported by `status` (the advisory presence read).
175/// ADVISORY — this is a display convenience, never an authorization surface. Surface-clean:
176/// FLAT vocabulary ONLY — a `user_id`, a human `device_label`, its `role` word, and an `online`
177/// boolean. It carries NO EndpointId / pubkey / hash / ALPN or any transport vocabulary.
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179pub struct PresencePeer {
180 pub user_id: String,
181 pub device_label: String,
182 pub role: String, // "primary" | "mirror" (roster vocabulary)
183 /// Whether the device has a live presence heartbeat (advisory — absence never blocks a dial).
184 pub online: bool,
185 /// The device's OPTIONAL embedder-set app metadata (#39) — an opaque ≤256B blob carried
186 /// (signed) on its presence heartbeat, empty when the device set none. Advisory display
187 /// data; never an authz input. Additive: default + skip-if-empty.
188 #[serde(default, skip_serializing_if = "String::is_empty")]
189 pub meta: String,
190}
191
192/// One recently completed INVITER-side pairing, surfaced by `status` so the inviter's human can
193/// read the short authentication code (SAS) and compare it with the redeemer's out-of-band —
194/// the pairing ceremony is "both humans compare the code": the redeemer sees it in its
195/// [`PairResult`]; this is the inviter's porcelain surface for the same words. DISPLAY-ONLY
196/// ceremony state: held in-memory by the daemon (a small ring), lost on restart, NEVER an
197/// authorization input or trust data. Surface-clean: a nickname + the SAS wordlist words +
198/// an epoch — never an EndpointId.
199#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
200pub struct RecentPairing {
201 /// The peer's nickname as stored by the inviter (its local name for the redeemer).
202 pub peer_nickname: String,
203 /// The display-only SAS words (e.g. `"tango-fig-cabbage"`) — the same code the redeemer's
204 /// `PairResult.sas_code` carried. Never checked programmatically.
205 pub sas_code: String,
206 /// When the pairing completed (epoch seconds) — the porcelain renders a friendly age.
207 pub paired_at_epoch: u64,
208}
209
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211pub struct StatusResult {
212 pub stack_version: String,
213 pub services: Vec<ServiceInfo>,
214 pub peers: Vec<PeerInfo>,
215 /// Roster-mode status, absent in a pure-pairing daemon. Additive:
216 /// `#[serde(default, skip_serializing_if = ...)]` so a daemon/client without it round-trips.
217 #[serde(default, skip_serializing_if = "Option::is_none")]
218 pub roster: Option<RosterStatus>,
219 /// The reachable roster peer devices (the advisory presence read), each with an `online`
220 /// flag. Empty in a pure-pairing daemon / when no roster is installed. Additive:
221 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
222 #[serde(default, skip_serializing_if = "Vec::is_empty")]
223 pub presence: Vec<PresencePeer>,
224 /// THIS daemon's own self-sovereign `user_id` (`b64u:<user_pk>`), if it has a user key (auto-
225 /// minted at boot; shared by pairing AND roster mode). Lets the operator see + share their stable
226 /// identity that multiple devices resolve to. `None` only when no user key exists. Additive:
227 /// `#[serde(default, skip_serializing_if = "Option::is_none")]` so an older payload round-trips.
228 #[serde(default, skip_serializing_if = "Option::is_none")]
229 pub self_user_id: Option<String>,
230 /// Recent INVITER-side pairing completions, newest first (display-only pairing-ceremony aids —
231 /// see [`RecentPairing`]; in-memory on the daemon, cleared by a restart). Empty on a daemon
232 /// that has accepted no pairing since it started. Additive:
233 /// `#[serde(default, skip_serializing_if = "Vec::is_empty")]` so an older payload round-trips.
234 #[serde(default, skip_serializing_if = "Vec::is_empty")]
235 pub recent_pairings: Vec<RecentPairing>,
236 /// Advisory reachability of paired peers, from the on-demand probe cache. Empty until the
237 /// first probe completes. Additive: default + skip-if-empty.
238 #[serde(default, skip_serializing_if = "Vec::is_empty")]
239 pub reachability: Vec<PeerReachability>,
240 /// This node's EFFECTIVE self-nickname — what a freshly minted invite would present
241 /// (config `[identity].nickname`, else the hostname, else a fingerprint; live-updated by
242 /// `set_nickname`, #37). Empty only in mesh-less control-only mode. Additive: default +
243 /// skip-if-empty so an older payload round-trips.
244 #[serde(default, skip_serializing_if = "String::is_empty")]
245 pub self_nickname: String,
246}
247
248/// Params of [`Request::RegisterService`]: the `[services.*]` entry to write/update.
249#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(deny_unknown_fields)]
251pub struct RegisterServiceParams {
252 pub name: String,
253 pub backend: BackendSpec,
254 pub allow: Vec<String>,
255 /// When true (#36), the registration is EPHEMERAL: kept in daemon memory only, never written
256 /// to the on-disk config, and automatically unregistered when the control connection that
257 /// registered it closes (and gone on daemon restart). For an embedder that serves a
258 /// `socket` backend from a fresh path each run, this removes the need to derive a stable
259 /// socket path solely to keep a persisted registration valid, and the stale-registration
260 /// accumulation that comes with no unregister. Default false = the persistent behavior.
261 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
262 pub ephemeral: bool,
263}
264
265/// Params of [`Request::Invite`]: the services the minted invite grants. Rejects unknown
266/// fields (so `{service: "kb"}` — a singular typo — is a loud error, not a silently
267/// grants-nothing invite), and the daemon additionally rejects an empty/absent `services`
268/// list (an invite that grants nothing is useless — #34).
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270#[serde(deny_unknown_fields)]
271pub struct InviteParams {
272 #[serde(default)]
273 pub services: Vec<String>,
274 /// An OPAQUE, caller-chosen label carried through to the redeemer in the `pair` result (#31).
275 /// mcpmesh never interprets it (not a nickname, never resolved or authorized) — a per-pairing
276 /// metadata slot for the embedder (e.g. its own URN). Capped at the daemon; omit for none.
277 #[serde(default, skip_serializing_if = "Option::is_none")]
278 pub app_label: Option<String>,
279}
280
281/// Params of [`Request::Pair`]: the copyable `mcpmesh-invite:` line. Defaultable — an
282/// absent field reads as an empty line, which simply fails to decode (a clean pair error).
283#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
284#[serde(deny_unknown_fields)]
285pub struct PairParams {
286 #[serde(default)]
287 pub invite_line: String,
288}
289
290/// Params of [`Request::PeerRemove`]: the nickname to unpair.
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292#[serde(deny_unknown_fields)]
293pub struct PeerRemoveParams {
294 pub nickname: String,
295}
296
297/// Params of [`Request::PeerRename`]: the contact to rename — every device sharing `user_id`
298/// when given, else the single provisional `nickname` entry — and the new nickname `to`.
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
300#[serde(deny_unknown_fields)]
301pub struct PeerRenameParams {
302 #[serde(default)]
303 pub user_id: Option<String>,
304 #[serde(default)]
305 pub nickname: Option<String>,
306 pub to: String,
307}
308
309/// Params of [`Request::PeerAdd`] (reserved/internal — see the variant): a raw `endpoint_id`
310/// (iroh base32) plus the nickname and service allow list to install it under.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312#[serde(deny_unknown_fields)]
313pub struct PeerAddParams {
314 pub nickname: String,
315 pub endpoint_id: String,
316 #[serde(default)]
317 pub allow: Vec<String>,
318}
319
320/// Params of [`Request::OpenSession`]: the `peer/service` target to dial. Both fields are
321/// defaultable — an empty target simply fails the dial (a clean `-32055` error).
322#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
323#[serde(deny_unknown_fields)]
324pub struct OpenSessionParams {
325 #[serde(default)]
326 pub peer: String,
327 #[serde(default)]
328 pub service: String,
329}
330
331/// Params of [`Request::RosterInstall`]: the LOCAL roster file `path`, plus the org-root pin
332/// on FIRST install (`b64u:`; omit once pinned — config carries it).
333#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
334#[serde(deny_unknown_fields)]
335pub struct RosterInstallParams {
336 pub path: String,
337 #[serde(default, skip_serializing_if = "Option::is_none")]
338 pub org_root_pk: Option<String>,
339}
340
341/// Params of [`Request::OrgJoin`]: the `[identity]` pin. `user_key` is a LOCAL path — the key
342/// never crosses the API.
343#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
344#[serde(deny_unknown_fields)]
345pub struct OrgJoinParams {
346 pub org_id: String,
347 pub org_root_pk: String,
348 pub user_id: String,
349 pub user_key: String,
350}
351
352/// Params of [`Request::SetAppMetadata`]: this node's opaque app-metadata blob (#39). The
353/// daemon NEVER interprets it — the embedder structures its own bytes (a version string,
354/// small JSON, …). Capped at 256 bytes; `""` clears it. Roster-mode only (it rides the
355/// signed presence heartbeat); a pure-pairing daemon accepts + stores it but never gossips it.
356#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(deny_unknown_fields)]
358pub struct SetAppMetadataParams {
359 pub metadata: String,
360}
361
362/// Params of [`Request::PeerServices`] (#52): the peer to query — a nickname, an `eid:` device
363/// principal, or a `b64u:` user_id.
364#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
365#[serde(deny_unknown_fields)]
366pub struct PeerServicesParams {
367 pub peer: String,
368}
369
370/// Result of [`Request::PeerServices`] (#52): the services the queried peer CURRENTLY grants the
371/// caller — computed authoritatively on the peer (which owns the truth), always current, only
372/// the caller's own admitted services (never the peer's full registry).
373#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
374pub struct PeerServicesResult {
375 pub services: Vec<String>,
376}
377
378/// Params of [`Request::UnregisterService`] (#50): the persistent (or ephemeral) service name
379/// to remove — the deregistration mirror of `register_service`.
380#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
381#[serde(deny_unknown_fields)]
382pub struct UnregisterServiceParams {
383 pub name: String,
384}
385
386/// Params of [`Request::ServiceAllowGrant`] / [`Request::ServiceAllowRevoke`] (#44): toggle a
387/// single stable `principal` (`b64u:`/`eid:`) on a single `service`'s allow list, WITHOUT
388/// unpairing. The per-peer "sharing" switch primitive the embedder drives.
389#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
390#[serde(deny_unknown_fields)]
391pub struct ServiceAllowParams {
392 pub service: String,
393 pub principal: String,
394}
395
396/// Params of [`Request::SetNickname`]: this node's new self-nickname (#37). Display-only
397/// semantics: it names this node in FUTURE invites/presentations; peers keep the nickname
398/// they stored at pairing time until a re-invite.
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(deny_unknown_fields)]
401pub struct SetNicknameParams {
402 pub nickname: String,
403}
404
405/// Params of [`Request::SetRosterUrl`]: the HTTPS roster URL to pin.
406#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
407#[serde(deny_unknown_fields)]
408pub struct SetRosterUrlParams {
409 pub url: String,
410}
411
412/// Params of [`Request::SetRelays`] (#53): the node's desired CUSTOM relay set. Declarative —
413/// "make the custom relay set exactly this" — applied as a live insert/remove diff against the
414/// running endpoint (iroh 1.0.3 `Endpoint::insert_relay`/`remove_relay`) when the node is already
415/// in `relay_mode = "custom"`, then persisted to `[network]`. Each entry must parse as an iroh
416/// `RelayUrl`; an empty list is rejected (custom mode requires ≥1 relay — fully disabling relays
417/// is a `relay_mode = "disabled"` restart, not this verb). Switching a node that is currently
418/// `default`/`disabled` onto custom persists the config but needs a restart to take effect (iroh
419/// cannot live-transition the relay MODE) — signalled by [`SetRelaysResult::restart_required`].
420#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
421#[serde(deny_unknown_fields)]
422pub struct SetRelaysParams {
423 pub relay_urls: Vec<String>,
424}
425
426/// Result of [`Request::SetRelays`] (#53).
427#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
428pub struct SetRelaysResult {
429 /// The persisted `relay_urls` differed from the prior config (a no-op edit → `false`).
430 pub changed: bool,
431 /// `true` iff the node's current `relay_mode` is not `custom`, so the new set was persisted
432 /// but NOT applied live — a node restart is required for it to take effect. `false` on the
433 /// live custom→custom path (already applied to the running endpoint).
434 pub restart_required: bool,
435}
436
437/// Params of [`Request::BlobPublish`]: the scope to publish into and the LOCAL file to add.
438#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
439#[serde(deny_unknown_fields)]
440pub struct BlobPublishParams {
441 pub scope: String,
442 pub path: String,
443}
444
445/// Params of [`Request::BlobGrant`]: the scope and the flat-namespace principal to grant it to.
446#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
447#[serde(deny_unknown_fields)]
448pub struct BlobGrantParams {
449 pub scope: String,
450 pub principal: String,
451}
452
453/// Params of [`Request::BlobRevoke`] (#62): the scope and the principals to withdraw from it.
454///
455/// SCOPED, unlike unpair hygiene: only the named scope's grants change. A principal that also holds
456/// grants on other scopes keeps them — withdrawing access to one thing must not silently withdraw
457/// access to everything else.
458#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
459#[serde(deny_unknown_fields)]
460pub struct BlobRevokeParams {
461 pub scope: String,
462 pub principals: Vec<String>,
463}
464
465/// Params of [`Request::BlobUnpublish`] (#62): the scope and the blake3 hex to remove from it.
466///
467/// Removes REACHABILITY, not bytes. The scope gate requires a hash to be listed in some scope, so
468/// this takes effect immediately for authorization — but the bytes stay in the local store, and
469/// there is no reclaim verb yet. Do not surface this to a user as deletion.
470#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
471#[serde(deny_unknown_fields)]
472pub struct BlobUnpublishParams {
473 pub scope: String,
474 pub hash: String,
475}
476
477/// Params of [`Request::BlobRepublish`] (#83): the scope and the blake3 hex to add to it.
478///
479/// The blob must already be held COMPLETE by this daemon — republish makes a fetched blob servable
480/// FROM this node, it does not fetch. A hash that is absent, or only partially present from an
481/// interrupted fetch, is refused with [`ERR_NO_SUCH_BLOB`]: advertising bytes we cannot serve would
482/// turn the original publisher going offline into a hang at every fetcher.
483///
484/// It grants NOBODY. The republisher names a scope they already control; inheriting the original
485/// publisher's grants would be a silent authorization transfer. Share with `blob_grant`.
486#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(deny_unknown_fields)]
488pub struct BlobRepublishParams {
489 pub scope: String,
490 pub hash: String,
491}
492
493/// Params of [`Request::BlobFetch`]: the `mcpmesh/blob/1` ticket and the LOCAL export path.
494#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
495#[serde(deny_unknown_fields)]
496pub struct BlobFetchParams {
497 pub ticket: String,
498 pub dest_path: String,
499}
500
501/// Control-API requests. Serialized as `{ "method": "...", "params": {...} }`
502/// (JSON-RPC-shaped; the id/jsonrpc envelope is added by the transport layer).
503///
504/// Each param-carrying variant wraps its named `*Params` struct — the ONE wire truth for that
505/// method's params, shared by clients (which serialize whole `Request`s) and the daemon (which
506/// deserializes `params` into the same struct after its method-string dispatch). Adjacent
507/// tagging serializes a newtype variant's content as the struct's fields, so the wire shape is
508/// identical to inline variant bodies.
509///
510/// **Servers dispatch on the `method` string and deserialize `params` per-method** — tolerating
511/// omitted / null / empty-object params for parameterless methods — rather than deserializing a
512/// whole message into `Request` (adjacent tagging rejects `params:{}` for unit variants).
513/// This keeps the wire tolerant for third-party clients (the versioned, additive-only surface).
514/// Use [`method_of`] to extract the tag, then match + deserialize `params` per-method.
515#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
516#[serde(tag = "method", content = "params", rename_all = "snake_case")]
517pub enum Request {
518 /// Register/update a `[services.*]` entry idempotently.
519 RegisterService(RegisterServiceParams),
520 Status,
521 /// Mint a one-time pairing invite granting `services`. The daemon
522 /// answers an [`InviteResult`] carrying the copyable `mcpmesh-invite:` line. Tag
523 /// `"invite"` (snake_case). `method_of` needs no per-variant arm — it reads the
524 /// `method` string generically; the tag comes from `rename_all`.
525 Invite(InviteParams),
526 /// Redeem a pairing invite. The daemon dials the inviter named by
527 /// `invite_line` on `mcpmesh/pair/1`, proves the secret, writes the mutual
528 /// (dial-back) `PeerEntry`, and answers a [`PairResult`]. Tag `"pair"`
529 /// (snake_case); `method_of` reads the `method` string generically.
530 ///
531 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
532 Pair(PairParams),
533 /// Remove a paired peer by nickname (`mcpmesh pair --remove`). The daemon drops the
534 /// peer's `PeerEntry` (identity) AND revokes its access by stripping its stable principals from every
535 /// `[services.*].allow` (authorization) — the inverse of the pairing grant. Idempotent: a
536 /// nickname with no entry / no allow membership is a clean no-op. Live in-flight sessions are
537 /// NOT severed here: existing sessions run to completion; the peer only loses the
538 /// ability to establish NEW authorized sessions. Tag `"peer_remove"` (snake_case);
539 /// `method_of` reads the `method` string generically (no per-variant arm).
540 ///
541 /// `PeerEntry` — the durable allowlist row — lives in the daemon crate.
542 PeerRemove(PeerRemoveParams),
543 /// Rename a contact's nickname (nickname) authoritatively. Renames the
544 /// PERSON — every `PeerEntry` sharing `user_id` when given (one op for all their devices), else the
545 /// single `nickname` entry (a provisional, no-`user_id` contact) — to `to`, AND rewrites the old
546 /// nickname → `to` in every `[services.*].allow` so grants follow the rename. Refuses (error frame)
547 /// when `to` is empty or already names/grants a DIFFERENT identity — the same collision guard the
548 /// pairing rendezvous uses, so a rename can't inherit another peer's access. Tag `"peer_rename"`;
549 /// host-privileged like the other pair ops.
550 PeerRename(PeerRenameParams),
551 /// RESERVED / INTERNAL (`docs/local-protocol.md` "Reserved / internal methods"): install a
552 /// peer directly from a raw `endpoint_id` — the trust-population stand-in for pairing behind
553 /// `mcpmesh internal peer add`. A deliberate, documented exception to the surface discipline
554 /// (raw endpoint identifiers otherwise never cross this socket); NOT part of the stable
555 /// vocabulary — do not build on it. Tag `"peer_add"`.
556 PeerAdd(PeerAddParams),
557 /// Open a mesh session to `peer/service`; the daemon dials and pipes.
558 /// Distinct from the proxy's job: this returns a session the client streams.
559 /// Named `open_session` rather than `connect` to avoid colliding
560 /// with the `connect` porcelain.
561 OpenSession(OpenSessionParams),
562 /// Install a signed roster from a local file (the manual `internal roster install` path).
563 /// `path` is a LOCAL file the same-uid daemon reads (the daemon runs as the caller's own
564 /// uid, so passing a path rather than the bytes crosses no trust boundary). `org_root_pk`
565 /// pins the org root on FIRST install (`b64u:`); omit it
566 /// once pinned (config carries it). Tag `"roster_install"`.
567 RosterInstall(RosterInstallParams),
568 /// Pin the org root on a JOINER — WITHOUT a roster (the joiner has none yet; its poll loop
569 /// fetches the first one). Records `[identity]` org_id / org_root_pk / user_id / user_key.
570 /// `user_key` is a LOCAL path
571 /// (the key never crosses the API). Tag `"org_join"`.
572 OrgJoin(OrgJoinParams),
573 /// Pin the HTTPS roster URL (`[roster].url`) in config. Written by `org create
574 /// --roster-url` (the operator keeps it current) AND by `join` when the org invite carries one —
575 /// so the joiner's poll loop bootstraps its FIRST roster. The daemon writes it under
576 /// `reload_lock` (single-writer), then the poll loop picks it up on the next daemon start. Tag
577 /// `"set_roster_url"`.
578 SetRosterUrl(SetRosterUrlParams),
579 /// Rename this node LIVE (#37): validate + upsert `[identity].nickname` through the
580 /// daemon's own serialized config-write path (no lost-update window against a
581 /// concurrent grant/registration) and update the in-memory name future invites
582 /// present — no restart. Ack result. Tag `"set_nickname"` (snake_case).
583 SetNickname(SetNicknameParams),
584 /// Set this node's opaque app-metadata blob (#39): validated (≤256B) and folded, signed,
585 /// into each outgoing presence heartbeat, so paired roster peers see it in their `status`
586 /// presence — no per-peer session. Ack result. Tag `"set_app_metadata"`. In-memory (lost
587 /// on restart; the embedder re-sets on startup).
588 SetAppMetadata(SetAppMetadataParams),
589 /// Set this node's CUSTOM relay set LIVE (#53): validate each URL as an iroh `RelayUrl`, diff
590 /// against the running endpoint's current custom relays and apply the delta via iroh 1.0.3
591 /// `Endpoint::insert_relay`/`remove_relay` (no endpoint rebuild, no dropped sessions), then
592 /// persist `[network] relay_mode="custom" relay_urls=[…]` under `reload_lock`. When the node
593 /// is currently `default`/`disabled`, the config is persisted but the live mode transition
594 /// isn't possible — [`SetRelaysResult::restart_required`] is `true`. Answers a
595 /// [`SetRelaysResult`]. Tag `"set_relays"`.
596 SetRelays(SetRelaysParams),
597 /// Grant a single stable principal access to a single service's allow (#44) — the per-peer
598 /// "sharing on" toggle, idempotent + serialized under the config lock. Ack result.
599 /// Remove a service registration (#50) — the deregistration mirror of `register_service`.
600 /// Removes the whole `[services.<name>]` entry (allow included) + any ephemeral one, then
601 /// hot-reloads. Idempotent. Ack result.
602 UnregisterService(UnregisterServiceParams),
603 /// Discover which services a paired peer CURRENTLY grants the caller (#52) — dials the peer
604 /// and returns the service names whose allow admits the caller's principal. Answers
605 /// [`PeerServicesResult`].
606 PeerServices(PeerServicesParams),
607 ServiceAllowGrant(ServiceAllowParams),
608 /// Revoke a single stable principal from a single service's allow (#44) — "sharing off"
609 /// WITHOUT unpairing (the peer's identity row is untouched; only NEW sessions are refused).
610 /// Idempotent. Ack result.
611 ServiceAllowRevoke(ServiceAllowParams),
612 /// Publish a LOCAL file INTO a scope: the daemon adds the bytes to its gated
613 /// app-blob store and records the hash in `scope`. `path` is a local file the same-uid daemon
614 /// reads. Answers a [`BlobPublishResult`] carrying the `mcpmesh/blob/1` ticket + hash.
615 /// Tag `"blob_publish"`.
616 BlobPublish(BlobPublishParams),
617 /// Grant a scope to a principal — any flat-namespace entry: a group name, a user_id, or a
618 /// nickname (the shared `principal_set` expansion). Tag
619 /// `"blob_grant"`.
620 BlobGrant(BlobGrantParams),
621 /// Tag `"blob_revoke"`: withdraw principals from ONE scope's grants (#62).
622 BlobRevoke(BlobRevokeParams),
623 /// Tag `"blob_unpublish"`: remove a hash from ONE scope (#62). Withdraws reachability, not
624 /// bytes.
625 BlobUnpublish(BlobUnpublishParams),
626 /// #83: make a blob this daemon already holds servable from HERE, in a scope it controls.
627 /// Answers a [`BlobPublishResult`] — same shape as `blob_publish`, so a client can treat the
628 /// two interchangeably after a fetch.
629 BlobRepublish(BlobRepublishParams),
630 /// List the daemon's blob scopes (name → hashes + grants). Tag `"blob_list"`.
631 BlobList(BlobListParams),
632 /// Fetch a `mcpmesh/blob/1` ticket THROUGH the daemon (BLAKE3-verified streaming) and export the
633 /// verified blob to `dest_path` (a local file the same-uid daemon writes). Answers a
634 /// [`BlobFetchResult`] with the verified hash + byte length. Tag `"blob_fetch"`.
635 BlobFetch(BlobFetchParams),
636 /// Summarize this node's LOCAL audit log into per-peer / per-service SESSION counts
637 /// (local-only — the daemon reads its OWN audit dir, nothing is transmitted). The host Mesh surface
638 /// renders these as "who serves me / whom I serve / session counts". Parameterless (like `Status`);
639 /// the server dispatches on the `method` string. Tag `"audit_summary"` (snake_case);
640 /// `method_of` reads the `method` string generically (no per-variant arm).
641 AuditSummary,
642 /// Open a live event stream (pairing liveness & health telemetry). Like `open_session`, the
643 /// connection STOPS being request/response after this call and becomes a one-way push stream
644 /// of `StreamFrame`s. Parameterless. Tag `"subscribe"`.
645 Subscribe,
646}
647
648/// Result of [`Request::OrgJoin`] — the pinned org id echoed back (surface-clean; the fingerprint is
649/// computed porcelain-side from the invite's org_root_pk). Additive-only.
650#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
651pub struct OrgJoinResult {
652 pub org_id: String,
653}
654
655/// Result of a [`Request::RosterInstall`] request (the manual install path): the installed roster's
656/// org id + serial (roster-status vocabulary the confirmation line is permitted to render) plus how
657/// many live sessions the install severed. Surface-clean: NO keys / EndpointIds / paths.
658///
659/// Additive-only: any future field MUST land as
660/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
661#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
662pub struct RosterInstallResult {
663 pub org_id: String,
664 pub serial: u64,
665 /// How many live sessions were severed, for the porcelain's confirmation line.
666 #[serde(default)]
667 pub severed: u32,
668}
669
670/// Result of [`Request::BlobPublish`]: the copyable `mcpmesh/blob/1` ticket + the blob's blake3 hash.
671/// A ticket/hash here is blob-reference vocabulary (NOT a transport-vocab leak — the same
672/// carve-out as the pairing invite line). Additive-only.
673#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
674pub struct BlobPublishResult {
675 pub ticket: String,
676 pub hash: String, // bare blake3 hex
677}
678
679/// One scope in a [`BlobScopeList`]: its name + the hashes it contains + the principals it
680/// grants. Flat vocabulary ONLY — no EndpointId/pubkey/ALPN. Additive-only.
681#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
682pub struct ScopeInfo {
683 pub name: String,
684 pub hashes: Vec<String>,
685 pub grants: Vec<String>,
686 /// Hashes deliberately WITHDRAWN from this scope (#107): `blob_unpublish` was called, and
687 /// `blob_republish` of these into THIS scope is refused with [`ERR_BLOB_WITHDRAWN`]. Cleared
688 /// only by a deliberate `blob_publish {scope, path}`. Additive — omitted when empty, so a
689 /// pre-`api_minor` 19 client sees exactly what it saw before.
690 #[serde(default, skip_serializing_if = "Vec::is_empty")]
691 pub withdrawn: Vec<String>,
692 /// Size of `hashes` — always present, even when `counts_only` empties the vector (#84b).
693 #[serde(default)]
694 pub hash_count: usize,
695 /// Size of `grants`.
696 #[serde(default)]
697 pub grant_count: usize,
698 /// Size of `withdrawn`.
699 #[serde(default)]
700 pub withdrawn_count: usize,
701}
702
703/// Params of [`Request::BlobList`] (#84b). ALL optional — `blob_list {}` still works, which
704/// matters because the verb took no params before `api_minor` 20.
705///
706/// A DEFAULT LIMIT applies when `limit` is absent. Deliberate: unpaged, `blob_list` renders every
707/// scope into one frame against the 16 MiB cap; past it the CLIENT rejects the frame as malformed.
708/// The control surface carries no strike bound, so the connection survives — but the caller gets an
709/// opaque failure with no way to page, which is unusable rather than merely large.
710#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
711#[serde(default, deny_unknown_fields)]
712pub struct BlobListParams {
713 /// EXACT scope name, never a prefix.
714 pub scope: Option<String>,
715 /// Only scopes containing this hash; the rendering you send is normalized first.
716 pub hash: Option<String>,
717 pub limit: Option<usize>,
718 pub offset: Option<usize>,
719 /// Omit `hashes`/`grants`/`withdrawn`, keep the counts.
720 pub counts_only: bool,
721}
722
723/// Result of [`Request::BlobList`]: the daemon's scopes. Additive-only.
724#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
725pub struct BlobScopeList {
726 pub scopes: Vec<ScopeInfo>,
727 /// Scopes matching the filter BEFORE `limit`/`offset` (#84b). Without this you cannot tell a
728 /// complete answer from a clipped one.
729 #[serde(default)]
730 pub total: usize,
731 /// True when more scopes matched than were returned. Page with `offset` to see the rest.
732 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
733 pub truncated: bool,
734}
735
736/// Result of [`Request::BlobFetch`]: the verified hash + byte length written to `dest_path`.
737/// Additive-only.
738#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
739pub struct BlobFetchResult {
740 pub hash: String,
741 pub bytes_len: u64,
742}
743
744/// Result of [`Request::AuditSummary`]: LOCAL per-peer / per-service session counts
745/// aggregated from this node's OWN audit log — NEVER transmitted (local-only). Surface-clean:
746/// peer names are nicknames / user_ids (NEVER EndpointIds), service names are the registered
747/// service names (NEVER transport vocabulary). A "session" is one `SessionOpen` record. `per_peer` /
748/// `per_service` are sorted ascending by name (deterministic). Tuples mirror kb's
749/// `InsightResponse::per_peer_contribution` — `["bob", 2]` on the wire.
750///
751/// Additive-only: any future field MUST land as
752/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
753#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
754pub struct AuditSummaryResult {
755 /// Sessions opened per peer (nickname). A session with no attributed peer is NOT counted here (no
756 /// peer to attribute) but IS in `total_sessions`.
757 pub per_peer: Vec<(String, u64)>,
758 /// Sessions opened per registered service name.
759 pub per_service: Vec<(String, u64)>,
760 /// Total sessions opened (every `SessionOpen` record, including peer-less ones).
761 #[serde(default)]
762 pub total_sessions: u64,
763}
764
765/// Result of an [`Request::Invite`] request: the copyable `mcpmesh-invite:` artifact
766/// (the ONE pairing artifact deliberately carved out of the
767/// transport-vocabulary blocklist, so this is NOT a transport-vocab leak) plus its
768/// absolute expiry in epoch seconds (≤ now + 24h).
769///
770/// `invite` returns BEFORE any redemption, so the SAS — which is derived from the redeemer's
771/// endpoint id, unknown until they redeem — cannot appear here. The inviter reads its side of
772/// the SAS from [`StatusResult::recent_pairings`] once a redemption completes (a `trust`/`pair`
773/// frame on the live [`StreamFrame`] stream signals that moment). See the "embedding the pairing
774/// ceremony" note in `docs/local-protocol.md` (#35).
775///
776/// Additive-only: any future field MUST land as `#[serde(default, skip_serializing_if = ...)]`
777/// so older payloads still deserialize.
778#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
779pub struct InviteResult {
780 /// The `mcpmesh-invite:<base32>` line, copied out-of-band to the redeemer.
781 pub invite_line: String,
782 /// When the invite expires (epoch seconds); the daemon burns it at redemption or expiry.
783 pub expires_at_epoch: u64,
784}
785
786/// Result of a [`Request::Pair`] request: the inviter's suggested nickname (the
787/// redeemer's local name for the new peer) plus the display-only short authentication
788/// code (SAS) — a few words the human reads aloud to a second channel to
789/// catch a whole-invite forgery / address-swap MITM. The SAS is a pairing-ceremony
790/// artifact (like the invite line), NOT a transport-vocabulary leak.
791///
792/// Additive-only: any future field MUST land as
793/// `#[serde(default, skip_serializing_if = ...)]` so older payloads still deserialize.
794#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
795pub struct PairResult {
796 /// The inviter's suggested nickname (from the invite) — the redeemer's local name for it.
797 pub peer_nickname: String,
798 /// The display-only short authentication code (e.g. `"tango-fig-42"`), shown on both
799 /// sides for the out-of-band human check. Never sent on the wire, never checked
800 /// programmatically.
801 pub sas_code: String,
802 /// The services this pairing granted the redeemer — each mountable as `<peer>/<service>`.
803 /// Populated from the invite (`invite.services`) by the redeemer-side `redeem_invite`, so
804 /// the porcelain can print the "You can mount: alice/notes" line without re-decoding the
805 /// invite. Additive: `#[serde(default, skip_serializing_if = ...)]` so a `PairResult`
806 /// minted by an older daemon (which omits `services`) still deserializes — to an empty list.
807 #[serde(default, skip_serializing_if = "Vec::is_empty")]
808 pub services: Vec<String>,
809 /// The opaque `app_label` the inviter attached at `invite` time (#31), echoed verbatim — or
810 /// absent if none was set. mcpmesh never interprets it; the embedder does. Additive.
811 #[serde(default, skip_serializing_if = "Option::is_none")]
812 pub app_label: Option<String>,
813 /// The inviter's proven self-sovereign `user_id` (`b64u:<user_pk>`), when it presented a
814 /// device→user binding at pairing (#30). This is the STABLE, portable identity the redeemer
815 /// can align with its own — and the same value it may later pass to `open_session` to dial
816 /// this peer by identity rather than by local nickname. `None` if the inviter presented no
817 /// binding (a legacy/keyless peer). Additive.
818 #[serde(default, skip_serializing_if = "Option::is_none")]
819 pub peer_user_id: Option<String>,
820}
821
822/// The event class of an [`AuditRecord`] (the four audit event classes). An additive discriminant on
823/// top of the base record schema: it removes no field and makes the JSONL self-describing so
824/// a consumer can filter by class without guessing from which optional fields are present.
825#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
826#[serde(rename_all = "snake_case")]
827pub enum AuditKind {
828 /// A mesh session opened (a backend was selected for an authenticated peer).
829 /// (A `session_open` with `status:"error"` is a synthesized FAILED-dial marker — no backend
830 /// was reached; it records an attempted-and-failed reach for the telemetry stream.)
831 SessionOpen,
832 /// A mesh session closed (the backend returned / the session tore down).
833 SessionClose,
834 /// One proxied MCP request line (method + tool NAME + args_hash). NEVER carries raw arguments.
835 Request,
836 /// A peer fetched a blob from this node's gated provider (peer + hash + allow/deny).
837 BlobFetch,
838 /// A trust mutation (pair, unpair, roster install/swap, revoke).
839 Trust,
840}
841
842/// One audit record — the union of the event classes, and the `record` payload of a
843/// [`StreamFrame::Event`]. ONE schema for the on-disk JSONL log and the live stream. Every field
844/// beyond `ts`/`kind` is optional and elided when absent (`skip_serializing_if`), so each class
845/// serializes to just its relevant keys (a session record has no `method`; a trust record has no
846/// `bytes_out`).
847///
848/// PRIVACY: the proxied-request record carries `method` + `tool` (NAME only) +
849/// `args_hash` (`"blake3:<hex>"`), and NEVER the raw arguments, the request/response content, or
850/// any tool-output bytes — only a `bytes_out` COUNT and a `status`.
851#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
852pub struct AuditRecord {
853 /// RFC3339 UTC with millisecond precision, e.g. `"2026-07-03T14:02:11.480Z"`. The `YYYY-MM`
854 /// prefix also selects the monthly file (the rotation boundary), so it is always present.
855 pub ts: String,
856 pub kind: AuditKind,
857 /// The gate-resolved authenticated peer (attributed by the endpoint_id-keyed trust gate). Absent on
858 /// local-only events with no remote peer (a manual roster install).
859 #[serde(skip_serializing_if = "Option::is_none")]
860 pub peer: Option<String>,
861 #[serde(skip_serializing_if = "Option::is_none")]
862 pub service: Option<String>,
863 #[serde(skip_serializing_if = "Option::is_none")]
864 pub method: Option<String>,
865 /// The tool NAME only (never its arguments or output) — e.g. `"read_file"` for a `tools/call`.
866 #[serde(skip_serializing_if = "Option::is_none")]
867 pub tool: Option<String>,
868 /// `"blake3:<hex>"` of the request arguments. The raw arguments are NEVER stored.
869 #[serde(skip_serializing_if = "Option::is_none")]
870 pub args_hash: Option<String>,
871 /// Byte COUNT of the response sent back to the peer — a count, never the content.
872 #[serde(skip_serializing_if = "Option::is_none")]
873 pub bytes_out: Option<u64>,
874 /// `"ok"` / `"error"` (proxied request) or `"ok"` / `"denied"` (blob fetch).
875 #[serde(skip_serializing_if = "Option::is_none")]
876 pub status: Option<String>,
877 #[serde(skip_serializing_if = "Option::is_none")]
878 pub latency_ms: Option<u64>,
879 /// Trust-event verb: `"pair"` / `"unpair"` / `"roster_install"` / `"revoke"` (kind == Trust).
880 #[serde(skip_serializing_if = "Option::is_none")]
881 pub event: Option<String>,
882 /// A reference, NEVER content: a blob hash (`BlobFetch`) or a trust-event target such as a
883 /// nickname or `org/serial` (`Trust`).
884 #[serde(skip_serializing_if = "Option::is_none")]
885 pub target: Option<String>,
886}
887
888impl AuditRecord {
889 fn base(ts: String, kind: AuditKind) -> Self {
890 Self {
891 ts,
892 kind,
893 peer: None,
894 service: None,
895 method: None,
896 tool: None,
897 args_hash: None,
898 bytes_out: None,
899 status: None,
900 latency_ms: None,
901 event: None,
902 target: None,
903 }
904 }
905
906 pub fn session_open(ts: String, peer: Option<String>, service: String) -> Self {
907 let mut r = Self::base(ts, AuditKind::SessionOpen);
908 r.peer = peer;
909 r.service = Some(service);
910 r
911 }
912
913 /// Set the record's `status` (`"ok"`/`"error"`/`"denied"`), returning `self` for chaining.
914 /// Marks a synthesized failure record — e.g. the `session_open` for a FAILED dial, which
915 /// reaches no backend and so is never audited by the far side's session guard — without a
916 /// dedicated constructor. DRY: reuses the existing optional `status` field.
917 pub fn with_status(mut self, status: &str) -> Self {
918 self.status = Some(status.into());
919 self
920 }
921
922 pub fn session_close(ts: String, peer: Option<String>, service: String) -> Self {
923 let mut r = Self::base(ts, AuditKind::SessionClose);
924 r.peer = peer;
925 r.service = Some(service);
926 r
927 }
928
929 /// A completed (request→response correlated) proxied line: method + tool NAME + args_hash, plus
930 /// the response's `bytes_out` COUNT, `status`, and `latency_ms`. PRIVACY: `args_hash` is a digest;
931 /// no raw arguments, request/response content, or tool-output bytes are ever passed in.
932 #[allow(clippy::too_many_arguments)]
933 pub fn proxied_request(
934 ts: String,
935 peer: Option<String>,
936 service: String,
937 method: String,
938 tool: Option<String>,
939 args_hash: String,
940 bytes_out: u64,
941 status: String,
942 latency_ms: u64,
943 ) -> Self {
944 let mut r = Self::base(ts, AuditKind::Request);
945 r.peer = peer;
946 r.service = Some(service);
947 r.method = Some(method);
948 r.tool = tool;
949 r.args_hash = Some(args_hash);
950 r.bytes_out = Some(bytes_out);
951 r.status = Some(status);
952 r.latency_ms = Some(latency_ms);
953 r
954 }
955
956 /// A proxied NOTIFICATION line (no `id`, so no response correlates): method + tool + args_hash,
957 /// no `bytes_out`/`status`/`latency_ms`. The line is still recorded — every proxied request is audited.
958 pub fn proxied_notification(
959 ts: String,
960 peer: Option<String>,
961 service: String,
962 method: String,
963 tool: Option<String>,
964 args_hash: String,
965 ) -> Self {
966 let mut r = Self::base(ts, AuditKind::Request);
967 r.peer = peer;
968 r.service = Some(service);
969 r.method = Some(method);
970 r.tool = tool;
971 r.args_hash = Some(args_hash);
972 r
973 }
974
975 pub fn blob_fetch(ts: String, peer: Option<String>, hash: String, status: String) -> Self {
976 let mut r = Self::base(ts, AuditKind::BlobFetch);
977 r.peer = peer;
978 r.target = Some(hash);
979 r.status = Some(status);
980 r
981 }
982
983 pub fn trust(ts: String, event: String, target: Option<String>) -> Self {
984 let mut r = Self::base(ts, AuditKind::Trust);
985 r.event = Some(event);
986 r.target = target;
987 r
988 }
989}
990
991/// One live mesh session, in a [`StreamFrame::Snapshot`]. Surface-clean: `peer` is the
992/// user_id-or-nickname the audit records carry, never an endpoint-id. `opened_at` is epoch seconds.
993#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
994pub struct ActiveSession {
995 pub peer: String,
996 pub service: String,
997 pub opened_at: i64,
998}
999
1000/// One frame of the [`Request::Subscribe`] stream (pairing liveness & health telemetry). Tagged on
1001/// `type` (snake_case), so a frame is `{"type":"snapshot",...}` / `{"type":"event",...}` /
1002/// `{"type":"lagged",...}`. `Event.record` is the [`AuditRecord`] verbatim, so the stream and the
1003/// on-disk log carry ONE schema. The daemon serializes these; an embedding consumer deserializes
1004/// them (see `docs/local-protocol.md` "Live event stream").
1005/// **`#[non_exhaustive]`**: a future frame kind must not break a downstream `match`. Adding
1006/// `Reachability` in 0.13.0 DID break exhaustive matches — which is why that release is a MINOR,
1007/// per `RELEASING.md`'s pre-1.0 rule that breaking changes bump the minor. Consumers now write a
1008/// `_ =>` arm and later additions are additive for Rust as well as for JSON.
1009#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1010#[serde(tag = "type", rename_all = "snake_case")]
1011#[non_exhaustive]
1012pub enum StreamFrame {
1013 /// The FIRST frame: a point-in-time picture of the mesh (open sessions + paired-peer
1014 /// reachability) so a fresh subscriber renders immediately without replaying history.
1015 Snapshot {
1016 active_sessions: Vec<ActiveSession>,
1017 reachability: Vec<PeerReachability>,
1018 },
1019 /// A live audit event (session open/close, request, blob fetch, trust) — the tap on the hub.
1020 /// Boxed so this (much larger) variant does not bloat every frame; serde delegates through the
1021 /// `Box`, so the wire shape is the record's fields verbatim.
1022 Event { record: Box<AuditRecord> },
1023 /// A peer's reachability TRANSITIONED (#58): it became reachable, became unreachable, or was
1024 /// probed for the first time. Pushed so an embedder does not have to poll `status` for a live
1025 /// online/offline indicator — and so work queued for an unreachable peer can flush the moment
1026 /// it returns, rather than on the next poll tick.
1027 ///
1028 /// Emitted on a change of `reachable` **or of `path`**. A refresh with the same verdict AND the
1029 /// same path emits nothing, so a peer that stays up does not produce a frame per TTL refresh;
1030 /// `rtt_ms`/`meta`/`services` drift is advisory detail and is not a transition. `age_secs` is
1031 /// `0` — the observation just completed.
1032 ///
1033 /// **Do not treat this as an up/down toggle.** It carried that meaning through 0.18, and this
1034 /// doc said "on a CHANGE of `reachable` only" until 1.22 — which stopped being true in 0.19.0
1035 /// (#92 item 1), when `path` joined the transition rule. A consumer that assumed same-verdict
1036 /// frames were impossible was reading a stale guarantee.
1037 ///
1038 /// Two producers, as of API 1.22:
1039 ///
1040 /// - a **probe** completing (`status`/`subscribe` refreshing a stale entry), which carries a
1041 /// measured `rtt_ms`; and
1042 /// - a **live session** whose selected path changed under it (#92 item 2), which carries
1043 /// `rtt_ms: None` on a first observation — no round trip was measured and none is invented.
1044 ///
1045 /// The second producer is why `path` is trustworthy for a long-lived session: a session that
1046 /// degrades Direct→Relay mid-call now says so when it happens, rather than staying silently
1047 /// mislabelled until something probes. `path` is a truth claim about where user data went, so
1048 /// `Unknown` means "we do not know" and must never be rendered as private.
1049 Reachability { peer: PeerReachability },
1050 /// The subscriber fell `dropped` records behind the broadcast ring; the stream continues (a
1051 /// fresh reconnect would re-`Snapshot`). Never drops the subscriber — lag is reported, never fatal.
1052 Lagged { dropped: u64 },
1053}
1054
1055/// Extract the `method` tag from a raw request value without deserializing the whole
1056/// message. The daemon's dispatcher uses this: match on the method string, then deserialize
1057/// `params` per-method — which tolerates omitted / null / `{}` params for parameterless
1058/// methods (adjacent tagging rejects `params:{}` on unit variants).
1059pub fn method_of(v: &serde_json::Value) -> Option<&str> {
1060 v.get("method").and_then(serde_json::Value::as_str)
1061}
1062
1063/// How a service is answered. Mirrors the config `[services.*]` *kinds*;
1064/// Config→BackendSpec is a hand-written match, not a serde passthrough.
1065#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1066#[serde(rename_all = "snake_case")]
1067pub enum BackendSpec {
1068 Run {
1069 cmd: Vec<String>,
1070 /// Per-service environment variables (#51) for the spawned child. Overlaid on the
1071 /// daemon's inherited env; the injected `MCPMESH_PEER_*` identity vars ALWAYS win over
1072 /// these (identity is not spoofable by a service definition). Default empty.
1073 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1074 env: BTreeMap<String, String>,
1075 /// Working directory to spawn the child in (#51). Default: inherit the daemon's cwd.
1076 #[serde(default, skip_serializing_if = "Option::is_none")]
1077 cwd: Option<String>,
1078 },
1079 Socket {
1080 path: String,
1081 },
1082}
1083
1084/// Control-API error code: the named service exists in neither `config.toml` nor the ephemeral
1085/// registry (#55). Distinct from the generic `-32000` so a caller can BRANCH on "no such service"
1086/// instead of parsing a message — `service_allow_grant`/`service_allow_revoke` previously answered
1087/// `{}` (success) for an unknown name, which silently included every ephemeral service.
1088pub const ERR_NO_SUCH_SERVICE: i64 = -32040;
1089/// The named blob is not held COMPLETE by this daemon (#83, `blob_republish`). Distinct from
1090/// [`ERR_NO_SUCH_SERVICE`] because the remedy differs: fetch the blob first.
1091pub const ERR_NO_SUCH_BLOB: i64 = -32041;
1092/// The blob was deliberately withdrawn from this scope (#107). Distinct from
1093/// [`ERR_NO_SUCH_BLOB`]: that means "fetch it first", this means "someone un-shared this on
1094/// purpose — `blob_publish` from the file if the re-share is intended".
1095pub const ERR_BLOB_WITHDRAWN: i64 = -32042;
1096
1097pub const API_NAME: &str = "mcpmesh-local/1";
1098/// The protocol-compatibility version as `"MAJOR.MINOR"`, distinct from the crate/stack version.
1099///
1100/// - **MAJOR** matches the `/N` in [`API_NAME`] and changes only on a breaking wire change (the
1101/// transport already rejects a mismatched `api`, so an equality check on that is redundant).
1102/// - **MINOR** ([`API_MINOR`]) increments on a surface change within a major — additive fields, new
1103/// methods, or a strictness change like params validation — bumped in the same change that makes
1104/// it. A client can guard with `api_minor >= N` for a feature it needs, or refuse a daemon older
1105/// than a minor it requires. It never resets except on a MAJOR bump.
1106///
1107/// It also bumps for a change to what a field MEANS with no change to its shape — six of the
1108/// twenty-four have, see [`API_MINOR`]'s history. "Every surface change" is what this line used
1109/// to claim, and it was wrong in both directions: minor 9's entry records surface changes that
1110/// shipped WITHOUT a bump, and six bumps changed no type at all. Read the history, not the rule.
1111pub const API_VERSION: &str = "1.24";
1112/// The integer MINOR of [`API_VERSION`] — see there. Bumped from 0 to 1 when params validation
1113/// became strict (#34); to 2 with the `set_nickname` verb + `StatusResult.self_nickname` (#37);
1114/// to 3 when `allow`/grant strings became STABLE principals — `b64u:`/`eid:`/roster names,
1115/// never nicknames (#38); to 4 with the `set_app_metadata` verb + `PresencePeer.meta` (#39);
1116/// to 5 with `PeerReachability.meta` — pairing-mode app metadata on the probe pong (#40);
1117/// to 6 with `PeerInfo.principal` — the peer's eid: device principal on `status` (#41);
1118/// to 7 with `PeerReachability.principal` — the same on reachability rows (#42); to 8 with the
1119/// `service_allow_grant`/`service_allow_revoke` per-peer access verbs (#44); to 9 covering the
1120/// `unregister_service` (#50) / `peer_services` (#52) / Run `env`+`cwd` (#51) surface that shipped
1121/// in 0.10.1 without a bump, PLUS the `set_relays` live relay-set verb (#53); to 10 when
1122/// `service_allow_revoke`/`peer_remove` became IMMEDIATE — no verb shape changed, but their
1123/// observable contract did: a revoked principal's next session is refused even on a connection it
1124/// already holds, and its live connections are severed. Previously both waited for the peer to
1125/// disconnect on its own, which is unbounded (#54). A consumer can guard on
1126/// `api_minor >= 10` before telling a user that revocation has taken effect; to 11 when
1127/// `service_allow_grant`/`service_allow_revoke` gained EPHEMERAL-service support and became strict
1128/// about an unknown service name — a name in neither the config nor the ephemeral registry now
1129/// answers [`ERR_NO_SUCH_SERVICE`] instead of a silent `{}` (#55, #69); to 12 with the pushed
1130/// [`StreamFrame::Reachability`] liveness transition frame (#58); to 13 with
1131/// [`PeerReachability::path`] — direct-vs-relay attribution on every reachability row (#64); to 14
1132/// with the `run`-backend `MCPMESH_PEER_EID` identity var — the caller's stable device principal,
1133/// unconditionally present, so a `run` server can scope per caller without keying on a nickname
1134/// (#60); to 15 with the `blob_revoke` / `blob_unpublish` verbs — per-scope withdrawal of a grant
1135/// and of a published hash, so un-sharing a file no longer requires unpairing the person (#62); to
1136/// 16 when the app-blob provider became available in PAIRING mode — the blob verbs previously
1137/// errored on any daemon without an org root key, though their scope gate never needed one (#61);
1138/// to 17 when the service answer began coming from the LIVE registry rather than config + overlay,
1139/// so a grant the accept path would refuse is no longer advertised. Three surfaces share that
1140/// resolver and all changed together: `status`'s `services[].allow`, `peer_services`' name list,
1141/// and the `mcpmesh/ping/1` probe's `services`. No wire shape changed, only the source of truth —
1142/// exactly the class of change a downstream cannot see in a type diff (#100); to 18 with `blob_republish`, so a fetched blob can
1143/// be re-served and every recipient becomes a source (#83); to 19 with durable blob revocation — an
1144/// unpublish now survives a later republish via a per-scope withdrawal set, and
1145/// [`ERR_BLOB_WITHDRAWN`] distinguishes "deliberately withdrawn" from "never had it" (#107); to 20
1146/// with `blob_list` filters + paging AND a DEFAULT limit of 256 scopes (the clamp is 4096) — a
1147/// daemon with more scopes than that previously answered with
1148/// everything, and past the 16 MiB frame cap the CLIENT rejected the response as malformed, leaving
1149/// the caller an opaque failure with no way to page. The connection survived: the control surface
1150/// carries no strike bound. This is a behaviour change for existing callers, detectable via the new
1151/// `total`/`truncated` (#84b); to 21 when a
1152/// PATH change became a reachability transition — [`StreamFrame::Reachability`] stopped being an
1153/// up/down toggle and same-verdict frames became possible (#92); to 22 with a SECOND producer for
1154/// that frame: a live per-session watcher that pushes when a session's selected path changes,
1155/// rather than waiting for a probe, at a cadence probes never had (#92); to 23 when
1156/// [`PeerReachability::rtt_ms`] stopped including the path-settle window — a relayed peer could
1157/// previously never report under 600ms, so "relayed AND fast" was unreachable by construction
1158/// (#123); to 24 when `reachable` stopped sharing a deadline with path classification — a relayed
1159/// peer whose pong arrived after ~2.4s was reported OFFLINE while it was answering (#128).
1160///
1161/// **Not every semantic change gets a minor, and that is the gap to watch (#122).** A minor marks a
1162/// change to this *surface*. A change to behaviour BEHIND the surface — same fields, same shapes,
1163/// different meaning — may not bump it, and is invisible to a type diff. 17 and 24 above happen to
1164/// be that class and did bump; do not infer from them that every such change will. When bumping
1165/// several minors at once, read this block end to end AND the release notes, not the diff.
1166///
1167/// That class is bigger than it looks: **10, 17, 21, 22, 23 and 24 all shipped with no change to
1168/// any type in this file** — they moved meaning, not shape. Six of the twenty-four. A downstream
1169/// that diffs types across a multi-minor bump sees nothing for any of them.
1170pub const API_MINOR: u32 = 24;
1171
1172#[cfg(test)]
1173mod tests {
1174 use super::*;
1175
1176 /// #64: the path field's wire shape, and its ADDITIVE default. A row from an older daemon has
1177 /// no `path` key at all and must land on `Unknown` — never on `Direct`, which would invent a
1178 /// privacy guarantee that daemon never made.
1179 #[test]
1180 fn peer_path_tags_and_defaults_to_unknown() {
1181 let tagged = |p: PeerPath| serde_json::to_value(p).unwrap();
1182 assert_eq!(tagged(PeerPath::Direct)["kind"], "direct");
1183 assert_eq!(tagged(PeerPath::Unknown)["kind"], "unknown");
1184 let relay = tagged(PeerPath::Relay {
1185 url: Some("https://relay.example/".into()),
1186 });
1187 assert_eq!(relay["kind"], "relay");
1188 assert_eq!(relay["url"], "https://relay.example/");
1189 // A relay whose URL we do not know still tags as relay, with the key elided.
1190 let bare = tagged(PeerPath::Relay { url: None });
1191 assert_eq!(bare["kind"], "relay");
1192 assert!(bare.get("url").is_none(), "elided, not null: {bare}");
1193
1194 // #64 review: a path kind from a NEWER daemon must degrade to Unknown, not fail the whole
1195 // row. Without `#[serde(other)]` an unknown `kind` errors out of
1196 // `PeerReachability` entirely, so one new variant would break every `status` read an
1197 // older pinned client does.
1198 let future: PeerPath =
1199 serde_json::from_value(serde_json::json!({"kind": "quantum", "id": "x"})).unwrap();
1200 assert_eq!(future, PeerPath::Unknown);
1201 let row: PeerReachability = serde_json::from_value(serde_json::json!({
1202 "name": "bob", "reachable": true, "path": {"kind": "quantum"}
1203 }))
1204 .expect("an unknown path kind must not fail the whole row");
1205 assert_eq!(row.path, PeerPath::Unknown);
1206 assert!(row.reachable, "the rest of the row survives");
1207
1208 // A pre-#64 row: no `path` key.
1209 let old = serde_json::json!({"name": "bob", "reachable": true});
1210 let parsed: PeerReachability = serde_json::from_value(old).unwrap();
1211 assert_eq!(
1212 parsed.path,
1213 PeerPath::Unknown,
1214 "an older daemon's row must never imply a direct path"
1215 );
1216 }
1217
1218 /// #58: the pushed liveness frame tags as `{"type":"reachability","peer":{…}}` and carries a
1219 /// whole `PeerReachability` row — the SAME shape the opening snapshot's list holds, so a
1220 /// consumer projects both through one code path.
1221 #[test]
1222 fn reachability_frame_tags_and_round_trips() {
1223 let frame = StreamFrame::Reachability {
1224 peer: PeerReachability {
1225 name: "bob".into(),
1226 reachable: true,
1227 rtt_ms: Some(12),
1228 age_secs: Some(0),
1229 meta: String::new(),
1230 principal: Some("eid:beef".into()),
1231 path: Default::default(),
1232 },
1233 };
1234 let v = serde_json::to_value(&frame).unwrap();
1235 assert_eq!(v["type"], "reachability");
1236 assert_eq!(v["peer"]["name"], "bob");
1237 assert_eq!(v["peer"]["reachable"], true);
1238 assert_eq!(
1239 v["peer"]["age_secs"], 0,
1240 "a transition frame is fresh by construction: {v}"
1241 );
1242 let back: StreamFrame = serde_json::from_value(v).unwrap();
1243 assert_eq!(back, frame);
1244 }
1245
1246 #[test]
1247 fn peer_reachability_serde_is_additive() {
1248 let r = PeerReachability {
1249 name: "bob".into(),
1250 reachable: true,
1251 rtt_ms: Some(42),
1252 age_secs: Some(3),
1253 meta: String::new(),
1254 principal: None,
1255 path: Default::default(),
1256 };
1257 let v = serde_json::to_value(&r).unwrap();
1258 assert_eq!(v["name"], "bob");
1259 assert_eq!(v["reachable"], true);
1260 assert_eq!(v["rtt_ms"], 42);
1261 assert_eq!(v["age_secs"], 3);
1262 // Never-probed peer: optionals elided, not null.
1263 let unknown = PeerReachability {
1264 name: "carol".into(),
1265 reachable: false,
1266 rtt_ms: None,
1267 age_secs: None,
1268 meta: String::new(),
1269 principal: None,
1270 path: Default::default(),
1271 };
1272 let uv = serde_json::to_value(&unknown).unwrap();
1273 assert!(uv.get("rtt_ms").is_none() && uv.get("age_secs").is_none());
1274 // An older StatusResult (no reachability field) still deserializes.
1275 let old = serde_json::json!({"stack_version":"0.1.0","services":[],"peers":[]});
1276 let s: StatusResult = serde_json::from_value(old).unwrap();
1277 assert!(s.reachability.is_empty());
1278 }
1279
1280 #[test]
1281 fn subscribe_method_tag_resolves() {
1282 let req = serde_json::to_value(Request::Subscribe).unwrap();
1283 assert_eq!(method_of(&req), Some("subscribe"));
1284 }
1285
1286 // --- #34: params structs reject unknown fields (the `{service: "kb"}` silent-accept bug) ---
1287
1288 #[test]
1289 fn invite_params_reject_singular_service_typo() {
1290 // The reported bug: `{"service":"kb"}` (singular) used to deserialize to
1291 // InviteParams { services: [] } and mint a grants-nothing invite that looked
1292 // successful. With deny_unknown_fields the typo is a loud parse error instead.
1293 let err = serde_json::from_value::<InviteParams>(serde_json::json!({"service": "kb"}));
1294 assert!(
1295 err.is_err(),
1296 "an unknown `service` key must be rejected, not silently ignored"
1297 );
1298 // The correct plural shape still parses.
1299 let ok: InviteParams =
1300 serde_json::from_value(serde_json::json!({"services": ["kb"]})).unwrap();
1301 assert_eq!(ok.services, vec!["kb".to_string()]);
1302 }
1303
1304 #[test]
1305 fn open_session_params_reject_unknown_field() {
1306 let err = serde_json::from_value::<OpenSessionParams>(
1307 serde_json::json!({"peer": "a", "service": "b", "nonsense": 1}),
1308 );
1309 assert!(err.is_err(), "unknown params keys must be rejected");
1310 }
1311
1312 #[test]
1313 fn set_app_metadata_request_carries_the_method_tag() {
1314 let r = Request::SetAppMetadata(SetAppMetadataParams {
1315 metadata: "v=1.2.3".into(),
1316 });
1317 let v = serde_json::to_value(&r).unwrap();
1318 assert_eq!(v["method"], "set_app_metadata");
1319 assert_eq!(v["params"]["metadata"], "v=1.2.3");
1320 assert_eq!(method_of(&v), Some("set_app_metadata"));
1321 }
1322
1323 #[test]
1324 fn set_app_metadata_params_reject_unknown_field() {
1325 let err = serde_json::from_value::<SetAppMetadataParams>(
1326 serde_json::json!({"metadata": "x", "nonsense": 1}),
1327 );
1328 assert!(err.is_err(), "unknown params keys must be rejected");
1329 }
1330
1331 /// `PresencePeer.meta` is additive — an older payload (no meta) still deserializes, and an
1332 /// empty meta does not serialize.
1333 #[test]
1334 fn peer_info_principal_is_additive() {
1335 // An older payload (no principal) still deserializes; empty does not serialize.
1336 let old = serde_json::json!({"name": "bob", "services": ["notes"]});
1337 let p: PeerInfo = serde_json::from_value(old).unwrap();
1338 assert_eq!(p.principal, None);
1339 assert!(serde_json::to_value(&p).unwrap().get("principal").is_none());
1340 // A bound peer carries BOTH the person user_id AND the device principal (#41).
1341 let full = PeerInfo {
1342 name: "bob".into(),
1343 services: vec!["notes".into()],
1344 user_id: Some("b64u:BOB".into()),
1345 principal: Some("eid:0707".into()),
1346 };
1347 let back: PeerInfo = serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1348 assert_eq!(back.user_id.as_deref(), Some("b64u:BOB"));
1349 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1350 }
1351
1352 #[test]
1353 fn peer_reachability_principal_is_additive() {
1354 // Older payload (no principal) still deserializes; empty does not serialize; a set
1355 // value round-trips alongside the #40 meta so an embedder joins on the principal.
1356 let old = serde_json::json!({"name": "bob", "reachable": true});
1357 let r: PeerReachability = serde_json::from_value(old).unwrap();
1358 assert_eq!(r.principal, None);
1359 assert!(serde_json::to_value(&r).unwrap().get("principal").is_none());
1360 let full = PeerReachability {
1361 name: "bob".into(),
1362 reachable: true,
1363 rtt_ms: Some(12),
1364 age_secs: Some(3),
1365 meta: "v=1.2.3".into(),
1366 principal: Some("eid:0707".into()),
1367 path: Default::default(),
1368 };
1369 let back: PeerReachability =
1370 serde_json::from_value(serde_json::to_value(&full).unwrap()).unwrap();
1371 assert_eq!(back.principal.as_deref(), Some("eid:0707"));
1372 assert_eq!(back.meta, "v=1.2.3");
1373 }
1374
1375 #[test]
1376 fn peer_reachability_meta_is_additive() {
1377 // An older payload (no meta) still deserializes; an empty meta does not serialize.
1378 let old = serde_json::json!({"name": "bob", "reachable": true});
1379 let r: PeerReachability = serde_json::from_value(old).unwrap();
1380 assert_eq!(r.meta, "");
1381 assert!(serde_json::to_value(&r).unwrap().get("meta").is_none());
1382 // A set value round-trips.
1383 let with = PeerReachability {
1384 name: "bob".into(),
1385 reachable: true,
1386 rtt_ms: Some(12),
1387 age_secs: Some(3),
1388 meta: "v=1.2.3".into(),
1389 principal: None,
1390 path: Default::default(),
1391 };
1392 let back: PeerReachability =
1393 serde_json::from_value(serde_json::to_value(&with).unwrap()).unwrap();
1394 assert_eq!(back.meta, "v=1.2.3");
1395 }
1396
1397 #[test]
1398 fn presence_peer_meta_is_additive() {
1399 let old = serde_json::json!({
1400 "user_id": "b64u:A", "device_label": "laptop", "role": "primary", "online": true
1401 });
1402 let p: PresencePeer = serde_json::from_value(old).unwrap();
1403 assert_eq!(p.meta, "");
1404 assert!(serde_json::to_value(&p).unwrap().get("meta").is_none());
1405 }
1406
1407 #[test]
1408 fn set_nickname_request_carries_the_method_tag() {
1409 let r = Request::SetNickname(SetNicknameParams {
1410 nickname: "workbench".into(),
1411 });
1412 let v = serde_json::to_value(&r).unwrap();
1413 assert_eq!(v["method"], "set_nickname");
1414 assert_eq!(v["params"]["nickname"], "workbench");
1415 assert_eq!(method_of(&v), Some("set_nickname"));
1416 }
1417
1418 #[test]
1419 fn set_nickname_params_reject_unknown_field() {
1420 let err = serde_json::from_value::<SetNicknameParams>(
1421 serde_json::json!({"nickname": "x", "nonsense": 1}),
1422 );
1423 assert!(err.is_err(), "unknown params keys must be rejected");
1424 }
1425
1426 /// An OLDER daemon's status payload (no `self_nickname`) must still deserialize —
1427 /// the additive-only contract — and an empty name must not serialize at all.
1428 #[test]
1429 fn status_self_nickname_is_additive() {
1430 let old = serde_json::json!({
1431 "stack_version": "0.7.0", "services": [], "peers": []
1432 });
1433 let s: StatusResult = serde_json::from_value(old).unwrap();
1434 assert_eq!(s.self_nickname, "");
1435 let v = serde_json::to_value(&s).unwrap();
1436 assert!(v.get("self_nickname").is_none(), "empty name is skipped");
1437 }
1438
1439 #[test]
1440 fn api_minor_is_present_and_monotonic_from_hello() {
1441 // #34 part 2: a machine-comparable protocol-compat minor, distinct from the
1442 // crate/stack version, additive on the Hello frame.
1443 let h = Hello {
1444 api: API_NAME.into(),
1445 api_version: API_VERSION.into(),
1446 api_minor: API_MINOR,
1447 stack_version: "9.9.9".into(),
1448 };
1449 let v = serde_json::to_value(&h).unwrap();
1450 assert_eq!(v["api_minor"], API_MINOR);
1451 // An OLD Hello without api_minor still deserializes (additive contract).
1452 let old = serde_json::json!({
1453 "api": API_NAME, "api_version": "1.0", "stack_version": "0.4.0"
1454 });
1455 let back: Hello = serde_json::from_value(old).unwrap();
1456 assert_eq!(back.api_minor, 0, "absent api_minor defaults to 0");
1457 }
1458
1459 #[test]
1460 fn hello_result_roundtrips() {
1461 let h = Hello {
1462 api: "mcpmesh-local/1".into(),
1463 api_version: "1.0".into(),
1464 api_minor: 0,
1465 stack_version: "0.1.0".into(),
1466 };
1467 let v = serde_json::to_value(&h).unwrap();
1468 assert_eq!(v["api"], "mcpmesh-local/1");
1469 let back: Hello = serde_json::from_value(v).unwrap();
1470 assert_eq!(back, h);
1471 }
1472
1473 #[test]
1474 fn request_tagged_by_method() {
1475 let r = Request::Status;
1476 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "status");
1477 let r = Request::OpenSession(OpenSessionParams {
1478 peer: "alice".into(),
1479 service: "notes".into(),
1480 });
1481 let v = serde_json::to_value(&r).unwrap();
1482 assert_eq!(v["method"], "open_session");
1483 assert_eq!(v["params"]["peer"], "alice");
1484 }
1485
1486 #[test]
1487 fn parameterless_method_tolerates_params_forms() {
1488 // Omitted and null params deserialize straight into the unit variant.
1489 let omitted: Request =
1490 serde_json::from_value(serde_json::json!({"method": "status"})).unwrap();
1491 assert_eq!(omitted, Request::Status);
1492 let null: Request =
1493 serde_json::from_value(serde_json::json!({"method": "status", "params": null}))
1494 .unwrap();
1495 assert_eq!(null, Request::Status);
1496
1497 // Known limitation: adjacent tagging rejects `params:{}` for a unit variant, so
1498 // the server MUST dispatch on the method string rather than deserialize the whole
1499 // message into `Request`. This is the pattern the daemon's dispatcher uses.
1500 let empty = serde_json::json!({"method": "status", "params": {}});
1501 assert!(serde_json::from_value::<Request>(empty.clone()).is_err());
1502 match method_of(&empty) {
1503 Some("status") => {} // dispatcher resolves Status via the method string
1504 other => panic!("method_of failed to resolve status: {other:?}"),
1505 }
1506 }
1507
1508 #[test]
1509 fn backend_spec_roundtrips() {
1510 let run = BackendSpec::Run {
1511 cmd: vec!["notes-mcp".into(), "--stdio".into()],
1512 env: Default::default(),
1513 cwd: None,
1514 };
1515 let v = serde_json::to_value(&run).unwrap();
1516 assert_eq!(v["run"]["cmd"][0], "notes-mcp");
1517 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), run);
1518
1519 let sock = BackendSpec::Socket {
1520 path: "/run/notes.sock".into(),
1521 };
1522 let v = serde_json::to_value(&sock).unwrap();
1523 assert_eq!(v["socket"]["path"], "/run/notes.sock");
1524 assert_eq!(serde_json::from_value::<BackendSpec>(v).unwrap(), sock);
1525 }
1526
1527 #[test]
1528 fn register_service_wire_shape() {
1529 let r = Request::RegisterService(RegisterServiceParams {
1530 name: "notes".into(),
1531 backend: BackendSpec::Run {
1532 cmd: vec!["notes-mcp".into()],
1533 env: Default::default(),
1534 cwd: None,
1535 },
1536 allow: vec!["alice".into()],
1537 ephemeral: false,
1538 });
1539 let v = serde_json::to_value(&r).unwrap();
1540 assert_eq!(
1541 v,
1542 serde_json::json!({
1543 "method": "register_service",
1544 "params": {
1545 "name": "notes",
1546 "backend": {"run": {"cmd": ["notes-mcp"]}},
1547 "allow": ["alice"],
1548 }
1549 })
1550 );
1551 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1552 }
1553
1554 #[test]
1555 fn invite_request_and_result_roundtrip() {
1556 // Request::Invite → `{ "method": "invite", "params": { "services": [...] } }`.
1557 let r = Request::Invite(InviteParams {
1558 services: vec!["notes".into(), "kb".into()],
1559 app_label: None,
1560 });
1561 let v = serde_json::to_value(&r).unwrap();
1562 assert_eq!(v["method"], "invite");
1563 assert_eq!(v["params"]["services"][0], "notes");
1564 assert_eq!(v["params"]["services"][1], "kb");
1565 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1566 // method_of resolves the tag generically (no per-variant arm).
1567 assert_eq!(
1568 method_of(&serde_json::json!({"method": "invite", "params": {"services": []}})),
1569 Some("invite")
1570 );
1571
1572 // InviteResult carries the copyable line + expiry (surface #2 pairing artifact).
1573 let res = InviteResult {
1574 invite_line: "mcpmesh-invite:ABCDEF".into(),
1575 expires_at_epoch: 1_800_000_000,
1576 };
1577 let v = serde_json::to_value(&res).unwrap();
1578 assert_eq!(v["invite_line"], "mcpmesh-invite:ABCDEF");
1579 assert_eq!(v["expires_at_epoch"], 1_800_000_000u64);
1580 assert_eq!(serde_json::from_value::<InviteResult>(v).unwrap(), res);
1581 }
1582
1583 #[test]
1584 fn pair_request_and_result_roundtrip() {
1585 // Request::Pair → `{ "method": "pair", "params": { "invite_line": "..." } }`.
1586 let r = Request::Pair(PairParams {
1587 invite_line: "mcpmesh-invite:ABCDEF".into(),
1588 });
1589 let v = serde_json::to_value(&r).unwrap();
1590 assert_eq!(v["method"], "pair");
1591 assert_eq!(v["params"]["invite_line"], "mcpmesh-invite:ABCDEF");
1592 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1593 // method_of resolves the tag generically (no per-variant arm).
1594 assert_eq!(
1595 method_of(&serde_json::json!({"method": "pair", "params": {"invite_line": "x"}})),
1596 Some("pair")
1597 );
1598
1599 // PairResult carries the inviter's suggested nickname + the display-only SAS words +
1600 // the granted services (the porcelain renders each as `<peer>/<service>`).
1601 let res = PairResult {
1602 peer_nickname: "alice".into(),
1603 sas_code: "tango-fig-cabbage".into(),
1604 services: vec!["notes".into(), "kb".into()],
1605 app_label: None,
1606 peer_user_id: None,
1607 };
1608 let v = serde_json::to_value(&res).unwrap();
1609 assert_eq!(v["peer_nickname"], "alice");
1610 assert_eq!(v["sas_code"], "tango-fig-cabbage");
1611 assert_eq!(v["services"][0], "notes");
1612 assert_eq!(v["services"][1], "kb");
1613 assert_eq!(serde_json::from_value::<PairResult>(v).unwrap(), res);
1614
1615 // Additive-only: a PairResult minted by an older daemon (no `services` key) still
1616 // deserializes — the `#[serde(default)]` fills it with an empty list.
1617 let old_shape = serde_json::json!({
1618 "peer_nickname": "alice",
1619 "sas_code": "tango-fig-cabbage",
1620 });
1621 let back: PairResult = serde_json::from_value(old_shape).unwrap();
1622 assert_eq!(back.peer_nickname, "alice");
1623 assert!(back.services.is_empty());
1624 }
1625
1626 #[test]
1627 fn roster_install_request_and_result_roundtrip() {
1628 // Request::RosterInstall → `{ "method": "roster_install", "params": { "path": ...,
1629 // "org_root_pk": ... } }`. The optional pk is present on the first-install shape.
1630 let r = Request::RosterInstall(RosterInstallParams {
1631 path: "/tmp/roster.json".into(),
1632 org_root_pk: Some("b64u:AAAA".into()),
1633 });
1634 let v = serde_json::to_value(&r).unwrap();
1635 assert_eq!(v["method"], "roster_install");
1636 assert_eq!(v["params"]["path"], "/tmp/roster.json");
1637 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1638 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1639 // method_of resolves the tag generically (no per-variant arm).
1640 assert_eq!(
1641 method_of(&serde_json::json!({"method": "roster_install", "params": {"path": "/x"}})),
1642 Some("roster_install")
1643 );
1644
1645 // When the pk is omitted (a subsequent install using the pinned value), it is
1646 // `skip_serializing_if`-dropped from the wire and deserializes back to `None`.
1647 let omit = Request::RosterInstall(RosterInstallParams {
1648 path: "/tmp/roster.json".into(),
1649 org_root_pk: None,
1650 });
1651 let v = serde_json::to_value(&omit).unwrap();
1652 assert!(
1653 v["params"].get("org_root_pk").is_none(),
1654 "an omitted org_root_pk must not appear on the wire: {v}"
1655 );
1656 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), omit);
1657
1658 // RosterInstallResult carries org_id + serial + severed count (roster-status vocabulary).
1659 let res = RosterInstallResult {
1660 org_id: "acme".into(),
1661 serial: 42,
1662 severed: 1,
1663 };
1664 let v = serde_json::to_value(&res).unwrap();
1665 assert_eq!(v["org_id"], "acme");
1666 assert_eq!(v["serial"], 42u64);
1667 assert_eq!(v["severed"], 1u32);
1668 assert_eq!(
1669 serde_json::from_value::<RosterInstallResult>(v).unwrap(),
1670 res
1671 );
1672
1673 // Additive-only: a result minted by an older daemon (no `severed` key) still
1674 // deserializes — the `#[serde(default)]` fills it with 0.
1675 let old_shape = serde_json::json!({ "org_id": "acme", "serial": 7 });
1676 let back: RosterInstallResult = serde_json::from_value(old_shape).unwrap();
1677 assert_eq!(back.serial, 7);
1678 assert_eq!(back.severed, 0);
1679 }
1680
1681 #[test]
1682 fn org_join_request_and_result_roundtrip() {
1683 // Request::OrgJoin → `{ "method": "org_join", "params": { org_id, org_root_pk, user_id,
1684 // user_key } }`. `user_key` is a LOCAL path string (the key never crosses the API).
1685 let r = Request::OrgJoin(OrgJoinParams {
1686 org_id: "acme".into(),
1687 org_root_pk: "b64u:AAAA".into(),
1688 user_id: "alice".into(),
1689 user_key: "/home/alice/.config/mcpmesh/user.key".into(),
1690 });
1691 let v = serde_json::to_value(&r).unwrap();
1692 assert_eq!(v["method"], "org_join");
1693 assert_eq!(v["params"]["org_id"], "acme");
1694 assert_eq!(v["params"]["org_root_pk"], "b64u:AAAA");
1695 assert_eq!(v["params"]["user_id"], "alice");
1696 assert_eq!(
1697 v["params"]["user_key"],
1698 "/home/alice/.config/mcpmesh/user.key"
1699 );
1700 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1701 // method_of resolves the tag generically (no per-variant arm).
1702 assert_eq!(
1703 method_of(&serde_json::json!({"method": "org_join", "params": {"org_id": "x"}})),
1704 Some("org_join")
1705 );
1706
1707 // OrgJoinResult echoes the pinned org id (surface-clean; the fingerprint is porcelain-side).
1708 let res = OrgJoinResult {
1709 org_id: "acme".into(),
1710 };
1711 let v = serde_json::to_value(&res).unwrap();
1712 assert_eq!(v["org_id"], "acme");
1713 assert_eq!(serde_json::from_value::<OrgJoinResult>(v).unwrap(), res);
1714 }
1715
1716 #[test]
1717 fn set_roster_url_request_roundtrip() {
1718 // Request::SetRosterUrl → `{ "method": "set_roster_url", "params": { "url": "..." } }`.
1719 let r = Request::SetRosterUrl(SetRosterUrlParams {
1720 url: "https://intranet.acme.com/roster.json".into(),
1721 });
1722 let v = serde_json::to_value(&r).unwrap();
1723 assert_eq!(v["method"], "set_roster_url");
1724 assert_eq!(v["params"]["url"], "https://intranet.acme.com/roster.json");
1725 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1726 assert_eq!(
1727 method_of(&serde_json::json!({"method": "set_roster_url", "params": {"url": "x"}})),
1728 Some("set_roster_url")
1729 );
1730 }
1731
1732 #[test]
1733 fn peer_remove_request_roundtrip() {
1734 // Request::PeerRemove → `{ "method": "peer_remove", "params": { "nickname": "..." } }`.
1735 let r = Request::PeerRemove(PeerRemoveParams {
1736 nickname: "bob".into(),
1737 });
1738 let v = serde_json::to_value(&r).unwrap();
1739 assert_eq!(v["method"], "peer_remove");
1740 assert_eq!(v["params"]["nickname"], "bob");
1741 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1742 // method_of resolves the tag generically (no per-variant arm).
1743 assert_eq!(
1744 method_of(&serde_json::json!({"method": "peer_remove", "params": {"nickname": "bob"}})),
1745 Some("peer_remove")
1746 );
1747 }
1748
1749 /// The reserved/internal `peer_add` rides the SAME typed vocabulary as every other method —
1750 /// `{ "method": "peer_add", "params": { nickname, endpoint_id, allow } }` — with `allow`
1751 /// defaulting to empty when absent.
1752 #[test]
1753 fn peer_add_request_roundtrip() {
1754 let r = Request::PeerAdd(PeerAddParams {
1755 nickname: "bob".into(),
1756 endpoint_id: "96246d3f".into(),
1757 allow: vec!["notes".into()],
1758 });
1759 let v = serde_json::to_value(&r).unwrap();
1760 assert_eq!(v["method"], "peer_add");
1761 assert_eq!(v["params"]["nickname"], "bob");
1762 assert_eq!(v["params"]["endpoint_id"], "96246d3f");
1763 assert_eq!(v["params"]["allow"][0], "notes");
1764 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1765 // An absent allow list deserializes to empty (the server-side tolerance).
1766 let p: PeerAddParams =
1767 serde_json::from_value(serde_json::json!({"nickname": "bob", "endpoint_id": "x"}))
1768 .unwrap();
1769 assert!(p.allow.is_empty());
1770 }
1771
1772 #[test]
1773 fn peer_rename_request_roundtrip() {
1774 // By user_id (renames all of a person's devices in one op).
1775 let r = Request::PeerRename(PeerRenameParams {
1776 user_id: Some("b64u:BOB".into()),
1777 nickname: None,
1778 to: "Bobby".into(),
1779 });
1780 let v = serde_json::to_value(&r).unwrap();
1781 assert_eq!(v["method"], "peer_rename");
1782 assert_eq!(v["params"]["user_id"], "b64u:BOB");
1783 assert_eq!(v["params"]["to"], "Bobby");
1784 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1785 // A provisional contact is renamed by nickname; omitted user_id defaults to None.
1786 assert_eq!(
1787 method_of(
1788 &serde_json::json!({"method": "peer_rename", "params": {"nickname": "carol", "to": "Carol"}})
1789 ),
1790 Some("peer_rename")
1791 );
1792 }
1793
1794 #[test]
1795 fn status_result_roundtrips() {
1796 // Pure-pairing daemon: `roster` is None — absent from the wire (skip_serializing_if) and an
1797 // older payload with no `roster` key still deserializes to None (serde default).
1798 let s = StatusResult {
1799 stack_version: "0.1.0".into(),
1800 services: vec![ServiceInfo {
1801 name: "notes".into(),
1802 allow: vec!["alice".into()],
1803 allow_display: vec![],
1804 backend: BackendKind::Run,
1805 ephemeral: false,
1806 }],
1807 peers: vec![PeerInfo {
1808 name: "alice".into(),
1809 services: vec!["notes".into()],
1810 // A paired peer that proved a self-sovereign user_id at pairing (surface-clean id).
1811 user_id: Some("b64u:alicepk".into()),
1812 principal: None,
1813 }],
1814 roster: None,
1815 presence: vec![],
1816 self_user_id: Some("b64u:selfpk".into()),
1817 recent_pairings: vec![],
1818 reachability: vec![],
1819 self_nickname: String::new(),
1820 };
1821 let v = serde_json::to_value(&s).unwrap();
1822 assert_eq!(v["services"][0]["backend"], "run");
1823 // The additive identity fields ride the wire when present.
1824 assert_eq!(v["peers"][0]["user_id"], "b64u:alicepk");
1825 assert_eq!(v["self_user_id"], "b64u:selfpk");
1826 assert!(
1827 v.get("roster").is_none(),
1828 "an absent roster must not appear on the wire: {v}"
1829 );
1830 assert!(
1831 v.get("presence").is_none(),
1832 "an empty presence must not appear on the wire: {v}"
1833 );
1834 assert!(
1835 v.get("recent_pairings").is_none(),
1836 "an empty recent_pairings must not appear on the wire: {v}"
1837 );
1838 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1839
1840 // A payload minted by an older daemon (no `roster`/`presence`/identity keys) still
1841 // deserializes — the identity fields default to None / a nickname-only peer.
1842 let old_shape = serde_json::json!({
1843 "stack_version": "0.1.0",
1844 "services": [],
1845 "peers": [{ "name": "bob", "services": [] }],
1846 });
1847 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1848 assert!(back.roster.is_none());
1849 assert!(back.presence.is_empty());
1850 assert!(back.self_user_id.is_none());
1851 assert!(back.peers[0].user_id.is_none());
1852 assert!(back.recent_pairings.is_empty());
1853
1854 // Roster daemon: a Some(RosterStatus) + an advisory presence list round-trip. `presence`
1855 // carries FLAT vocabulary only (user_id/device_label/role/online) — no EndpointId/key.
1856 let s = StatusResult {
1857 stack_version: "0.1.0".into(),
1858 services: vec![],
1859 peers: vec![],
1860 roster: Some(RosterStatus {
1861 org_id: "acme".into(),
1862 serial: 42,
1863 state: "approved".into(),
1864 org_root_fingerprint: "tango-fig-cabbage-anchor".into(),
1865 }),
1866 presence: vec![
1867 PresencePeer {
1868 user_id: "alice".into(),
1869 device_label: "laptop".into(),
1870 role: "primary".into(),
1871 online: true,
1872 meta: String::new(),
1873 },
1874 PresencePeer {
1875 user_id: "alice".into(),
1876 device_label: "desktop".into(),
1877 role: "mirror".into(),
1878 online: false,
1879 meta: String::new(),
1880 },
1881 ],
1882 self_user_id: None,
1883 recent_pairings: vec![],
1884 reachability: vec![],
1885 self_nickname: String::new(),
1886 };
1887 let v = serde_json::to_value(&s).unwrap();
1888 assert_eq!(v["roster"]["org_id"], "acme");
1889 assert_eq!(v["roster"]["serial"], 42u64);
1890 assert_eq!(v["roster"]["state"], "approved");
1891 assert_eq!(
1892 v["roster"]["org_root_fingerprint"],
1893 "tango-fig-cabbage-anchor"
1894 );
1895 assert_eq!(v["presence"][0]["user_id"], "alice");
1896 assert_eq!(v["presence"][0]["device_label"], "laptop");
1897 assert_eq!(v["presence"][0]["role"], "primary");
1898 assert_eq!(v["presence"][0]["online"], true);
1899 assert_eq!(v["presence"][1]["online"], false);
1900 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1901 }
1902
1903 /// The `recent_pairings` status field is ADDITIVE: a populated list round-trips with
1904 /// the flat `{peer_nickname, sas_code, paired_at_epoch}` shape (nickname + SAS words + epoch —
1905 /// never an EndpointId), an empty list is dropped from the wire, and a payload minted by an
1906 /// older daemon (no key at all) still deserializes to empty.
1907 #[test]
1908 fn recent_pairings_are_additive_on_status() {
1909 let s = StatusResult {
1910 stack_version: "0.1.0".into(),
1911 services: vec![],
1912 peers: vec![],
1913 roster: None,
1914 presence: vec![],
1915 self_user_id: None,
1916 recent_pairings: vec![RecentPairing {
1917 peer_nickname: "bob".into(),
1918 sas_code: "tango-fig-cabbage".into(),
1919 paired_at_epoch: 1_800_000_000,
1920 }],
1921 reachability: vec![],
1922 self_nickname: String::new(),
1923 };
1924 let v = serde_json::to_value(&s).unwrap();
1925 assert_eq!(v["recent_pairings"][0]["peer_nickname"], "bob");
1926 assert_eq!(v["recent_pairings"][0]["sas_code"], "tango-fig-cabbage");
1927 assert_eq!(v["recent_pairings"][0]["paired_at_epoch"], 1_800_000_000u64);
1928 assert_eq!(serde_json::from_value::<StatusResult>(v).unwrap(), s);
1929
1930 // A payload minted by an OLDER daemon (no `recent_pairings` key) still deserializes —
1931 // the `#[serde(default)]` fills it with an empty list.
1932 let old_shape = serde_json::json!({
1933 "stack_version": "0.1.0",
1934 "services": [],
1935 "peers": [],
1936 });
1937 let back: StatusResult = serde_json::from_value(old_shape).unwrap();
1938 assert!(back.recent_pairings.is_empty());
1939 }
1940
1941 #[test]
1942 fn blob_requests_and_results_roundtrip() {
1943 // BlobPublish → { method, params: { scope, path } }.
1944 let r = Request::BlobPublish(BlobPublishParams {
1945 scope: "docs".into(),
1946 path: "/tmp/a.bin".into(),
1947 });
1948 let v = serde_json::to_value(&r).unwrap();
1949 assert_eq!(v["method"], "blob_publish");
1950 assert_eq!(v["params"]["scope"], "docs");
1951 assert_eq!(v["params"]["path"], "/tmp/a.bin");
1952 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1953
1954 // BlobGrant → { method, params: { scope, principal } }.
1955 // #62: the two withdrawal verbs' wire tags. A wrong dispatch string or a swapped param
1956 // would otherwise ship undetected — the e2e test calls the provider directly and never
1957 // crosses JSON-RPC.
1958 let rev = Request::BlobRevoke(BlobRevokeParams {
1959 scope: "photos".into(),
1960 principals: vec!["alice".into()],
1961 });
1962 let v = serde_json::to_value(&rev).unwrap();
1963 assert_eq!(v["method"], "blob_revoke");
1964 assert_eq!(v["params"]["principals"][0], "alice");
1965 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), rev);
1966
1967 let unp = Request::BlobUnpublish(BlobUnpublishParams {
1968 scope: "photos".into(),
1969 hash: "abc123".into(),
1970 });
1971 let v = serde_json::to_value(&unp).unwrap();
1972 assert_eq!(v["method"], "blob_unpublish");
1973 assert_eq!(v["params"]["hash"], "abc123");
1974 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), unp);
1975
1976 let r = Request::BlobGrant(BlobGrantParams {
1977 scope: "docs".into(),
1978 principal: "alice".into(),
1979 });
1980 let v = serde_json::to_value(&r).unwrap();
1981 assert_eq!(v["method"], "blob_grant");
1982 assert_eq!(v["params"]["principal"], "alice");
1983 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
1984
1985 // BlobList is parameterless (method_of resolves it).
1986 assert_eq!(
1987 method_of(&serde_json::json!({"method": "blob_list"})),
1988 Some("blob_list")
1989 );
1990
1991 // BlobFetch → { method, params: { ticket, dest_path } }.
1992 let r = Request::BlobFetch(BlobFetchParams {
1993 ticket: "blobAAA".into(),
1994 dest_path: "/tmp/out.bin".into(),
1995 });
1996 let v = serde_json::to_value(&r).unwrap();
1997 assert_eq!(v["method"], "blob_fetch");
1998 assert_eq!(v["params"]["ticket"], "blobAAA");
1999 assert_eq!(v["params"]["dest_path"], "/tmp/out.bin");
2000 assert_eq!(serde_json::from_value::<Request>(v).unwrap(), r);
2001
2002 // BlobPublishResult carries the ticket + hash (blob-reference vocabulary).
2003 let res = BlobPublishResult {
2004 ticket: "blobAAA".into(),
2005 hash: "ab".repeat(32),
2006 };
2007 let v = serde_json::to_value(&res).unwrap();
2008 assert_eq!(v["ticket"], "blobAAA");
2009 assert_eq!(serde_json::from_value::<BlobPublishResult>(v).unwrap(), res);
2010
2011 // BlobScopeList carries flat (name, hashes, grants) — no EndpointId/key leakage.
2012 let res = BlobScopeList {
2013 scopes: vec![ScopeInfo {
2014 name: "docs".into(),
2015 hashes: vec!["ab".repeat(32)],
2016 grants: vec!["alice".into()],
2017 withdrawn: vec![],
2018 hash_count: 1,
2019 grant_count: 1,
2020 withdrawn_count: 0,
2021 }],
2022 total: 1,
2023 truncated: false,
2024 };
2025 let v = serde_json::to_value(&res).unwrap();
2026 assert_eq!(v["scopes"][0]["name"], "docs");
2027 assert_eq!(v["scopes"][0]["grants"][0], "alice");
2028 assert_eq!(serde_json::from_value::<BlobScopeList>(v).unwrap(), res);
2029
2030 // BlobFetchResult carries the verified hash + byte length.
2031 let res = BlobFetchResult {
2032 hash: "ab".repeat(32),
2033 bytes_len: 4194304,
2034 };
2035 let v = serde_json::to_value(&res).unwrap();
2036 assert_eq!(v["bytes_len"], 4194304u64);
2037 assert_eq!(serde_json::from_value::<BlobFetchResult>(v).unwrap(), res);
2038 }
2039
2040 /// The three `subscribe` frame shapes round-trip with the documented `type`-tagged wire form
2041 /// (docs/local-protocol.md "Live event stream"): `snapshot` carries the flat session/reachability
2042 /// lists, `event` delegates through the `Box` so the record's fields sit VERBATIM under
2043 /// `record` (one schema with the JSONL log), and `lagged` carries the dropped count.
2044 #[test]
2045 fn stream_frames_roundtrip_with_the_documented_tags() {
2046 let snap = StreamFrame::Snapshot {
2047 active_sessions: vec![ActiveSession {
2048 peer: "bob".into(),
2049 service: "notes".into(),
2050 opened_at: 1_751_760_000,
2051 }],
2052 reachability: vec![PeerReachability {
2053 name: "bob".into(),
2054 reachable: true,
2055 rtt_ms: Some(42),
2056 age_secs: Some(3),
2057 meta: String::new(),
2058 principal: None,
2059 path: Default::default(),
2060 }],
2061 };
2062 let v = serde_json::to_value(&snap).unwrap();
2063 assert_eq!(v["type"], "snapshot");
2064 assert_eq!(v["active_sessions"][0]["peer"], "bob");
2065 assert_eq!(v["active_sessions"][0]["opened_at"], 1_751_760_000i64);
2066 assert_eq!(v["reachability"][0]["name"], "bob");
2067 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), snap);
2068
2069 let event = StreamFrame::Event {
2070 record: Box::new(AuditRecord::session_open(
2071 "2026-07-03T14:02:11.480Z".into(),
2072 Some("bob".into()),
2073 "notes".into(),
2074 )),
2075 };
2076 let v = serde_json::to_value(&event).unwrap();
2077 assert_eq!(v["type"], "event");
2078 // The record's fields ride verbatim under `record` — no Box indirection on the wire.
2079 assert_eq!(v["record"]["kind"], "session_open");
2080 assert_eq!(v["record"]["peer"], "bob");
2081 assert_eq!(v["record"]["service"], "notes");
2082 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), event);
2083
2084 let lagged = StreamFrame::Lagged { dropped: 12 };
2085 let v = serde_json::to_value(&lagged).unwrap();
2086 assert_eq!(v, serde_json::json!({ "type": "lagged", "dropped": 12 }));
2087 assert_eq!(serde_json::from_value::<StreamFrame>(v).unwrap(), lagged);
2088 }
2089
2090 /// A frame minted by a NEWER daemon (an unknown `type`) fails to deserialize rather than
2091 /// mis-parsing — the typed stream surface is closed; a forward-compatible consumer reads the
2092 /// raw `Value` stream instead (`ControlClient::open_stream`).
2093 #[test]
2094 fn unknown_stream_frame_type_is_rejected() {
2095 let future = serde_json::json!({ "type": "future_kind", "x": 1 });
2096 assert!(serde_json::from_value::<StreamFrame>(future).is_err());
2097 }
2098
2099 #[test]
2100 fn audit_summary_request_and_result_roundtrip() {
2101 // Request::AuditSummary is parameterless → `{ "method": "audit_summary" }`. Like Status, it
2102 // tolerates omitted/null params; the server dispatches on the method string (method_of).
2103 let r = Request::AuditSummary;
2104 assert_eq!(serde_json::to_value(&r).unwrap()["method"], "audit_summary");
2105 assert_eq!(
2106 method_of(&serde_json::json!({"method": "audit_summary"})),
2107 Some("audit_summary")
2108 );
2109
2110 // AuditSummaryResult carries LOCAL per-peer / per-service session counts (nicknames + service
2111 // names only — never endpoints/transport terms) + a total. Tuples mirror kb's
2112 // InsightResponse.per_peer_contribution: `["bob", 2]` on the wire.
2113 let res = AuditSummaryResult {
2114 per_peer: vec![("alice".into(), 1), ("bob".into(), 2)],
2115 per_service: vec![("kb".into(), 1), ("notes".into(), 3)],
2116 total_sessions: 4,
2117 };
2118 let v = serde_json::to_value(&res).unwrap();
2119 assert_eq!(v["per_peer"][1][0], "bob");
2120 assert_eq!(v["per_peer"][1][1], 2u64);
2121 assert_eq!(v["per_service"][1][0], "notes");
2122 assert_eq!(v["total_sessions"], 4u64);
2123 assert_eq!(
2124 serde_json::from_value::<AuditSummaryResult>(v).unwrap(),
2125 res
2126 );
2127
2128 // Additive-only: a result minted by an older daemon (no `total_sessions` key) still
2129 // deserializes — the `#[serde(default)]` fills it with 0.
2130 let old_shape = serde_json::json!({ "per_peer": [], "per_service": [] });
2131 let back: AuditSummaryResult = serde_json::from_value(old_shape).unwrap();
2132 assert_eq!(back.total_sessions, 0);
2133 assert!(back.per_peer.is_empty());
2134 }
2135}