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