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