meerkat-runtime 0.7.3

v9 runtime control-plane for Meerkat agent lifecycle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
//! Runtime-side impls of the cross-crate DSL handle traits defined in
//! `meerkat_core::handles`.
//!
//! Each handle holds an `Arc<std::sync::Mutex<mm_dsl::MeerkatMachineAuthority>>`
//! that points at the **session's real DSL authority** — the same instance
//! stored on [`crate::meerkat_machine::RuntimeSessionEntry::dsl_authority`].
//! All 5 handles for a given session share the same `Arc`, so transitions
//! fired through any handle land on the session's canonical DSL state.
//!
//! Sync `std::sync::Mutex` is used (not tokio's async lock) because the
//! [`meerkat_core::handles`] trait methods are sync. Shell code that already
//! mutates the session DSL authority under the `sessions` tokio lock takes the
//! same inner sync lock via [`HandleDslAuthority::apply_input`] /
//! [`HandleDslAuthority::apply_signal`]; locks are held briefly across a
//! single DSL transition, so contention is not a concern.
//!
//! Phase 5F/0 is a pure addition commit: these handles are constructed by
//! [`crate::meerkat_machine::MeerkatMachine::prepare_bindings`] and populated
//! on [`meerkat_core::SessionRuntimeBindings`], but no existing callsites
//! dispatch through them yet. Phases 5F/1-5 flip callsites to the new handles.

use std::sync::{
    Arc, Mutex,
    atomic::{AtomicBool, Ordering},
};

use crate::meerkat_machine::dsl as mm_dsl;
use crate::meerkat_machine_types::MeerkatMachineFieldlessRuntimeInternalInput;
use meerkat_core::handles::DslTransitionError;

/// Bridge the generated kernel's `MeerkatMachineTransitionError` into a
/// typed [`DslTransitionError`]. Keeps the `kind` field accurate so
/// callers that distinguish guard rejection from out-of-scope input
/// (e.g., realtime dispatchers firing idempotently) never need to
/// substring-match the rendered message.
fn map_kernel_error(
    err: mm_dsl::MeerkatMachineTransitionError,
    context: &'static str,
) -> DslTransitionError {
    let reason = err.to_string();
    match err {
        mm_dsl::MeerkatMachineTransitionError::GuardRejected { .. } => {
            DslTransitionError::guard_rejected(context, reason)
        }
        mm_dsl::MeerkatMachineTransitionError::NoMatchingTransition { .. } => {
            DslTransitionError::no_matching(context, reason)
        }
        mm_dsl::MeerkatMachineTransitionError::RecoveredStateInvariantRejected { .. } => {
            DslTransitionError::recovered_state_invariant_rejected(context, reason)
        }
    }
}

mod auth_lease;
mod comms_drain;
mod external_tool_surface;
mod interaction_stream;
mod mcp_server_lifecycle;
mod model_routing;
#[cfg(not(target_arch = "wasm32"))]
mod oauth_flow;
mod peer_comms;
mod peer_interaction;
mod session_admission;
mod session_claim;
mod session_context;
mod turn_state;

pub use auth_lease::RuntimeAuthLeaseHandle;
pub use comms_drain::RuntimeCommsDrainHandle;
pub use external_tool_surface::RuntimeExternalToolSurfaceHandle;
pub use interaction_stream::RuntimeInteractionStreamHandle;
pub use mcp_server_lifecycle::RuntimeMcpServerLifecycleHandle;
pub use model_routing::RuntimeModelRoutingHandle;
#[cfg(not(target_arch = "wasm32"))]
pub use oauth_flow::RuntimeOAuthFlowHandle;
pub use peer_comms::RuntimePeerCommsHandle;
pub use peer_interaction::RuntimePeerInteractionHandle;
pub use session_admission::RuntimeSessionAdmissionHandle;
pub use session_claim::RuntimeSessionClaimRegistry;
pub use session_context::RuntimeSessionContextHandle;
pub use turn_state::RuntimeTurnStateHandle;

