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