Skip to main content

agentmux_srv/server/
reactive.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use axum::{
5    extract::{Extension, Query, State},
6    http::StatusCode,
7    response::{IntoResponse, Json, Response},
8};
9use serde_json::json;
10
11use crate::backend::blockcontroller;
12use crate::backend::reactive::{registry as agent_registry, AgentRegistration, InjectionRequest};
13use crate::backend::{base, subagent_watcher};
14
15use super::AppState;
16
17/// Max cross-instance forwards one inject may take (Tiers 2a/2b/3 each add one). A real delivery is
18/// one hop; the cap only stops two channels that hold stale-but-alive registry entries for the same
19/// agent from forwarding it back and forth forever (#2350).
20const MAX_FORWARD_HOPS: u8 = 3;
21
22pub(super) use super::jekt_echo::{echo_jekt_to_sender, EchoTrust};
23use super::jekt_echo::{echo_jekt_to_sender_with_files, echo_trust_from_peer_body};
24
25/// One forward candidate: where to POST, how to authenticate, and what the
26/// echoed marker should claim about the hop if it lands.
27pub(super) struct ForwardPeer<'a> {
28    /// Base URL of the peer srv (no path), e.g. `http://127.0.0.1:1234`.
29    pub url: &'a str,
30    /// `X-AuthKey` value; skipped entirely when empty.
31    pub auth_key: &'a str,
32    /// Which tier resolved this candidate — log field only.
33    pub kind: &'a str,
34    /// Channel the candidate came from, for the cross-channel registry tier.
35    /// `None` where the notion doesn't apply.
36    pub channel: Option<&'a str>,
37    pub trust: EchoTrust<'a>,
38}
39
40/// What one forward attempt concluded. The distinction that matters is
41/// [`Stale`](ForwardOutcome::Stale) vs
42/// [`Inconclusive`](ForwardOutcome::Inconclusive): only the former is evidence
43/// about the *candidate*, and only the former may drive an eviction.
44pub(super) enum ForwardOutcome {
45    /// The peer delivered it. The sender echo has already been emitted; the
46    /// caller should return this body verbatim.
47    Delivered(serde_json::Value),
48    /// The peer answered without delivering (`success` was not `true`), or was
49    /// unreachable at the transport level. Both are consistent with a registry
50    /// entry or discovery-cache entry pointing at something that is no longer
51    /// there — but neither *proves* it (a startup race looks identical), so
52    /// each tier applies its own eviction policy on top of this.
53    Stale,
54    /// Something failed that says nothing about whether the candidate is
55    /// alive — a non-2xx status, or a body that wasn't JSON. **Never evict on
56    /// this**; fall through to the next candidate/tier and leave the entry be.
57    Inconclusive,
58    /// The peer refused the jekt's files for a reason no other candidate
59    /// would change (`jekt_files::refused`): end the search with its answer.
60    Refused(serde_json::Value),
61    /// The request went out and no answer came in time (a peer that polls fine but does not take the message).
62    NoAnswer,
63}
64
65/// POSTs `forwarded_req` to a peer srv and echoes it to the sender if it lands: the one
66/// implementation every forwarding tier shares. As three copies, a tier that forgot the echo or
67/// passed `delivery_tier` wrong failed silently and differently from its siblings
68/// (`docs/reports/REPORT_NETWORK_ARCHITECTURE_DRYNESS_AND_ROBUST_LAN_2026_09_06.md` §4).
69///
70/// Delivered means `success: true` in the body, in every tier. The LAN tier used to accept a body
71/// that omitted `success`, which echoed a delivery confirmation for a message that may never have
72/// arrived. A real peer always sends it (`InjectionResponse::success` has no
73/// `skip_serializing_if`).
74pub(super) async fn forward_inject_to_peer(
75    state: &AppState,
76    req: &InjectionRequest,
77    forwarded_req: &InjectionRequest,
78    peer: ForwardPeer<'_>,
79) -> ForwardOutcome {
80    // A jekt with files carries them, after it (file transfer spec §4).
81    let route = if forwarded_req.files.is_some() { "inject-files" } else { "inject" };
82    let forward_url = format!("{}/agentmux/reactive/{route}", peer.url);
83    let channel = peer.channel.unwrap_or("-");
84    tracing::debug!(
85        target = %req.target_agent,
86        url = %forward_url,
87        kind = peer.kind,
88        channel,
89        "inject forward"
90    );
91
92    let mut fwd = state.http_client.post(&forward_url);
93    fwd = if forwarded_req.files.is_some() {
94        match super::jekt_files::transfer_body(forwarded_req).await {
95            Ok(body) => fwd.body(body).timeout(super::jekt_files::TRANSFER_TIMEOUT),
96            Err(e) => return ForwardOutcome::Refused(super::jekt_files::refused(req, e)),
97        }
98    } else {
99        fwd.json(forwarded_req)
100    };
101    if !peer.auth_key.is_empty() {
102        fwd = fwd.header(AUTH_KEY_HEADER, peer.auth_key);
103    }
104
105    match fwd.send().await {
106        Ok(r) if r.status().is_success() => {
107            let Ok(body) = r.json::<serde_json::Value>().await else {
108                tracing::warn!(
109                    target = %req.target_agent,
110                    url = %forward_url,
111                    kind = peer.kind,
112                    channel,
113                    "inject forward: 2xx with an unparseable body — not evicting"
114                );
115                return ForwardOutcome::Inconclusive;
116            };
117            if super::jekt_hold::peer_refused(&body) {
118                return ForwardOutcome::Refused(body);
119            }
120            if body.get("success").and_then(|v| v.as_bool()) != Some(true) {
121                tracing::warn!(
122                    target = %req.target_agent,
123                    url = %forward_url,
124                    kind = peer.kind,
125                    channel,
126                    "inject forward: peer did not deliver — candidate may be stale"
127                );
128                return ForwardOutcome::Stale;
129            }
130            echo_jekt_to_sender_with_files(
131                state,
132                req.source_agent.as_deref(),
133                &req.target_agent,
134                &req.message,
135                body.get("request_id").and_then(|v| v.as_str()).unwrap_or(""),
136                body.get("effective_tier").and_then(|v| v.as_str()),
137                body.get("requires_stop").and_then(|v| v.as_bool()),
138                echo_trust_from_peer_body(&body, peer.trust),
139                req.priority.as_deref().unwrap_or("normal"),
140                req.files_delivery.as_ref(),
141            );
142            ForwardOutcome::Delivered(body)
143        }
144        Ok(r) => {
145            tracing::warn!(
146                target = %req.target_agent,
147                status = %r.status(),
148                url = %forward_url,
149                kind = peer.kind,
150                channel,
151                "inject forward: non-success HTTP status — not evicting"
152            );
153            ForwardOutcome::Inconclusive
154        }
155        Err(e) => {
156            tracing::warn!(target = %req.target_agent, error = %e, url = %forward_url, kind = peer.kind, channel, timed_out = e.is_timeout(), "inject forward: transport failure, candidate may be stale");
157            if e.is_timeout() { ForwardOutcome::NoAnswer } else { ForwardOutcome::Stale }
158        }
159    }
160}
161
162/// Max age (seconds) of a signed jekt's `ts_secs` for it to verify
163/// (SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md §2.2, anti-replay, #2565). Without the check a
164/// captured valid signature verified forever. Wide enough for same-machine latency and clock skew,
165/// narrow enough to bound replay.
166const JEKT_SIG_MAX_AGE_SECS: i64 = 300;
167
168use agentmux_common::{time::now_secs as now_unix_secs, AUTH_KEY_HEADER};
169
170/// Host-tier jekt sender verification (SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md §2.2): sets
171/// `req.sig_verified` by checking `req.jekt_sig` against the claimed `source_agent`'s stored
172/// signing key, inside the freshness window.
173///
174/// **Every entry point that builds a host-tier `InjectionRequest` from client-supplied fields MUST
175/// call this before `Handler::inject_message`** (#2565): `messagebus.rs::handle_inject` and
176/// `websocket.rs`'s `bus:inject` once skipped it and rendered `TRUST=self-declared` for an
177/// impersonated sender.
178///
179/// **Deliberately not gated on `delivery_tier == "host"`** (#2588). `delivery_tier` is
180/// self-declared by any caller holding the full local `auth_key` (see `resolve_delivery_tier`), so
181/// gating on it let a request claiming `"lan"` or `"wan"` dodge this check and impersonate a
182/// locally known agent. Ungated, it acts only when `agent_jekt_key_load` finds a LOCAL key for the
183/// claimed sender: never for a genuine remote LAN/WAN sender, always for an impersonation of an
184/// agent this instance knows.
185pub(super) fn verify_jekt_signature(state: &AppState, req: &mut InjectionRequest) {
186    let Some(claimed) = req.source_agent.clone().filter(|s| !s.is_empty()) else {
187        return;
188    };
189    if super::actor::jekt_sender_by_token(&state.mstore, req, &claimed) {
190        req.sig_verified = Some(true); // identity M4d-4
191        return;
192    }
193    if former_slug::refuse_former_sender(state, req) {
194        return;
195    }
196    let Ok(Some(key)) = state.mstore.agent_jekt_key_load(&claimed) else {
197        return;
198    };
199    crate::backend::agent_resolve::record_uid_fallback("m4d.host_hmac_by_name");
200    let msgid = req.request_id.clone().unwrap_or_default();
201    let ts = req.ts_secs.unwrap_or(0);
202    let within_freshness_window =
203        ts > 0 && (now_unix_secs() - ts).abs() <= JEKT_SIG_MAX_AGE_SECS;
204    let verified = within_freshness_window
205        && req.jekt_sig.as_deref().map_or(false, |sig| {
206            agentmux_common::jekt_sign::verify_jekt(
207                &key, &msgid, &claimed, &req.target_agent, ts, &req.message, sig,
208            )
209        });
210    if !verified { tracing::warn!(agent_id = %claimed, fresh = within_freshness_window, "host jekt signature missing or did not verify"); }
211    req.sig_verified = Some(verified);
212}
213
214/// Anti-replay window for `req.reagent_ts_secs`: WAN-scoped, so wider than host-tier's 300 s
215/// because it covers real network latency. Same value as
216/// `cloud_subscriber::REAGENT_SIG_MAX_AGE_SECS`.
217const REAGENT_SIG_MAX_AGE_SECS: i64 = 600;
218
219/// WAN-tier reagent-signature check for the HTTP `/agentmux/reactive/inject` path, mirroring
220/// `cloud_subscriber::sync_agent_reactive` for the WS path. Before it, nothing on this path read
221/// `reagent_sig`/`reagent_key_id`, so a signed notification arrived effectively unsigned and never
222/// rendered `SIG=verified` (#41).
223///
224/// Only for `delivery_tier == "wan"`. A partial set of the four fields reads as "not signed"
225/// (`reagent_verified` stays `None`), as in `cloud_subscriber.rs`: a legitimate sender sends all
226/// four, and a stripped signature looks exactly like an absent one, so it buys an attacker nothing.
227///
228/// Takes `now` so a test can hold its fixed offline-signed fixture inside the window: the private
229/// half of the pinned Ed25519 key isn't in this repo (same as
230/// `cloud_subscriber::reagent_sig_is_fresh`).
231pub(super) fn verify_reagent_signature(req: &mut InjectionRequest, now: i64) {
232    if req.delivery_tier.as_deref() != Some("wan") {
233        return;
234    }
235    let (Some(sig), Some(key_id), Some(msg_id), Some(ts_secs)) =
236        (req.reagent_sig.as_deref(), req.reagent_key_id.as_deref(), req.reagent_msg_id.as_deref(), req.reagent_ts_secs)
237    else {
238        return;
239    };
240    let within_freshness_window = ts_secs > 0 && (now - ts_secs).abs() <= REAGENT_SIG_MAX_AGE_SECS;
241    let verified = within_freshness_window
242        && agentmux_common::jekt_sign::verify_trusted_reagent_jekt(
243            key_id,
244            msg_id,
245            req.source_agent.as_deref().unwrap_or(""),
246            &req.target_agent,
247            ts_secs,
248            &req.message,
249            sig,
250        );
251    req.reagent_verified = Some(verified);
252}
253
254/// Anti-replay window for `lan_sig`: the WAN value, since LAN crosses a real network hop (mDNS plus
255/// an HTTP round trip), not a same-machine call.
256const LAN_SIG_MAX_AGE_SECS: i64 = REAGENT_SIG_MAX_AGE_SECS;
257
258/// LAN-tier per-agent Ed25519 signature check (docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md
259/// §2.4). Async because the claimed sender's public key lives on whichever peer hosts that agent: a
260/// LAN round trip (`LanDiscoveryController::find_agent_lan_pubkey`), unlike
261/// `verify_jekt_signature`'s local lookup.
262///
263/// Only for `delivery_tier == "lan"`; `handle_reactive_inject` has already overridden the tier
264/// server-side (spec §3), so this never runs off a request that wasn't `lan_key`-authenticated.
265///
266/// No `lan_sig`, or no peer has the sender's public key: `lan_verified` stays `None` ("nothing to
267/// check against", as for `sig_verified`/`reagent_verified`). A `lan_sig` with a key found that
268/// doesn't verify: `Some(false)`, which `handler.rs` forces to `TIER=sensitive`, an active attempt
269/// to forge an agent's identity.
270pub(super) async fn verify_lan_signature(state: &AppState, req: &mut InjectionRequest) {
271    if req.delivery_tier.as_deref() != Some("lan") {
272        return;
273    }
274    let Some(sig) = req.lan_sig.as_deref() else {
275        return;
276    };
277    let Some(claimed) = req.source_agent.clone().filter(|s| !s.is_empty()) else {
278        return;
279    };
280    let observed_key = match lan_signer::resolve(state, &claimed).await {
281        lan_signer::SignerKey::Pinned(key) => key,
282        lan_signer::SignerKey::Unknown | lan_signer::SignerKey::Unproven => return,
283        lan_signer::SignerKey::Refused => {
284            req.lan_verified = Some(false);
285            return;
286        }
287    };
288
289    let msgid = req.request_id.clone().unwrap_or_default();
290    let ts = req.ts_secs.unwrap_or(0);
291    let within_freshness_window = ts > 0 && (now_unix_secs() - ts).abs() <= LAN_SIG_MAX_AGE_SECS;
292    let verified = within_freshness_window
293        && agentmux_common::jekt_sign::verify_lan_jekt(
294            &observed_key,
295            &msgid,
296            &claimed,
297            &req.target_agent,
298            ts,
299            &req.message,
300            sig,
301        );
302    if !verified { tracing::warn!(agent_id = %claimed, fresh = within_freshness_window, "LAN jekt signature did not verify"); }
303    req.lan_verified = Some(verified);
304    lan_v2::claim_uid(state, req, &claimed, &observed_key).await;
305}
306
307mod channel_v2; mod detached;
308mod flow_notes;
309mod forward_tiers;
310pub(super) mod peer_hold;
311pub(crate) mod lan_signer;
312mod registration_flags;
313pub(crate) mod former_slug;
314mod lan_v2;
315pub(crate) mod lan_continuity; pub(crate) mod lan_handover;
316pub(crate) mod lan_refusals;
317pub(super) mod replay;
318mod register;
319pub(super) use register::handle_reactive_register;
320#[cfg(test)]
321use register::RegisterRequest;
322
323/// Anti-replay window for `channel_sig` (SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D6):
324/// host-tier's tight one, since a cross-channel forward is a same-machine call to `127.0.0.1`.
325const CHANNEL_SIG_MAX_AGE_SECS: i64 = JEKT_SIG_MAX_AGE_SECS;
326
327/// Cross-channel (same machine, other AgentMux instance) per-agent Ed25519 signature check
328/// (docs/specs/SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D2, Phase B). Like
329/// `verify_lan_signature`, but the sender's public key comes from the host-global shared registry
330/// (`AgentEntry::jekt_public_key`, published at registration, §D1): a local file read, so it is
331/// synchronous and has no LAN rate-limiter `Skipped` hazard.
332///
333/// Only for `delivery_tier == "channel"`, the label a same-host forward carries (§D4, set in
334/// `handle_reactive_inject`'s Tier 2a/2b); `channel_verified` stays `None` otherwise.
335///
336/// Ordering (§D2 step 2): a sender this instance holds an HMAC key for is a same-instance agent
337/// that `verify_jekt_signature` owns entirely, so this returns without touching `channel_verified`
338/// and the two verifiers can never disagree.
339///
340/// Outcomes:
341///
342/// - `None`: no shared-registry entry for the sender, or every entry has an empty `jekt_public_key`
343///   (written before Phase A: "cannot check", never "failed", §6).
344///
345/// - `Some(true)`: `channel_sig` is present, fresh and verifies against the published key of ANY of
346///   the agent's entries (one name can be live in several channels, §D2 step 5).
347///
348/// - `Some(false)`: a published key was found but the signature was missing, stale or wrong. The
349///   §D3 red flag; not escalated in Phase B (see `InjectionRequest::channel_verified`).
350pub(super) fn verify_cross_channel_signature(state: &AppState, req: &mut InjectionRequest) {
351    let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() else {
352        return;
353    };
354    verify_cross_channel_signature_in(state, req, &shared_dir, now_unix_secs());
355}
356
357/// [`verify_cross_channel_signature`] with the shared registry dir and clock injected: the testable
358/// core, which keeps tests off the process-global `AGENTMUX_SHARED_DIR`.
359pub(super) fn verify_cross_channel_signature_in(
360    state: &AppState,
361    req: &mut InjectionRequest,
362    shared_dir: &std::path::Path,
363    now_secs: i64,
364) {
365    if req.delivery_tier.as_deref() != Some("channel") {
366        return;
367    }
368    let Some(claimed) = req.source_agent.clone().filter(|s| !s.is_empty()) else {
369        return;
370    };
371    // Identity M4d-6: a v2 signature proves the sender's UID. When it is the agent this instance
372    // knows by the claimed name, the name's checks are settled, even a failed HMAC against a key
373    // kept from when that agent ran here; a different agent of the same name is not the name's.
374    if channel_v2::settle_by_uid(state, req, &claimed, shared_dir, now_secs) {
375        return;
376    }
377    // §D2 step 2: a same-instance sender is the HMAC path's to judge.
378    if matches!(state.mstore.agent_jekt_key_load(&claimed), Ok(Some(_))) {
379        return;
380    }
381    // Only entries that published a key count: an empty one (pre-Phase-A) is "cannot check", and
382    // must not turn a missing signature into `Some(false)` on a mixed-version machine (§6).
383    let published_keys: Vec<Vec<u8>> = agent_registry::lookup_all_shared(shared_dir, &claimed)
384        .into_iter()
385        .filter(|e| !e.jekt_public_key.is_empty())
386        .filter_map(|e| agentmux_common::jekt_sign::decode_key(&e.jekt_public_key))
387        .collect();
388    if published_keys.is_empty() {
389        return;
390    }
391
392    let msgid = req.request_id.clone().unwrap_or_default();
393    let ts = req.ts_secs.unwrap_or(0);
394    let within_freshness_window = ts > 0 && (now_secs - ts).abs() <= CHANNEL_SIG_MAX_AGE_SECS;
395    let source_channel = req.source_channel.as_deref().unwrap_or("");
396    let verified = within_freshness_window
397        && req.channel_sig.as_deref().is_some_and(|sig| {
398            published_keys.iter().any(|key| {
399                agentmux_common::jekt_sign::verify_channel_jekt(
400                    key,
401                    &msgid,
402                    &claimed,
403                    source_channel,
404                    &req.target_agent,
405                    ts,
406                    &req.message,
407                    sig,
408                )
409            })
410        });
411    if !verified {
412        tracing::warn!(
413            agent_id = %claimed,
414            source_channel = %source_channel,
415            has_signature = req.channel_sig.is_some(),
416            fresh = within_freshness_window,
417            "cross-channel jekt: claimed sender has a published key but the signature did not verify"
418        );
419    }
420    req.channel_verified = Some(verified);
421}
422
423/// Server-derived `delivery_tier` for the LAN-key case only
424/// (docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md §3): a `lan_key` caller is forced to
425/// `"lan"` whatever the body says, so claiming `"host"` can't dodge LAN scrutiny. Any other
426/// caller's claim (host/wan/lan/channel) is kept.
427///
428/// A full-`auth_key` caller is not downgraded from `"lan"`: a jekt that arrived by `lan_key` and
429/// was relayed to a sibling instance on this machine authenticates that second hop with the
430/// sibling's full `auth_key` (`lan_key` is peer-to-peer between machines only). Downgrading
431/// discarded an already-detected LAN signature failure's forced-sensitive escalation
432/// (`lan_verified`/`reagent_verified` are `#[serde(skip_deserializing)]`, so they re-derive on
433/// every hop). Honouring the claim costs nothing: the full key already grants full control, and a
434/// self-labelled tier only adds verification, never removes it.
435///
436/// `"channel"` (SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D4) follows the same rule: the
437/// forwarding instance sets it on a same-host Tier 2a/2b hop, and it only adds
438/// `verify_cross_channel_signature`.
439pub(super) fn resolve_delivery_tier(auth_via: super::ReactiveAuthVia, claimed: Option<&str>) -> String {
440    if auth_via == super::ReactiveAuthVia::LanKey {
441        "lan".to_string()
442    } else {
443        claimed.unwrap_or("host").to_string()
444    }
445}
446
447/// The `delivery_tier` a same-host Tier 2a/2b forward carries
448/// (SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §D4): `host` or unlabelled becomes `channel`; a
449/// network tier is kept so the peer re-derives that tier's verification.
450fn same_host_forward_tier(current: Option<&str>) -> &str {
451    match current {
452        None | Some("host") => "channel",
453        Some(other) => other,
454    }
455}
456
457/// Server-side resolution of `InjectionRequest::is_transcript_request` /
458/// `transcript_request_escalate_forced` (fields documented in `backend/reactive/types.rs`;
459/// SPEC_JEKT_TRANSCRIPT_REQUEST_TIER_RULES_2026_08_22.md). Here, not in
460/// `Handler::inject_message_inner`, because it needs `Store`, which `Handler` lacks by design.
461///
462/// Takes `&Arc<Store>` so `muxbus::cloud_subscriber::sync_agent_reactive`, the WAN path that calls
463/// `Handler::inject_message` directly, applies the same rules; without it a WAN
464/// `transcript_request` would skip both.
465///
466/// Always recomputes from `req.message`, never from anything the client set on the two fields.
467pub(crate) fn resolve_transcript_request_tier_fields(mstore: &std::sync::Arc<crate::backend::storage::store::Store>, req: &mut InjectionRequest) {
468    let Some(transcript_req) = crate::backend::reactive::transcript_request::parse_transcript_request(&req.message) else {
469        return;
470    };
471    let _ = transcript_req; // request_id/max_lines belong to the (not-yet-built) auto-responder, not tier resolution.
472    req.is_transcript_request = true;
473
474    // The RESPONDING agent's (target_agent's) own definition: by its slug,
475    // the stable AGENTMUX_AGENT_ID-derived identifier, else by its display
476    // name's route name (a fork targeted as `Loap-3`, #4744). A target naming
477    // several agents fails closed, as `ask`.
478    let defs = mstore.agent_defs_for_target(&req.target_agent).unwrap_or_default();
479    let (slug, visibility) = match defs.as_slice() {
480        [def] => (def.slug.clone(), def.conversation_visibility.clone()),
481        [] => (req.target_agent.clone(), crate::backend::storage::agents::default_conversation_visibility()),
482        _ => (req.target_agent.clone(), "ask".to_string()),
483    };
484
485    let tier = req.delivery_tier.as_deref().unwrap_or("host");
486    req.transcript_request_escalate_forced = match visibility.as_str() {
487        "ask" => true,
488        "trusted_peers" => {
489            let requester = req.source_agent.as_deref().unwrap_or("");
490            let granted = mstore
491                .conversation_trust_grant_check(&slug, requester, tier)
492                .unwrap_or(false);
493            !granted
494        }
495        // "private" and any unrecognized value fail closed on the ESCALATE-forcing question too: a
496        // def from a state older than this feature never opted into relaxation. Rule 1's forced
497        // TIER=sensitive still applies; only this extra rule reads "private" as "no need to force
498        // more", since a "private" agent auto-denies (once the responder auto-resolve is built) and
499        // discloses nothing either way.
500        _ => false,
501    };
502}
503
504#[cfg(test)]
505#[path = "tests/reactive/transcript_request_tier_resolution_tests.rs"]
506mod transcript_request_tier_resolution_tests;
507
508pub(super) async fn handle_reactive_inject(
509    State(state): State<AppState>,
510    Extension(auth_via): Extension<super::ReactiveAuthVia>,
511    caller: Option<Extension<super::caller::Caller>>,
512    Json(req): Json<InjectionRequest>,
513) -> Json<serde_json::Value> {
514    if let Err(error) = super::lan_watch::acting(req.source_agent.as_deref(), super::actor::require_actor(&state, caller.as_deref(), super::actor::ActorSite::Inject, req.source_agent.as_deref())).await {
515        return Json(serde_json::json!({ "success": false, "error": error }));
516    }
517    tracing::info!(
518        target_agent = %req.target_agent,
519        source_agent = ?req.source_agent,
520        msg_len = req.message.len(),
521        "reactive inject request received"
522    );
523    let caller_uid = super::caller::attributed_uid(caller.as_deref());
524    Json(detached::deliver_to_completion(&state, auth_via, &caller_uid, req).await)
525}
526
527/// Deliver an inject — verify, try this instance, then forward
528/// cross-instance, cross-channel, LAN and cloud relay — exactly as
529/// `POST /agentmux/reactive/inject` does. Shared with the cron scheduler's
530/// in-process fire (identity M4c-3, spec §6.5.9), which passes its tier
531/// explicitly (`auth_via`) in place of the route's `ReactiveAuthVia`
532/// extension. `caller_uid` is the sender's attributed UID, audited on this
533/// instance only (`InjectionRequest::audit_source_uid` never rides a hop);
534/// `""` when Unattributed.
535pub(crate) async fn deliver(
536    state: &AppState,
537    auth_via: super::ReactiveAuthVia,
538    caller_uid: &str,
539    mut req: InjectionRequest,
540) -> serde_json::Value {
541    let mut replay = match admit(state, auth_via, caller_uid, &mut req).await {
542        Ok(replay) => replay,
543        Err(answer) => return flow_notes::noted(state, &req, answer),
544    };
545
546    // 1. Try local ReactiveHandler first (fast path — same instance).
547    let resp = super::lan_watch::during("local delivery", super::cron::inject_here_following_runs(state, &req)).await;
548    if resp.success {
549        replay.delivered();
550        flow_notes::note_delivered(state, &req);
551        echo_local_delivery(state, &req, &resp);
552        return super::jekt_files::with_count(serde_json::to_value(&resp).unwrap_or_default(), &req);
553    }
554
555    // The target is here but not signed in, or its pane has no controller yet: held, not failed.
556    if let Some(answer) = super::jekt_hold::hold_for_refusal_here(state, auth_via, &req, &resp, &mut replay).await {
557        return flow_notes::noted(state, &req, answer);
558    }
559
560    // 2. On "agent not found", check cross-instance file registry and forward.
561    let is_not_found = resp
562        .error
563        .as_deref()
564        .map(|e| e.starts_with("agent not found"))
565        .unwrap_or(false);
566
567    if is_not_found && req.forward_hops >= MAX_FORWARD_HOPS {
568        tracing::warn!(
569            target = %req.target_agent,
570            hops = req.forward_hops,
571            "reactive inject: forward-hop limit reached, not forwarding further"
572        );
573        return serde_json::to_value(&resp).unwrap_or_default();
574    }
575
576    if is_not_found {
577        if let Some(body) = super::lan_watch::during("forwarding", forward_tiers::Tiers::new(state, auth_via, caller_uid, &req, &resp).run(&mut replay)).await {
578            return body;
579        }
580    }
581
582    // 6. Every tier declined — return the original local error.
583    serde_json::to_value(&resp).unwrap_or_default()
584}
585
586/// What a jekt must pass before any delivery is tried: its signatures, the checks on its
587/// files and its text, and the holds for an agent that cannot take it now. `Err` is the
588/// answer to send back; `Ok` is the claim on its request id, released when `deliver` ends.
589async fn admit(
590    state: &AppState,
591    auth_via: super::ReactiveAuthVia,
592    caller_uid: &str,
593    req: &mut InjectionRequest,
594) -> Result<replay::Reservation, serde_json::Value> {
595    req.delivery_tier = Some(resolve_delivery_tier(auth_via, req.delivery_tier.as_deref()));
596    // Identity M4c-2d: the sender's UID, for the audit only (`#[serde(skip)]`).
597    req.audit_source_uid = caller_uid.to_string();
598    super::actor::source_from_token(&state.mstore, caller_uid, req);
599    // Identity M4d-6: count a signed source_uid other than the token's UID.
600    if !caller_uid.is_empty() && req.source_uid.as_deref().is_some_and(|s| s != caller_uid) {
601        crate::backend::agent_resolve::record_uid_fallback("m4.source_uid_mismatch");
602    }
603
604    verify_jekt_signature(state, req);
605    verify_reagent_signature(req, now_unix_secs());
606    super::lan_watch::during("sender signature check", verify_lan_signature(state, req)).await;
607    verify_cross_channel_signature(state, req);
608    lan_v2::log_receipt(req);
609    let mut replay = replay::reserve(req, now_unix_secs());
610    if let Some(answer) = super::quiet_remote::intercept(state, req, &mut replay).await { return Err(answer); } // a quiet note is answered, never delivered
611    req.route_unsigned_target();
612    resolve_transcript_request_tier_fields(&state.mstore, req);
613
614    // Files (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §3.3, §6): refused unless the
615    // msgid binds them, then prepared here, since the handler does no I/O.
616    if let Err(error) = super::jekt_files::check(req) {
617        return Err(super::jekt_files::refused(req, error));
618    }
619    // A reply that says nothing starts a turn for nothing (SPEC_CHEAPER_FLEET_MESSAGING_2026_10_30.md §6).
620    if let Some(refused) = super::jekt_ack::refuse_empty_reply(state, auth_via, req) {
621        return Err(refused);
622    }
623    crate::backend::reactive::sent_audit::record(req);
624    // An agent here out of quota or signed out would lose it in a failed turn, and a Claude
625    // session gone cold should not be woken by a routine one: hold it, or refuse it where it
626    // can't be held (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §5, SPEC_JEKT_HOLD_FOR_COLD_SESSIONS_
627    // 2026_10_25.md). Before `prepare`, which charges inline attachments to the session.
628    if let Some(held) = super::lan_watch::during("hold check", hold_before_delivery(state, auth_via, req, &mut replay)).await {
629        return Err(held);
630    }
631
632    super::jekt_files::prepare(req).await;
633    Ok(replay)
634}
635
636/// Echo a locally delivered jekt into the sender's own pane, as every
637/// successful delivery path does.
638pub(super) fn echo_local_delivery(
639    state: &AppState,
640    req: &InjectionRequest,
641    resp: &crate::backend::reactive::types::InjectionResponse,
642) {
643    echo_jekt_to_sender_with_files(
644        state,
645        req.source_agent.as_deref(),
646        &req.target_agent,
647        &req.message,
648        &resp.request_id,
649        resp.effective_tier.as_deref(),
650        resp.requires_stop,
651        // Same `req` the `effective_tier`/`requires_stop` came from, so the marker's TRUST/SIG
652        // matches its ESCALATE=.
653        EchoTrust::of(req),
654        req.priority.as_deref().unwrap_or("normal"),
655        req.files_delivery.as_ref(),
656    );
657}
658
659/// The UID and slug of the agent defined in this channel that `target`
660/// names, as the hold resolves it (`hold_for_absent_target`). The slug is
661/// the agent's `AGENTMUX_AGENT_ID`, which its relay lease is keyed by.
662pub(super) fn defined_here(mstore: &crate::backend::storage::store::Store, target: &str) -> Option<(String, String)> {
663    let target = target.trim();
664    let uid = match mstore.instance_get(target) {
665        Ok(Some(row)) => row.id,
666        _ => match mstore.agents_matching_name(target) {
667            Ok(rows) if rows.len() == 1 => rows[0].id.clone(),
668            _ => return None,
669        },
670    };
671    let slug = match mstore.agent_def_get(&uid) {
672        Ok(Some(def)) if !def.slug.is_empty() => def.slug,
673        _ => target.to_string(),
674    };
675    Some((uid, slug))
676}
677
678/// Where a jekt goes when no tier found its target live
679/// (`PLAN_JEKT_LOCAL_FIRST_ROUTING_2026_10_02.md` §5-§6).
680#[derive(Debug, Clone, Copy, PartialEq, Eq)]
681pub(crate) enum AbsentRoute {
682    /// Hold it on this instance (24 h) and deliver when the agent opens here.
683    HoldHere,
684    /// Leave it to the cloud relay, then the hold as a fallback (the order
685    /// before this plan).
686    Relay,
687}
688
689/// Decide [`AbsentRoute`] for a target no tier found live. Holding here is
690/// the default for an agent defined in this channel, so messaging works
691/// without the relay; the relay overrides it only when it says another
692/// install of the account holds the agent's lease. Anything the relay
693/// cannot answer plainly keeps the old order (relay first), so an older
694/// relay changes nothing.
695pub(crate) async fn route_for_absent(
696    state: &AppState,
697    auth_via: super::ReactiveAuthVia,
698    req: &InjectionRequest,
699    resp: &crate::backend::reactive::types::InjectionResponse,
700) -> AbsentRoute {
701    use crate::muxbus::wan_lease;
702    if !hold_applies(auth_via, req, resp) {
703        return AbsentRoute::Relay;
704    }
705    let mstore = state.mstore.clone();
706    let target = req.target_agent.clone();
707    let Some((_uid, slug)) = tokio::task::spawn_blocking(move || defined_here(&mstore, &target)).await.ok().flatten() else {
708        // Not an agent of this channel: it can only be on another install.
709        return AbsentRoute::Relay;
710    };
711    // This instance itself recently heard the lease is held elsewhere.
712    if wan_lease::held_elsewhere(&slug).is_some() {
713        return AbsentRoute::Relay;
714    }
715    // No relay for this sender (no source agent, not signed in): hold.
716    let Some(source) = req.source_agent.as_deref().filter(|s| !s.is_empty()) else {
717        return AbsentRoute::HoldHere;
718    };
719    let Some(credential) = crate::muxbus::relay::relay_token(source, &state.id_store, &state.http_client).await else {
720        return AbsentRoute::HoldHere;
721    };
722    let answer = wan_lease::holder(
723        &crate::muxbus::relay::rest_base_url(),
724        &slug,
725        source,
726        &credential.token,
727        &state.http_client,
728    )
729    .await;
730    let route = absent_route_for(&answer);
731    tracing::debug!(target = %req.target_agent, lease = ?answer, ?route, "jekt: routing an absent local agent");
732    route
733}
734
735/// The relay's lease answer as a route: hold here unless it says another
736/// install runs the agent or cannot say; an unreachable relay holds here
737/// (there is no relay to send through anyway).
738pub(super) fn absent_route_for(answer: &crate::muxbus::wan_lease::Holder) -> AbsentRoute {
739    use crate::muxbus::wan_lease::Holder;
740    match answer {
741        Holder::Free | Holder::Yours | Holder::Unreachable => AbsentRoute::HoldHere,
742        Holder::Other(..) | Holder::Unknown | Holder::Unsupported => AbsentRoute::Relay,
743    }
744}
745
746/// Why a jekt is held (`server::hold_reason`).
747pub(crate) use super::hold_reason::HoldReason;
748pub(in crate::server) use super::jekt_hold::hold_for_absent_target;
749use super::jekt_hold::{hold_applies, hold_before_delivery};
750
751/// Tier 4. `Some(body)` when the cloud accepted the injection (sender echo emitted); `None` when it
752/// doesn't apply or didn't take, leaving the caller to return its original error.
753///
754/// **Queued is not delivered:** `success: true` means "handed to the relay", the strongest claim
755/// any WAN tier makes (and what `DELIVERY=wan` on the echoed marker says). The recipient's srv
756/// picks it up on its next sync, or never if that instance is offline.
757pub(super) async fn try_cloud_relay(state: &AppState, req: &InjectionRequest, caller_uid: &str) -> Option<serde_json::Value> {
758    // Never re-relay what ARRIVED over the cloud: an agent unknown everywhere would bounce between
759    // the relay and every subscriber forever. `forward_hops` can't catch it (the cloud resets the
760    // count), so this tier needs its own guard.
761    if req.delivery_tier.as_deref() == Some("wan") {
762        return None;
763    }
764
765    // The cloud route derives the sender from `X-Agent-ID` and 400s without it,
766    // so a caller with no source agent (cron, external bridge) has no tier 4.
767    let source = req.source_agent.as_deref().filter(|s| !s.is_empty())?;
768
769    let credential = crate::muxbus::relay::relay_token(source, &state.id_store, &state.http_client).await;
770    let Some(credential) = credential else {
771        tracing::debug!(
772            target = %req.target_agent,
773            "cloud relay skipped: not logged in to muxbus"
774        );
775        return None;
776    };
777
778    let priority = req.priority.as_deref().unwrap_or("normal");
779    // SPEC_WAN_JEKT_SIGNED_BY_SRV_2026_10_14.md: srv signs at the origin for the agent the
780    // request's token names (`wan_signer`). Any unmet condition relays unsigned; the reason rides
781    // on the "queued" log line so the receiver can tell it from a sender that never signed.
782    // `directory` is this relay plus the credential's account.
783    let directory = Some(credential.account_sub.as_str())
784        .filter(|sub| !sub.is_empty())
785        .map(|sub| crate::muxbus::wan_publish::directory_id(&crate::muxbus::relay::rest_base_url(), sub));
786    let (carried, unsigned_reason) = match crate::muxbus::relay::wan_sign_at_origin(
787        req,
788        super::actor::wan_signer(&state.mstore, caller_uid, req),
789        state.mstore.wan_identity().as_deref(),
790        directory.as_deref(),
791        &crate::backend::reactive::registry::local_channel_id(),
792        agentmux_common::time::now_secs(),
793    ) {
794        Ok(carried) => (Some(carried), ""),
795        Err(reason) => (None, reason),
796    };
797    let outcome = crate::muxbus::relay::relay_inject(
798        &crate::muxbus::relay::rest_base_url(),
799        &state.http_client,
800        &credential.token,
801        source,
802        &req.target_agent,
803        &req.message,
804        priority,
805        carried.as_ref(), req.cloud_files.as_deref(), req.jekt_tier.as_ref(), req.expires_at_ms,
806    )
807    .await;
808
809    match outcome {
810        crate::muxbus::relay::RelayOutcome::Queued { injection_id, target_in_account } => {
811            let request_id = injection_id.unwrap_or_default();
812            tracing::info!(
813                target = %req.target_agent,
814                injection_id = %request_id,
815                signed = carried.is_some(),
816                unsigned_reason,
817                // The relay answers with an `inj-w-` id when it kept a valid
818                // carried tuple; any other id means the message travels
819                // unsigned, including when it dropped a tuple as invalid.
820                cloud_kept_signature = request_id.starts_with("inj-w-"),
821                "cloud relay: queued for WAN delivery"
822            );
823            echo_jekt_to_sender_with_files(
824                state,
825                Some(source),
826                &req.target_agent,
827                &req.message,
828                &request_id,
829                None, // no receiver-side escalation to mirror: nobody has
830                None, // seen the message yet, so neither field is known
831                EchoTrust {
832                    delivery_tier: "wan",
833                    // Signing here is #2586's unbuilt WAN half: an outbound relay carries no proof
834                    // of sender identity, and claiming one would put a TRUST value on the marker
835                    // the receiver won't agree with.
836                    sig_verified: None,
837                    reagent_verified: None,
838                    lan_verified: None,
839                    channel_verified: None,
840                },
841                priority, req.files_delivery.as_ref(),
842            );
843            // Watched for the sender's sake: a message nobody picks up is reported, not forgotten
844            // (muxbus::relay_watch). The LAN peers go in the answer: the target is on none of them.
845            crate::muxbus::relay_watch::watch(state.reactive_handler, source, &req.target_agent, &request_id);
846            let peers = state.lan_discovery.get_instances().iter().map(crate::backend::lan::peer_words::describe_peer).collect();
847            let body = super::name_resolution::with_did_you_mean(state, &req.target_agent, crate::muxbus::relay_watch::queued_answer(request_id.clone(), target_in_account, peers, now_unix_secs().max(0) as u64)).await;
848            Some(flow_notes::queued(state, req, &request_id, body))
849        }
850        crate::muxbus::relay::RelayOutcome::Failed(e) => {
851            tracing::warn!(
852                target = %req.target_agent,
853                error = %e,
854                signed = carried.is_some(),
855                unsigned_reason,
856                "cloud relay failed"
857            );
858            None
859        }
860    }
861}
862
863pub(super) async fn handle_reactive_agents(
864    State(state): State<AppState>,
865) -> Json<serde_json::Value> {
866    let agents = state.reactive_handler.list_agents();
867    Json(serde_json::to_value(&agents).unwrap_or(json!([])))
868}
869
870/// Agent NAMES only, for LAN peers: not [`handle_reactive_agents`], whose
871/// full `AgentRegistration` records (`block_id`, `tab_id`, `registration_nonce`,
872/// ...) are routing details that stay behind full auth.
873///
874/// Reachable with the broadcast `lan_key` (`lan_or_full_auth_middleware`), so
875/// its output is public to anyone on the local network. **Do not extend it**
876/// without the owner's decision.
877///
878/// Built by [`crate::backend::lan::discovery::agent_names_body`], which lists
879/// the fields and the decision behind each.
880pub(super) async fn handle_reactive_agent_names(
881    State(state): State<AppState>,
882) -> Json<serde_json::Value> {
883    let settings = state.config_watcher.get_full_config();
884    let agents = state.reactive_handler.list_agents();
885    let account_of_block = crate::identity::stable_account::stable_id_of_block(&state.mstore, &state.id_store, &state.identity_store);
886    Json(crate::backend::lan::discovery::agent_names_body(&state.mstore, &settings.settings, &agents, account_of_block))
887}
888
889#[derive(serde::Deserialize)]
890pub(super) struct AgentQuery {
891    id: Option<String>,
892}
893
894pub(super) async fn handle_reactive_agent(
895    State(state): State<AppState>,
896    Query(params): Query<AgentQuery>,
897) -> Response {
898    let id = match &params.id {
899        Some(id) if !id.is_empty() => id.as_str(),
900        _ => {
901            return (
902                StatusCode::BAD_REQUEST,
903                Json(json!({"error": "missing id param"})),
904            )
905                .into_response()
906        }
907    };
908    if let Some(sender) = crate::backend::lan::swarm_broadcast::sender_lookup(&state.mstore, &state.hostname, id) { return Json(lan_continuity::with_sender_cert(&state, sender)).into_response(); }
909    match state.reactive_handler.get_delivery_target(id) {
910        Some(agent) => {
911            // Merged in, not part of AgentRegistration's serialization: the LAN pubkey-lookup half
912            // of docs/specs/SPEC_JEKT_LAN_TIER_SIGNING_2026_08_15.md §2.2. A public key isn't
913            // secret, and this route is already gated by lan_or_full_auth_middleware. Omitted
914            // entirely (not `null`) when no LAN key is minted yet, so existing callers see no
915            // change in shape.
916            let mut value = serde_json::to_value(&agent).unwrap_or_default();
917            if let Some(obj) = value.as_object_mut() {
918                obj.insert("jekt_features".into(), json!([agentmux_common::jekt_files::FEATURE]));
919            }
920            if let Ok(Some(pubkey)) = state.mstore.agent_lan_public_key_load(id) {
921                if let Some(obj) = value.as_object_mut() {
922                    obj.insert("lan_public_key".to_string(), json!(pubkey));
923                    lan_continuity::add_cert(&state, id, &pubkey, obj); // so a peer pinned to an older key can move its pin
924                }
925            }
926            // Identity M4d-5: the registration's UID key, separately; the
927            // name-keyed key above stays the query id's (spec §6.5.10).
928            if let Some(Ok(Some(pubkey))) = agent.uid.as_deref().map(|uid| state.mstore.agent_uid_lan_public_key_load(uid)) {
929                if let Some(obj) = value.as_object_mut() {
930                    obj.insert("uid_public_key".to_string(), json!(pubkey));
931                }
932            }
933            // A former slug: its agent's current name and key (`former_slug`).
934            former_slug::renamed_lookup(&state, id, &mut value);
935            Json(value).into_response()
936        }
937        None => (
938            StatusCode::NOT_FOUND,
939            Json(json!({"error": "agent not found"})),
940        )
941            .into_response(),
942    }
943}
944
945#[derive(serde::Deserialize)]
946pub(super) struct AuditQuery {
947    #[serde(default = "default_audit_limit")]
948    limit: usize,
949}
950fn default_audit_limit() -> usize {
951    100
952}
953
954pub(super) async fn handle_reactive_audit(
955    State(state): State<AppState>,
956    Query(params): Query<AuditQuery>,
957) -> Json<serde_json::Value> {
958    let log = state.reactive_handler.get_audit_log(params.limit);
959    Json(serde_json::to_value(&log).unwrap_or(json!([])))
960}
961
962#[derive(serde::Deserialize)]
963pub(super) struct EnsureSigningKeyRequest {
964    agent_id: String,
965}
966
967/// Mints or reuses `agent_id`'s host-tier jekt signing key and returns it base64-encoded: the value
968/// `agent_config::inject_jekt_signing_keys_into_mcp_json` writes into a real agent's `.mcp.json` at
969/// spawn, exposed here so tests and external harnesses can exercise host-tier signing without
970/// `agent.open`'s WebSocket path, which also spawns a live provider session.
971///
972/// **Disabled unless `AGENTMUX_ENABLE_TEST_ENDPOINTS=1` was set in the srv process's own
973/// environment at start** (#2635). `X-AuthKey` is not enough: it is injected into every spawned
974/// agent's env (`agent_handlers/input.rs`), so any agent holds it, and returning another agent's
975/// raw key would be exfiltration enabling impersonation, breaking the invariant
976/// `agent_jekt_keys.rs` documents (a key goes only to its own agent, by its identity token) and
977/// `TRUST=host-verified`. Nothing in the request can prove the caller IS `agent_id` (that is the
978/// problem host-tier signing solves, so leaning on it is circular); the env flag is set by whoever
979/// launches the instance, which a running agent's tool calls can't do. Off by default, on only for
980/// an isolated test instance of synthetic agents.
981pub(super) async fn handle_reactive_ensure_signing_key(
982    State(state): State<AppState>,
983    Json(req): Json<EnsureSigningKeyRequest>,
984) -> Response {
985    if std::env::var("AGENTMUX_ENABLE_TEST_ENDPOINTS").as_deref() != Ok("1") {
986        return (
987            StatusCode::NOT_FOUND,
988            Json(json!({"error": "not found"})),
989        )
990            .into_response();
991    }
992    match state.mstore.agent_jekt_key_ensure(&req.agent_id) {
993        Ok(key) => {
994            use base64::Engine as _;
995            let key_b64 = base64::engine::general_purpose::STANDARD.encode(&key);
996            Json(json!({ "agent_id": req.agent_id, "jekt_key_b64": key_b64 })).into_response()
997        }
998        Err(e) => (
999            StatusCode::INTERNAL_SERVER_ERROR,
1000            Json(json!({"error": e.to_string()})),
1001        )
1002            .into_response(),
1003    }
1004}
1005
1006#[derive(serde::Deserialize)]
1007pub(super) struct UnregisterRequest {
1008    pub(super) agent_id: String,
1009    /// Identity M2 (spec §4.4.4 Q7): optional, but both frontend callers
1010    /// send it. With it, teardown is by block. Without it, a name held by
1011    /// several live blocks is refused with HTTP 409 and the candidates —
1012    /// never a `success: true` that tore down nothing (§10 constraint 3).
1013    #[serde(default)]
1014    pub(super) block_id: String,
1015}
1016
1017/// Tear down a pane's registration. Reached only from the window's own socket (`agent.pane.unregister`)
1018/// and, for an agent's own pane, from `pane_binding::handle_unregister`.
1019pub(super) async fn unregister_pane(state: &AppState, req: UnregisterRequest) -> Response {
1020    use crate::backend::reactive::handler::UnregisterOutcome;
1021
1022    let (block_id, names): (Option<String>, Vec<String>) = if !req.block_id.trim().is_empty() {
1023        let names = state.reactive_handler.unregister_block(req.block_id.trim());
1024        (Some(req.block_id.trim().to_string()), names)
1025    } else {
1026        match state.reactive_handler.unregister_agent(&req.agent_id) {
1027            UnregisterOutcome::Removed { block_id, names } => (Some(block_id), names),
1028            UnregisterOutcome::NotFound => (None, Vec::new()),
1029            UnregisterOutcome::Ambiguous(candidates) => {
1030                let candidates: Vec<serde_json::Value> = candidates
1031                    .iter()
1032                    .map(
1033                        |c| json!({ "uid": c.uid, "block_id": c.block_id, "agent_id": c.agent_id }),
1034                    )
1035                    .collect();
1036                return (
1037                    StatusCode::CONFLICT,
1038                    Json(json!({
1039                        "success": false,
1040                        "error": format!(
1041                            "ambiguous agent name: '{}' is held by {} live agents; pass block_id",
1042                            req.agent_id,
1043                            candidates.len()
1044                        ),
1045                        "candidates": candidates,
1046                    })),
1047                )
1048                    .into_response();
1049            }
1050        }
1051    };
1052
1053    // Name-keyed side state is torn down for EVERY name the block held (display and stable). The
1054    // caller's name is used only when no block was found at all (the pre-M2 behaviour for an
1055    // unknown name): a torn-down block's own bindings are authoritative, since the caller's name
1056    // may be a stale display value another live block now holds, and removing that block's file
1057    // entry and cloud subscription would knock it off cross-instance routing.
1058    let mut all_names = names.clone();
1059    if block_id.is_none() {
1060        all_names.push(req.agent_id.clone());
1061    }
1062    let data_dir = base::get_mux_data_dir();
1063    for name in &all_names {
1064        // Also remove from cross-instance file registry.
1065        agent_registry::remove(&data_dir, name);
1066        // And from the host-global shared registry (Tier 2b).
1067        agent_registry::remove_shared_from_env(name);
1068        // Drop the subagent filesystem watcher (handle, channel, task): the symmetric teardown for
1069        // `watch_agent()` in the register handler. `block_id` lets a watcher shared with another
1070        // still-open block survive this one's teardown.
1071        state.subagent_watcher.unwatch_agent(name, block_id.as_deref());
1072        // Notify cloud subscriber so it stops subscribing for this agent
1073        if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
1074            sub.remove_agent(name);
1075        }
1076    }
1077
1078    // Symmetric refresh: tell the Swarm view this pane is gone.
1079    if let Some(bid) = block_id {
1080        state.broker.publish_event::<crate::backend::mps_events::AgentReactiveUnregistered>(&crate::backend::mps_events::BlockRefEvent { block_id: bid.to_string() }, vec![format!("block:{}", bid)], 0);
1081    }
1082
1083    Json(json!({"success": true})).into_response()
1084}
1085
1086pub(super) async fn handle_reactive_poller_stats(
1087    State(state): State<AppState>,
1088) -> Json<serde_json::Value> {
1089    let stats = state.poller.stats();
1090    Json(serde_json::to_value(&stats).unwrap_or(json!({})))
1091}
1092
1093#[derive(serde::Deserialize)]
1094pub(super) struct PollerConfigRequest {
1095    url: Option<String>,
1096    token: Option<String>,
1097}
1098
1099pub(super) async fn handle_reactive_poller_config(
1100    State(state): State<AppState>,
1101    Json(req): Json<PollerConfigRequest>,
1102) -> Json<serde_json::Value> {
1103    state.poller.reconfigure(req.url, req.token);
1104    Json(json!({"success": true}))
1105}
1106
1107pub(super) async fn handle_reactive_poller_status(
1108    State(state): State<AppState>,
1109) -> Json<serde_json::Value> {
1110    let status = state.poller.status();
1111    Json(serde_json::to_value(&status).unwrap_or(json!({})))
1112}
1113
1114/// Server-side ceiling on `max_lines`, so a transcript pull can't read a huge session file
1115/// unbounded. This route is a "recent tail" primitive, not a full-history export.
1116const TRANSCRIPT_MAX_LINES_CAP: usize = 500;
1117
1118#[derive(serde::Deserialize)]
1119pub(super) struct TranscriptQuery {
1120    agent: String,
1121    #[serde(default = "default_transcript_max_lines")]
1122    max_lines: usize,
1123    /// Set ONLY by [`handle_reactive_transcript_cross_channel`] on its single forwarded request,
1124    /// capping cross-channel resolution at one hop. Without it a stale-but-PID-alive
1125    /// shared-registry entry (pointing back at this instance, or at a second whose entry points
1126    /// back here) would forward forever, the failure `handle_reactive_inject`'s `MAX_FORWARD_HOPS`
1127    /// prevents for jekts (#2715). A bool is enough, unlike inject's counter: the owning instance
1128    /// found via `lookup_all_shared` has the agent on its own host tier, never a further hop, so
1129    /// "already forwarded once" and "hop limit reached" are the same condition.
1130    #[serde(default)]
1131    forwarded: bool,
1132}
1133fn default_transcript_max_lines() -> usize {
1134    100
1135}
1136
1137/// `GET /agentmux/reactive/transcript?agent=<name>&max_lines=<n>`: the tail of a registered agent's
1138/// session output (the `Agents` tool's `transcript` action). A pull primitive; nothing is pushed.
1139///
1140/// As of SPEC_MUXSPECT_CROSS_TIER_CONVERSATION_VISIBILITY_2026_08_21.md Phase A, a miss on this
1141/// instance's host-tier registry falls back to the host-global cross-channel registry and forwards
1142/// a single-hop GET to the owning channel's instance, with the same auth (`entry.auth_key` as
1143/// `X-AuthKey`) and loopback-only pattern as `handle_reactive_inject`'s Tier 2b. The response's
1144/// `"tier"` says which tier answered.
1145pub(super) async fn handle_reactive_transcript(
1146    State(state): State<AppState>,
1147    Query(params): Query<TranscriptQuery>,
1148) -> Response {
1149    if params.agent.is_empty() {
1150        return (
1151            StatusCode::BAD_REQUEST,
1152            Json(json!({"error": "missing agent param"})),
1153        )
1154            .into_response();
1155    }
1156
1157    let reg = match state.reactive_handler.lookup_delivery_target(&params.agent) {
1158        crate::backend::reactive::handler::LookupOutcome::One(reg) => reg,
1159        // Identity M2 (spec §4.4.3): a name several live blocks hold is a purely LOCAL collision:
1160        // refuse it with the candidates, never fall through to cross-channel forwarding as if it
1161        // were unknown.
1162        crate::backend::reactive::handler::LookupOutcome::Ambiguous(candidates) => {
1163            let candidates: Vec<serde_json::Value> = candidates
1164                .iter()
1165                .map(|c| json!({ "uid": c.uid, "block_id": c.block_id, "agent_id": c.agent_id }))
1166                .collect();
1167            return (
1168                StatusCode::CONFLICT,
1169                Json(json!({
1170                    "error": format!(
1171                        "ambiguous agent name: '{}' is held by {} live agents; address one by uid",
1172                        params.agent,
1173                        candidates.len()
1174                    ),
1175                    "candidates": candidates,
1176                })),
1177            )
1178                .into_response();
1179        }
1180        crate::backend::reactive::handler::LookupOutcome::NotFound => {
1181            if params.forwarded {
1182                // Already one hop in (see `TranscriptQuery::forwarded`): the owning instance's
1183                // host-tier lookup missed too, so the agent isn't registered anywhere reachable.
1184                // 404, no second forward.
1185                return (
1186                    StatusCode::NOT_FOUND,
1187                    Json(json!({"error": "agent not found"})),
1188                )
1189                    .into_response();
1190            }
1191            return handle_reactive_transcript_cross_channel(&state, &params).await;
1192        }
1193    };
1194    let block_id = reg.block_id.clone();
1195
1196    // A bounded tail, off the async workers (transcript_tail.rs): the file can be hundreds of MB.
1197    let requested = params.max_lines.min(TRANSCRIPT_MAX_LINES_CAP).max(1);
1198    let (mstore, filestore, bid) = (state.mstore.clone(), state.filestore.clone(), block_id.clone());
1199    let read = tokio::task::spawn_blocking(move || super::transcript_tail::tail_lines_for_readers(&mstore, &filestore, &bid, requested)).await;
1200    let (lines, truncated) = match read {
1201        Ok(Ok(t)) => (t.lines, t.truncated),
1202        Ok(Err(e)) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("read_session_output: {e}")}))).into_response(),
1203        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": format!("transcript read: {e}")}))).into_response(),
1204    };
1205
1206    let turn_active = crate::backend::blockcontroller::get_block_controller_status(&block_id)
1207        .map(|s| s.turn_active)
1208        .unwrap_or(false);
1209
1210    Json(json!({
1211        "agent": reg.agent_id,
1212        "block_id": block_id,
1213        "tier": "host",
1214        "turn_active": turn_active,
1215        "lines": lines,
1216        "truncated": truncated,
1217    }))
1218    .into_response()
1219}
1220
1221/// Fallback for [`handle_reactive_transcript`] when the agent isn't in this instance's host-tier
1222/// registry: looks in the host-global cross-channel registry and, on a hit, forwards to the owning
1223/// channel's instance. A miss on every channel of this host 404s as the host-only lookup always
1224/// did; it does not reach LAN or WAN (Phase A scope).
1225async fn handle_reactive_transcript_cross_channel(
1226    state: &AppState,
1227    params: &TranscriptQuery,
1228) -> Response {
1229    let known = crate::backend::agent_resolve::resolve_agent_id(&state.mstore, &params.agent).is_ok();
1230    let not_found = || {
1231        (StatusCode::NOT_FOUND, Json(json!({ "error": former_slug::transcript_not_found_error(known, &params.agent) }))).into_response()
1232    };
1233
1234    let Some(shared_dir) = crate::registry::resolve_shared_reactive_dir() else {
1235        return not_found();
1236    };
1237    // Skip any entry pointing back at THIS instance before picking one: a stale-but-PID-alive
1238    // self-registration (the registration race or incomplete cleanup, #2715) would forward the
1239    // request to ourselves and re-enter this function, including when it is merely the FRESHEST of
1240    // several candidates (the same defence as `handle_reactive_inject`'s Tier 2b).
1241    // `TranscriptQuery::forwarded` still caps it at one hop in a multi-instance cycle this filter
1242    // can't catch (A's entry points to B, B's back to A).
1243    // A former slug's agent is registered, and asked for, under its current one.
1244    let alias = former_slug::owner(state, &params.agent).map(|o| o.slug);
1245    let (agent, entries) = former_slug::shared_entries(&shared_dir, &params.agent, alias.as_deref());
1246    let Some(entry) = entries.into_iter().find(|e| !is_self_registration(&e.local_url, &state.local_web_url)) else {
1247        return not_found();
1248    };
1249
1250    let query: Vec<(&str, String)> = vec![
1251        ("agent", agent),
1252        ("max_lines", params.max_lines.to_string()),
1253        ("forwarded", "true".to_string()),
1254    ];
1255    let resp = state
1256        .http_client
1257        .get(format!("{}/agentmux/reactive/transcript", entry.local_url))
1258        .header(AUTH_KEY_HEADER, &entry.auth_key)
1259        .query(&query)
1260        .send()
1261        .await;
1262
1263    let Ok(resp) = resp else {
1264        return not_found();
1265    };
1266    if !resp.status().is_success() {
1267        return not_found();
1268    }
1269    let Ok(mut body) = resp.json::<serde_json::Value>().await else {
1270        return not_found();
1271    };
1272    if let Some(obj) = body.as_object_mut() {
1273        obj.insert("tier".to_string(), json!("cross-channel"));
1274        obj.insert("channel".to_string(), json!(entry.channel));
1275    }
1276    Json(body).into_response()
1277}
1278
1279#[cfg(test)]
1280#[path = "tests/reactive/transcript_cross_channel_tests.rs"]
1281mod transcript_cross_channel_tests;
1282
1283/// Default/cap for how many of an agent's sessions one search may open
1284/// (SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md). Full-parsing every session of a long-lived agent
1285/// isn't viable (the session that motivated the spec was 14.7 MB / 6682 records, one of several),
1286/// so candidates are taken newest-first and the default answers "what did I do recently".
1287const HISTORY_SEARCH_DEFAULT_MAX_SESSIONS: usize = 20;
1288const HISTORY_SEARCH_MAX_SESSIONS_CAP: usize = 100;
1289const HISTORY_SEARCH_DEFAULT_LIMIT: usize = 50;
1290const HISTORY_SEARCH_LIMIT_CAP: usize = 200;
1291/// How long a history search may read sessions before it answers with what it has: the client that asks gives up
1292/// after 10 seconds, and a partial answer with a hint to narrow is worth more than that timeout.
1293const HISTORY_SEARCH_BUDGET: std::time::Duration = std::time::Duration::from_secs(6);
1294
1295/// SearchHistory's answer to a request that carries no per-agent token.
1296const HISTORY_SEARCH_NEEDS_IDENTITY: &str = "history.search: this request carries no agent identity \
1297     (X-Agent-Token), so whose history to search is unknown. Every agent AgentMux spawns carries \
1298     one; a process started some other way, or an agent from before identity tokens, must be \
1299     reopened from AgentMux.";
1300
1301fn default_history_max_sessions() -> usize {
1302    HISTORY_SEARCH_DEFAULT_MAX_SESSIONS
1303}
1304fn default_history_limit() -> usize {
1305    HISTORY_SEARCH_DEFAULT_LIMIT
1306}
1307
1308#[derive(serde::Deserialize)]
1309pub(super) struct HistorySearchQuery {
1310    /// The caller's name, as the MCP sends it. **Never whose history is searched**: that is the row
1311    /// of the caller's per-agent token (`X-Agent-Token`, identity M4c-2c,
1312    /// SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md §6.5.9), and a request without one is
1313    /// refused. A name is self-declared (every local agent shares the instance `auth_key`), so
1314    /// resolving the owner from it could only guess, and a guess answered "no history" with
1315    /// confidence. Kept for the actor counters (M4a-2).
1316    #[serde(default)]
1317    agent: String,
1318    query: String,
1319    #[serde(default)]
1320    role: Option<String>,
1321    #[serde(default)]
1322    tool: Option<String>,
1323    #[serde(default)]
1324    since: Option<i64>,
1325    #[serde(default)]
1326    until: Option<i64>,
1327    #[serde(default = "default_history_max_sessions")]
1328    max_sessions: usize,
1329    #[serde(default = "default_history_limit")]
1330    limit: usize,
1331    /// Also search sessions found only by working directory or account,
1332    /// which the agent's own record doesn't name.
1333    #[serde(default)]
1334    include_inferred: bool,
1335}
1336
1337/// `GET /agentmux/reactive/history/search`: search an agent's own past conversations
1338/// (SPEC_AGENT_HISTORY_SEARCH_2026_09_17.md). Unlike `/reactive/transcript` (the live session's
1339/// tail), it reads sessions persisted on disk, including ended ones: after a compaction or session
1340/// reset an agent answers questions about its own past confidently and wrongly, with nothing
1341/// marking the boundary.
1342pub(super) async fn handle_reactive_history_search(
1343    State(state): State<AppState>,
1344    caller: Option<Extension<super::caller::Caller>>,
1345    Query(params): Query<HistorySearchQuery>,
1346) -> Response {
1347    super::actor::check_actor(
1348        &state,
1349        caller.as_deref(),
1350        super::actor::ActorSite::HistorySearch,
1351        Some(params.agent.as_str()).filter(|a| !a.trim().is_empty()),
1352    );
1353    // An empty query makes sense only with a `tool` filter ("every call to X"); alone it would
1354    // match everything and return a truncated firehose that reads as a real answer.
1355    if params.query.trim().is_empty() && params.tool.is_none() {
1356        return (
1357            StatusCode::BAD_REQUEST,
1358            Json(json!({"error": "query must be non-empty unless a tool filter is given"})),
1359        )
1360            .into_response();
1361    }
1362    if let Some(role) = params.role.as_deref() {
1363        if role != "user" && role != "assistant" {
1364            return (
1365                StatusCode::BAD_REQUEST,
1366                Json(json!({"error": "role must be 'user' or 'assistant'"})),
1367            )
1368                .into_response();
1369        }
1370    }
1371
1372    let started = std::time::Instant::now();
1373    let opts = crate::backend::history::index::HistorySearchOptions {
1374        query: params.query.clone(),
1375        role: params.role.clone(),
1376        tool: params.tool.clone(),
1377        limit: params.limit.clamp(1, HISTORY_SEARCH_LIMIT_CAP),
1378        since_ms: params.since.map(crate::backend::history::unix_time_to_ms),
1379        until_ms: params.until.map(crate::backend::history::unix_time_to_ms),
1380        max_sessions: Some(params.max_sessions.clamp(1, HISTORY_SEARCH_MAX_SESSIONS_CAP)),
1381        include_inferred: params.include_inferred,
1382        deadline: Some(started + HISTORY_SEARCH_BUDGET),
1383    };
1384
1385    // Identity M4c-2c (spec §6.5.9): the owner is the caller's own row, from its per-agent token,
1386    // never a name. A request without one can't say whose history it is, and resolving a
1387    // self-declared name could only guess (on 2026-09-24 a guess answered "no history" for an agent
1388    // whose sessions were on disk).
1389    let Some(uid) = caller.as_deref().and_then(super::caller::Caller::uid) else {
1390        crate::backend::agent_resolve::record_uid_fallback("history.search_refused_unattributed");
1391        return (
1392            StatusCode::FORBIDDEN,
1393            Json(json!({"error": HISTORY_SEARCH_NEEDS_IDENTITY})),
1394        )
1395            .into_response();
1396    };
1397    let row = match super::app_api::SelfOwner::caller_row(uid, &state.mstore) {
1398        Ok(row) => row,
1399        Err(e) => {
1400            // A gone row is the caller's problem; a store fault is ours.
1401            let status = if e.to_string().starts_with("store:") {
1402                StatusCode::INTERNAL_SERVER_ERROR
1403            } else {
1404                StatusCode::BAD_REQUEST
1405            };
1406            return (status, Json(json!({"error": format!("history.search: {e}")})))
1407                .into_response();
1408        }
1409    };
1410
1411    // Parsing sessions is blocking filesystem work: keep it off the async workers.
1412    let history = state.history_service.clone();
1413    let store = state.identity_store.clone();
1414    let result = tokio::task::spawn_blocking(move || {
1415        let owner = crate::backend::history::HistoryOwner::of_row(&row);
1416        history.search_for_agent(&store, &owner, &opts)
1417    })
1418    .await;
1419
1420    match result {
1421        Ok(Ok(outcome)) => (StatusCode::OK, Json(json!(outcome))).into_response(),
1422        // Retryable, and distinct from a fault: an index still building is
1423        // not an empty history.
1424        Ok(Err(crate::backend::history::HistorySearchError::IndexBuilding)) => (
1425            StatusCode::SERVICE_UNAVAILABLE,
1426            [(axum::http::header::RETRY_AFTER, "30")],
1427            Json(json!({"error": crate::backend::history::HISTORY_INDEX_BUILDING})),
1428        )
1429            .into_response(),
1430        Ok(Err(e)) => (
1431            StatusCode::INTERNAL_SERVER_ERROR,
1432            Json(json!({"error": e.to_string()})),
1433        )
1434            .into_response(),
1435        Err(e) => (
1436            StatusCode::INTERNAL_SERVER_ERROR,
1437            Json(json!({"error": format!("history search task failed: {e}")})),
1438        )
1439            .into_response(),
1440    }
1441}
1442
1443// ---- WS RPC: reactive.registrations (issue #2696, Stash UI indicator) ----
1444
1445/// Whether a host-global shared-registry entry is THIS instance's own registration. Every agent
1446/// writes itself into that registry, so a "registered elsewhere" listing must exclude its own entry
1447/// or it fires on every healthy agent (#2698). Same comparison as Tier 2a/2b forwarding.
1448pub(super) fn is_self_registration(entry_local_url: &str, this_instances_local_url: &str) -> bool {
1449    entry_local_url == this_instances_local_url
1450}
1451
1452/// One cross-instance/channel entry from the host-global shared registry
1453/// (`backend::reactive::registry::AgentEntry`), narrowed to what the frontend needs for a
1454/// "registered elsewhere too" badge: `local_url`/`auth_key` are internal forwarding plumbing and
1455/// stay out.
1456#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
1457#[ts(export, export_to = "../../../frontend/types/rpc/")]
1458pub(super) struct RemoteRegistrationEntry {
1459    channel: String,
1460    // u32 is < 2^53 so ts-rs maps it to `number` already; only 64-bit
1461    // integers become `bigint`. See updated_at below.
1462    pid: u32,
1463    #[ts(type = "number")]
1464    updated_at: u64,
1465}
1466
1467/// The most recent `identity-mismatch` audit entry for this agent_id, if any (#2695's
1468/// `Handler::inject_message_inner` check), narrowed to what the Stash badge needs.
1469#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
1470#[ts(export, export_to = "../../../frontend/types/rpc/")]
1471pub(super) struct MismatchAuditSummary {
1472    #[ts(type = "number")]
1473    timestamp: u64,
1474    block_id: String,
1475    error_message: Option<String>,
1476}
1477
1478#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
1479#[ts(export, export_to = "../../../frontend/types/rpc/")]
1480pub(super) struct ReactiveRegistrationsResult {
1481    /// This instance's own registration for the agent, if any: the same data as
1482    /// `GET /agentmux/reactive/agent`, reused so the frontend makes one call instead of two.
1483    local: Option<AgentRegistration>,
1484    /// Every OTHER instance/channel on this host claiming this agent_id, freshest first. A
1485    /// non-empty list is the risk signal the Stash badge surfaces (#2694's root cause was two
1486    /// panes racing to hold one agent_id).
1487    remote: Vec<RemoteRegistrationEntry>,
1488    recent_mismatch: Option<MismatchAuditSummary>,
1489}
1490
1491#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
1492#[ts(export, export_to = "../../../frontend/types/rpc/")]
1493pub(super) struct ReactiveRegistrationsParams {
1494    pub agent_id: String,
1495}
1496
1497/// Registers `reactive.registrations`, called by the Stash "Registration" tab
1498/// (`frontend/app/store/rpc-api/reactive.ts`) to answer "is this agent's jekt identity healthy
1499/// right now": where it's registered locally, whether any OTHER instance/channel on this host
1500/// also claims the same agent_id (the collision #2694 fixed one cause of), and whether a recent
1501/// delivery hit the #2695 identity-mismatch guard.
1502pub fn register_reactive_ws_handlers(engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>, state: &AppState) {
1503    let state = state.clone();
1504    // Typed registration (SPEC_RPC_BINDINGS_CODEGEN_2026_09_07.md §3.1): the params/result
1505    // structs derive `ts_rs::TS`, so the frontend consumes generated bindings, not
1506    // hand-written interfaces.
1507    registration_flags::register(engine, state.clone());
1508    engine.register_typed(
1509        "reactive.registrations",
1510        move |params: ReactiveRegistrationsParams, _ctx| {
1511            let state = state.clone();
1512            async move {
1513
1514                let local = state.reactive_handler.get_agent(&params.agent_id);
1515
1516                let (remote, recent_mismatch) = registration_flags::problems_of(&state, &local, &params.agent_id);
1517                let result = ReactiveRegistrationsResult {
1518                    local,
1519                    remote,
1520                    recent_mismatch,
1521                };
1522                Ok(result)
1523            }
1524        },
1525    );
1526}
1527
1528/// `verify_jekt_signature` unit tests (SPEC_JEKT_TRUST_LAYER_COMPLETION_2026_08_13.md §2.2,
1529/// #2565). They test the extracted function directly, not the full `handle_inject` / websocket
1530/// handlers: `server::tests::test_state()`'s `reactive_handler` is a global singleton shared by
1531/// every test in the binary (`backend_reactive::get_global_handler()`), so exercising it end to
1532/// end risks cross-test interference on shared agent registrations. `verify_jekt_signature`
1533/// touches only `state.mstore` (key lookup), so it is safe in isolation, and it is the logic
1534/// that was fixed; the two call sites (messagebus.rs, websocket.rs) are a one-line "call this
1535/// before inject_message" wiring.
1536#[cfg(test)]
1537#[path = "tests/reactive/verify_jekt_signature_tests.rs"]
1538mod verify_jekt_signature_tests;
1539
1540/// `verify_reagent_signature` unit tests (#41): `InjectionRequest` declared `reagent_sig` /
1541/// `reagent_key_id` as deserializable fields, but nothing on the HTTP
1542/// `/agentmux/reactive/inject` path verified them, so a reagent-signed notification delivered
1543/// through `@agentmuxai/muxbus-client`'s `pollAndDeliverInjections` arrived unsigned in effect.
1544#[cfg(test)]
1545#[path = "tests/reactive/verify_reagent_signature_tests.rs"]
1546mod verify_reagent_signature_tests;
1547
1548#[cfg(test)]
1549#[path = "tests/reactive/verify_lan_signature_tests.rs"]
1550mod verify_lan_signature_tests;
1551
1552#[cfg(test)]
1553#[path = "tests/reactive/registration_flags_tests.rs"]
1554mod registration_flags_tests;
1555
1556#[cfg(test)]
1557#[path = "tests/reactive/register_tests.rs"]
1558mod register_tests;
1559
1560/// SPEC_JEKT_CROSS_CHANNEL_TRUST_2026_09_02.md §9, the unit half of the test plan (items 1–8
1561/// and the D5 replay cases 9–10, driven through the verifier). Entries are written straight to
1562/// a temp shared-registry dir with an explicit public key, bypassing the process-global pubkey
1563/// resolver (a `OnceLock` owned by another test), so each test is hermetic and
1564/// order-independent.
1565#[cfg(test)]
1566#[path = "tests/reactive/verify_cross_channel_signature_tests.rs"]
1567mod verify_cross_channel_signature_tests;
1568
1569#[cfg(test)]
1570#[path = "tests/reactive/resolve_delivery_tier_tests.rs"]
1571mod resolve_delivery_tier_tests;
1572
1573#[cfg(test)]
1574#[path = "tests/reactive/is_self_registration_tests.rs"]
1575mod is_self_registration_tests;
1576
1577/// `forward_inject_to_peer` unit tests. They exercise the real HTTP path against a throwaway
1578/// loopback peer, not a mocked client, because the behaviour under test is the response
1579/// classification: which peer answers count as delivery, which as evidence the candidate is
1580/// stale, and which must never evict.
1581///
1582/// `source_agent` is `None` throughout so `echo_jekt_to_sender` returns at its first guard,
1583/// keeping these tests off the global singleton `reactive_handler` (see the
1584/// `verify_jekt_signature_tests` module comment).
1585#[cfg(test)]
1586#[path = "tests/reactive/forward_inject_tests.rs"]
1587mod forward_inject_tests;
1588
1589/// `deliver`'s forwarding tiers, end to end, against stub peers.
1590#[cfg(test)]
1591#[path = "tests/reactive/deliver_tiers_tests.rs"]
1592mod deliver_tiers_tests;
1593
1594/// PLAN_JEKT_LOCAL_FIRST_ROUTING_2026_10_02.md §5-§6: the relay's lease
1595/// answer as a route. Holding here is the default; only "another install
1596/// runs it" or an answer the relay cannot give plainly sends it to the relay.
1597#[cfg(test)]
1598#[path = "tests/reactive/absent_route_tests.rs"]
1599mod absent_route_tests;
1600
1601/// Tier-4 (cloud relay) gating tests: the decisions `try_cloud_relay` makes before it would
1602/// touch the network, the guards that keep it from firing when it must not. The wire contract
1603/// (headers, body shape, status handling) is tested against a stub relay in
1604/// `crate::muxbus::relay`'s own tests. A `test_state()` has no muxbus credential, so any path
1605/// that reaches token resolution returns `None` and no request is made; the tests assert `None`
1606/// rather than mock the relay, because the point is which guard stopped it, and each test
1607/// isolates one.
1608#[cfg(test)]
1609#[path = "tests/reactive/cloud_relay_gate_tests.rs"]
1610mod cloud_relay_gate_tests;
1611
1612/// Request-shape guard for `reactive.registrations` (typed-registration migration).
1613/// `register_typed` deserializes the payload BEFORE the handler runs, so the Req type must
1614/// accept exactly what the frontend stub sends. On `bookmarks.list` a unit Req compiled and
1615/// then rejected the stub's `{}` at runtime, because serde accepts `()` only from `null`
1616/// (#3293). Neither `tsc` nor `check-rpc-bindings.sh` catches that class (they verify
1617/// generated-type drift, not runtime payload shape), so every migrated command gets a test fed
1618/// the real payload.
1619#[cfg(test)]
1620#[path = "tests/reactive/reactive_registrations_req_tests.rs"]
1621mod reactive_registrations_req_tests;