/// Shared handle over a session's real `MeerkatMachineAuthority`.
///
/// Constructed from the session's
/// [`crate::meerkat_machine::RuntimeSessionEntry::dsl_authority`] `Arc`; cloned
/// into each of the 5 handle impls so all routes mutate the same underlying
/// authority.
///
/// A standalone ephemeral constructor ([`HandleDslAuthority::ephemeral`]) is
/// also provided for tests and minimal hosts that explicitly need
/// machine-owned semantics without a durable session authority. Ephemeral
/// authorities do not synchronize with any other state; transitions land on a
/// private initial DSL state only.
pub struct HandleDslAuthority {
    inner: Arc<Mutex<mm_dsl::MeerkatMachineAuthority>>,
    teardown_gate: Arc<HandleTeardownGate>,
}

/// Mechanical validity witness for a prepared session-owned handle bundle.
///
/// The generated MeerkatMachine remains the semantic lifecycle authority. This
/// gate only records whether the runtime owner has torn down the handle bundle
/// that was minted for one session epoch, so detached async holders fail closed
/// instead of applying through a stale `Arc<HandleDslAuthority>`.
pub(crate) struct HandleTeardownGate {
    closed: AtomicBool,
}

impl HandleTeardownGate {
    pub(crate) fn open() -> Arc<Self> {
        Arc::new(Self {
            closed: AtomicBool::new(false),
        })
    }

    pub(crate) fn close(&self) {
        self.closed.store(true, Ordering::Release);
    }

    fn ensure_open(&self, context: &'static str) -> Result<(), DslTransitionError> {
        if self.closed.load(Ordering::Acquire) {
            Err(DslTransitionError::no_matching(
                context,
                "session-owned runtime handle authority is closed by teardown",
            ))
        } else {
            Ok(())
        }
    }
}

impl HandleDslAuthority {
    /// Wrap an existing shared DSL authority. The returned handle and the
    /// caller's `Arc` both point at the same underlying authority instance.
    pub fn from_shared(inner: Arc<Mutex<mm_dsl::MeerkatMachineAuthority>>) -> Self {
        Self {
            inner,
            teardown_gate: HandleTeardownGate::open(),
        }
    }

    /// Wrap an existing shared DSL authority with a runtime-owned teardown gate.
    pub(crate) fn from_shared_with_teardown_gate(
        inner: Arc<Mutex<mm_dsl::MeerkatMachineAuthority>>,
        teardown_gate: Arc<HandleTeardownGate>,
    ) -> Self {
        Self {
            inner,
            teardown_gate,
        }
    }

    /// Construct a handle with its own ephemeral DSL authority at the
    /// generated initial state.
    ///
    /// Legacy callers without access to a session-owned authority use this for
    /// compile-time correctness of `SessionRuntimeBindings`. Transitions fired
    /// through a handle backed by this authority are not visible to any other
    /// session state.
    pub fn ephemeral() -> Self {
        Self {
            inner: Arc::new(Mutex::new(mm_dsl::MeerkatMachineAuthority::new())),
            teardown_gate: HandleTeardownGate::open(),
        }
    }

    /// Apply a DSL input under the shared authority's mutex.
    ///
    /// This is the shared authority entrypoint used by every intra-machine
    /// handle in `meerkat-runtime/src/handles/*`. Handles target the
    /// meerkat DSL directly — there is no route to resolve, so a
    /// `CompositionDispatcher` (the cross-machine seam closed by
    /// wave-c C-6c) is not applicable here. Routed inputs delivered by
    /// the `meerkat_mob_seam` dispatcher enter through
    /// [`crate::meerkat_machine::composition::MeerkatConsumerSurface::apply_routed_input`],
    /// not through this method.
    pub fn apply_input(
        &self,
        input: mm_dsl::MeerkatMachineInput,
        context: &'static str,
    ) -> Result<(), DslTransitionError> {
        // intra-machine: no route; dispatcher not applicable
        // (shared authority entrypoint; routed-effect delivery goes through
        // `MeerkatConsumerSurface`, not through this `apply_input`).
        self.apply_input_with_effects(input, context).map(|_| ())
    }

    /// Apply a DSL input and return the emitted effects.
    ///
    /// Handles that need to react to effect emission (e.g.,
    /// [`crate::handles::RuntimePeerInteractionHandle`] consuming
    /// `PeerInteractionCleanup` to drop shell-side channel projections)
    /// use this variant so the effect is observed under the same lock as
    /// the state update — the "terminal transition → effect → cleanup"
    /// chain is causal, not lexically adjacent.
    pub fn apply_input_with_effects(
        &self,
        input: mm_dsl::MeerkatMachineInput,
        context: &'static str,
    ) -> Result<Vec<mm_dsl::MeerkatMachineEffect>, DslTransitionError> {
        self.apply_input_with_transition(input, context)
            .map(|transition| transition.into_effects())
    }

    pub fn apply_input_with_transition(
        &self,
        input: mm_dsl::MeerkatMachineInput,
        context: &'static str,
    ) -> Result<mm_dsl::MeerkatMachineTransition, DslTransitionError> {
        MeerkatMachineFieldlessRuntimeInternalInput::reject_raw_dsl_input(&input)
            .map_err(|reason| DslTransitionError::no_matching(context, reason))?;
        self.teardown_gate.ensure_open(context)?;
        let mut guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.teardown_gate.ensure_open(context)?;
        mm_dsl::MeerkatMachineMutator::apply(&mut *guard, input)
            .map_err(|err| map_kernel_error(err, context))
    }

    /// Apply a DSL input, run `sample` on the emitted effects *while still
    /// holding the authority mutex*, and return the closure's result.
    ///
    /// The closure is the observer-sample seam: it runs inside the same
    /// critical section that committed the transition, so any observer
    /// slot the caller reads is totally ordered with respect to a
    /// concurrent `with_state_lock`-based installer. The caller fires the
    /// sampled observer AFTER this method returns (i.e., after the
    /// mutex has been released), which matters because observer
    /// callbacks typically re-enter the same authority via another
    /// handle method (e.g. `projection_advance_observed`) and the mutex
    /// is non-reentrant.
    ///
    /// Invariant closed by this method: a handle-local observer slot
    /// installed under `with_state_lock` sees no fires from transitions
    /// whose critical sections committed before its install — because
    /// the fire path samples the slot inside the same DSL-lock that
    /// committed the transition, and an installer running after the
    /// sample is ordered strictly after this transition's commit. The
    /// original post-lock-release observer read in the prior
    /// implementation allowed an install to interleave between commit
    /// and observer-read, so a just-installed observer saw a fire whose
    /// effect the installer's baseline had already captured — the race
    /// PR #286 attempted to close by construction.
    ///
    /// Lock order matches [`Self::apply_input_with_effects`] (DSL
    /// first); the closure may acquire handle-local locks it already
    /// nests inside the DSL lock elsewhere (e.g., the `observer:
    /// RwLock<Option<Weak<...>>>` slot) without deadlock.
    pub fn apply_input_with_effects_and_sample<S>(
        &self,
        input: mm_dsl::MeerkatMachineInput,
        context: &'static str,
        sample: impl FnOnce(&[mm_dsl::MeerkatMachineEffect]) -> S,
    ) -> Result<S, DslTransitionError> {
        MeerkatMachineFieldlessRuntimeInternalInput::reject_raw_dsl_input(&input)
            .map_err(|reason| DslTransitionError::no_matching(context, reason))?;
        self.teardown_gate.ensure_open(context)?;
        let mut guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.teardown_gate.ensure_open(context)?;
        let effects = mm_dsl::MeerkatMachineMutator::apply(&mut *guard, input)
            .map(|transition| transition.into_effects())
            .map_err(|err| map_kernel_error(err, context))?;
        Ok(sample(&effects))
    }

    /// Apply a DSL signal under the shared authority's mutex.
    pub fn apply_signal(
        &self,
        signal: mm_dsl::MeerkatMachineSignal,
        context: &'static str,
    ) -> Result<(), DslTransitionError> {
        self.apply_signal_with_effects(signal, context).map(|_| ())
    }

    /// Apply a DSL signal and return emitted effects.
    pub fn apply_signal_with_effects(
        &self,
        signal: mm_dsl::MeerkatMachineSignal,
        context: &'static str,
    ) -> Result<Vec<mm_dsl::MeerkatMachineEffect>, DslTransitionError> {
        self.teardown_gate.ensure_open(context)?;
        let mut guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.teardown_gate.ensure_open(context)?;
        guard
            .apply_signal(signal)
            .map(|transition| transition.into_effects())
            .map_err(|err| map_kernel_error(err, context))
    }

    /// Apply a DSL signal and sample state under the same authority mutex.
    pub fn apply_signal_and_sample<S>(
        &self,
        signal: mm_dsl::MeerkatMachineSignal,
        context: &'static str,
        sample: impl FnOnce(&mm_dsl::MeerkatMachineState) -> S,
    ) -> Result<S, DslTransitionError> {
        self.teardown_gate.ensure_open(context)?;
        let mut guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        self.teardown_gate.ensure_open(context)?;
        guard
            .apply_signal(signal)
            .map_err(|err| map_kernel_error(err, context))?;
        Ok(sample(guard.state()))
    }

    /// Clone the current DSL state under the shared authority's mutex.
    pub fn snapshot_state(&self) -> mm_dsl::MeerkatMachineState {
        let guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.state().clone()
    }

    /// Generated comms-trust freshness authority for peer-projection
    /// handoffs. The generated `comms_trust_reconcile` protocol uses this
    /// handle to fail closed when an obligation no longer matches the current
    /// MeerkatMachine peer-projection epoch.
    pub fn peer_projection_freshness_authority(
        &self,
    ) -> crate::protocol_comms_trust_reconcile::PeerProjectionFreshnessAuthority {
        crate::protocol_comms_trust_reconcile::PeerProjectionFreshnessAuthority::from_authority(
            Arc::clone(&self.inner),
        )
    }

    pub(crate) fn generated_authority_owner_token(&self) -> Arc<dyn std::any::Any + Send + Sync> {
        let guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        guard.generated_authority_owner_token()
    }

    /// Run `body` under the shared authority's mutex. The closure observes
    /// the DSL state atomically with any side effects it performs on the
    /// handle's external state (e.g. installing an observer before any
    /// further `apply_input_with_effects` can run). Locking order must
    /// match the order used by `apply_input_with_effects` (DSL first) so
    /// callers can safely acquire additional locks inside the closure.
    pub fn with_state_lock<R>(&self, body: impl FnOnce(&mm_dsl::MeerkatMachineState) -> R) -> R {
        let guard = self
            .inner
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        body(guard.state())
    }
}

impl std::fmt::Debug for HandleDslAuthority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HandleDslAuthority").finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn teardown_gate_rejects_stale_handle_input_before_mutation() {
        let authority = Arc::new(Mutex::new(mm_dsl::MeerkatMachineAuthority::new()));
        let gate = HandleTeardownGate::open();
        let handle = HandleDslAuthority::from_shared_with_teardown_gate(
            Arc::clone(&authority),
            Arc::clone(&gate),
        );
        gate.close();

        let err = handle
            .apply_input(
                mm_dsl::MeerkatMachineInput::RegisterSession {
                    session_id: mm_dsl::SessionId::from("closed-session"),
                },
                "test::stale_handle",
            )
            .expect_err("closed handle must reject writes");

        assert_eq!(
            err.kind,
            meerkat_core::handles::DslRejectionKind::NoMatchingTransition
        );
        assert!(err.reason.contains("closed by teardown"));
        let state = authority
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .state()
            .clone();
        assert_eq!(state.session_id, None);
    }
}