meerkat-runtime 0.8.18

v9 runtime control-plane for Meerkat agent lifecycle
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! MobRuntimeAdapter โ€” bridges mob provisioning to v9 RuntimeDriver lifecycle.
//!
//! When a mob member is spawned, the adapter registers a RuntimeDriver for that
//! session. When retired, the adapter retires/unregisters the driver. Flow steps
//! are delivered as FlowStepInput through accept_input().
//!
//! This adapter is optional โ€” mob works without it (existing SessionService path).
//! When present, it enables v9 input lifecycle tracking for mob members.

use meerkat_core::lifecycle::InputId;
use meerkat_core::types::ContentInput;
use meerkat_core::types::SessionId;

use crate::MeerkatMachine;
use crate::input::{
    FlowStepInput, Input, InputDurability, InputHeader, InputOrigin, InputVisibility,
};
#[allow(unused_imports)]
use crate::service_ext::SessionServiceRuntimeExt as _;
use crate::traits::{RuntimeControlPlaneError, RuntimeDriverError};

/// Create a FlowStepInput for a mob flow step.
pub fn create_flow_step_input(
    step_id: &str,
    instructions: ContentInput,
    flow_id: &str,
    step_index: usize,
    turn_metadata: Option<meerkat_core::lifecycle::run_primitive::RuntimeTurnMetadata>,
) -> Input {
    Input::FlowStep(FlowStepInput {
        header: InputHeader {
            id: InputId::new(),
            timestamp: chrono::Utc::now(),
            source: InputOrigin::Flow {
                flow_id: flow_id.into(),
                step_index,
            },
            durability: InputDurability::Durable,
            visibility: InputVisibility::default(),
            idempotency_key: None,
            supersession_key: None,
            correlation_id: None,
        },
        step_id: step_id.into(),
        content: instructions,
        directed_interaction_id: None,
        turn_metadata,
    })
}

/// Create the member-side tracked-turn input for a directive-bearing
/// `DeliverMemberInput` (multi-host mobs ยง18 O1, DEC-P6F-9 step 3): the
/// local flow-step mechanics relocated to the host that runs the loop.
///
/// `idempotency_key` is the delivery `input_id`, preserved EXACTLY so
/// redelivery deduplicates (`AcceptOutcome::Deduplicated`), matching the
/// plain-delivery path's `peer_input_from_delivery_payload` discipline.
pub fn create_tracked_flow_step_input(
    step_id: &str,
    instructions: ContentInput,
    flow_id: &str,
    turn_metadata: Option<meerkat_core::lifecycle::run_primitive::RuntimeTurnMetadata>,
    stable_input_id: &str,
) -> Result<Input, String> {
    let stable_uuid = uuid::Uuid::parse_str(stable_input_id).map_err(|error| {
        format!("tracked flow-step payload input_id '{stable_input_id}' is not a UUID: {error}")
    })?;
    if stable_uuid.is_nil() {
        return Err("tracked flow-step payload input_id must not be the nil UUID".to_string());
    }
    if stable_uuid.to_string() != stable_input_id {
        return Err(format!(
            "tracked flow-step payload input_id '{stable_input_id}' is not a canonical UUID"
        ));
    }
    Ok(Input::FlowStep(FlowStepInput {
        header: InputHeader {
            id: InputId::from_uuid(stable_uuid),
            timestamp: chrono::Utc::now(),
            source: InputOrigin::Flow {
                flow_id: flow_id.into(),
                // Remote steps carry no member-side step ordinal; the
                // controlling host owns flow sequencing (ยง18.1 โ€” frame
                // engine stays controlling-host-local).
                step_index: 0,
            },
            durability: InputDurability::Durable,
            visibility: InputVisibility::default(),
            idempotency_key: Some(crate::identifiers::IdempotencyKey::new(stable_input_id)),
            supersession_key: None,
            correlation_id: Some(crate::identifiers::CorrelationId::from_uuid(stable_uuid)),
        },
        step_id: step_id.into(),
        content: instructions,
        directed_interaction_id: Some(meerkat_core::interaction::InteractionId(stable_uuid)),
        turn_metadata,
    }))
}

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

    #[test]
    fn payload_uuid_owns_input_id_correlation_and_idempotency() {
        let stable = uuid::Uuid::new_v4();
        let input = create_tracked_flow_step_input(
            "step-1",
            ContentInput::Text("work".to_string()),
            "run-1",
            None,
            &stable.to_string(),
        )
        .expect("UUID lowers to tracked input");
        assert_eq!(input.id().0, stable);
        assert_eq!(
            input.header().correlation_id.as_ref().map(|id| id.0),
            Some(stable)
        );
        assert_eq!(
            input
                .header()
                .idempotency_key
                .as_ref()
                .map(ToString::to_string),
            Some(stable.to_string())
        );
        crate::input::validate_directed_flow_step_correlation(&input)
            .expect("constructor must mint a valid directed correlation");
    }

    #[test]
    fn forged_directed_correlation_is_rejected() {
        let stable = uuid::Uuid::new_v4();
        let mut input = create_tracked_flow_step_input(
            "step-1",
            ContentInput::Text("work".to_string()),
            "run-1",
            None,
            &stable.to_string(),
        )
        .expect("tracked input");
        let Input::FlowStep(flow_step) = &mut input else {
            panic!("flow step");
        };
        flow_step.directed_interaction_id = Some(meerkat_core::interaction::InteractionId(
            uuid::Uuid::new_v4(),
        ));

        assert!(crate::input::validate_directed_flow_step_correlation(&input).is_err());
    }

    #[test]
    fn caller_metadata_cannot_smuggle_directed_interaction_ids() {
        let stable = uuid::Uuid::new_v4();
        let forged = meerkat_core::interaction::InteractionId(uuid::Uuid::new_v4());
        let mut caller_metadata =
            meerkat_core::lifecycle::run_primitive::RuntimeTurnMetadata::default();
        caller_metadata.directed_interaction_ids.push(forged);
        let input = create_tracked_flow_step_input(
            "step-1",
            ContentInput::Text("work".to_string()),
            "run-1",
            Some(caller_metadata),
            &stable.to_string(),
        )
        .expect("tracked input");
        let semantics =
            crate::ingress_types::RuntimeInputSemantics::try_from_generated_admission(&input, true)
                .expect("flow step admission");
        let projected = crate::runtime_loop::for_input(&input, semantics);

        assert_eq!(
            projected.directed_interaction_ids,
            vec![meerkat_core::interaction::InteractionId(stable)],
            "runtime must overwrite caller-supplied directed identities"
        );
    }

    #[test]
    fn non_uuid_payload_id_is_rejected_before_admission() {
        assert!(
            create_tracked_flow_step_input(
                "step-1",
                ContentInput::Text("work".to_string()),
                "run-1",
                None,
                "alias-not-uuid",
            )
            .is_err()
        );
    }

    #[test]
    fn nil_uuid_payload_id_is_rejected_before_admission() {
        assert!(
            create_tracked_flow_step_input(
                "step-1",
                ContentInput::Text("work".to_string()),
                "run-1",
                None,
                &uuid::Uuid::nil().to_string(),
            )
            .expect_err("nil cannot own tracked-turn custody")
            .contains("nil UUID")
        );
    }
}

/// Register a mob member's session with the runtime adapter.
///
/// Registration is a control-plane prerequisite. A failed register is propagated
/// as a typed error rather than swallowed so the mob provisioning caller can abort
/// instead of proceeding as if the member's runtime exists.
pub async fn register_mob_member(
    adapter: &MeerkatMachine,
    session_id: SessionId,
) -> Result<(), RuntimeControlPlaneError> {
    adapter.register_session(session_id).await
}

/// Unregister a mob member's session from the runtime adapter.
pub async fn unregister_mob_member(
    adapter: &MeerkatMachine,
    session_id: &SessionId,
) -> Result<(), RuntimeDriverError> {
    adapter.unregister_session(session_id).await
}

/// Deliver a flow step to a mob member through the runtime path.
pub async fn deliver_flow_step(
    adapter: &MeerkatMachine,
    session_id: &SessionId,
    step_id: &str,
    instructions: impl Into<ContentInput>,
    flow_id: &str,
    step_index: usize,
) -> Result<crate::AcceptOutcome, RuntimeDriverError> {
    let input = create_flow_step_input(step_id, instructions.into(), flow_id, step_index, None);
    adapter.accept_input(session_id, input).await
}

/// Retire a mob member's runtime.
///
/// If the session is attached to a live `RuntimeLoop`, queued inputs remain
/// pending for drain. For plain registered sessions without a loop, retirement
/// abandons queued work because nothing can execute the drain path.
pub async fn retire_mob_member(
    adapter: &MeerkatMachine,
    session_id: &SessionId,
) -> Result<crate::traits::RetireReport, RuntimeDriverError> {
    adapter.retire_runtime(session_id).await
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::policy_table::DefaultPolicyTable;
    use std::sync::Arc;

    #[tokio::test]
    async fn spawn_creates_runtime_driver_session() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();

        register_mob_member(&adapter, sid.clone()).await.unwrap();

        // Session should have a runtime driver
        let state = adapter.runtime_state(&sid).await.unwrap();
        assert_eq!(state, crate::RuntimeState::Idle);
    }

    #[tokio::test]
    async fn flow_step_delivered_as_input() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();
        register_mob_member(&adapter, sid.clone()).await.unwrap();

        let outcome = deliver_flow_step(&adapter, &sid, "step-1", "analyze the data", "flow-1", 0)
            .await
            .unwrap();

        assert!(outcome.is_accepted());

        // Verify policy: flow_step โ†’ StageRunStart + WakeIfIdle
        let input = create_flow_step_input("s", "i".into(), "f", 0, None);
        let policy = DefaultPolicyTable::resolve(&input, true);
        assert_eq!(policy.apply_mode, crate::ApplyMode::StageRunStart);
        assert_eq!(policy.wake_mode, crate::WakeMode::WakeIfIdle);
    }

    #[tokio::test]
    async fn retire_without_runtime_loop_abandons_pending_inputs() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();
        register_mob_member(&adapter, sid.clone()).await.unwrap();

        // Accept an input first
        deliver_flow_step(&adapter, &sid, "s1", "do it", "f1", 0)
            .await
            .unwrap();

        // No RuntimeLoop is attached for plain registration, so retirement
        // abandons queued work instead of leaving it pending forever.
        let report = retire_mob_member(&adapter, &sid).await.unwrap();
        assert_eq!(report.inputs_abandoned, 1);
        assert_eq!(report.inputs_pending_drain, 0);
    }

    #[tokio::test]
    async fn create_flow_step_input_preserves_multimodal_blocks() -> Result<(), String> {
        let input = create_flow_step_input(
            "s",
            ContentInput::Blocks(vec![
                meerkat_core::types::ContentBlock::Text {
                    text: "inspect image".into(),
                },
                meerkat_core::types::ContentBlock::Image {
                    media_type: "image/png".into(),
                    data: "abc123".into(),
                },
            ]),
            "f",
            0,
            None,
        );

        let flow_step = match input {
            Input::FlowStep(flow_step) => flow_step,
            other => return Err(format!("expected flow step input, got {other:?}")),
        };
        assert_eq!(
            flow_step.content.text_content(),
            "inspect image\n[image: image/png]"
        );
        assert!(matches!(
            &flow_step.content,
            meerkat_core::types::ContentInput::Blocks(blocks) if blocks.len() == 2
        ));
        Ok(())
    }

    #[tokio::test]
    async fn unregister_removes_driver() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();
        register_mob_member(&adapter, sid.clone()).await.unwrap();

        unregister_mob_member(&adapter, &sid).await.unwrap();

        // Should fail now
        let result = adapter.runtime_state(&sid).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn register_exposes_driver_state() {
        // Mob-member registration is owned by the runtime control plane:
        // the registered session must have a live driver entry that surfaces
        // through typed runtime-state queries.
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();
        register_mob_member(&adapter, sid.clone()).await.unwrap();

        let active = adapter.list_active_inputs(&sid).await.unwrap();
        assert!(active.is_empty()); // No inputs yet
    }

    /// Gate (#99/#277): a control-plane registration that fails (the session was
    /// destroyed, so the RegisterSession command returns `Destroyed`) must surface
    /// a typed `Err` from `register_session` rather than being laundered to success.
    /// Pre-fix the helper dropped the result with `let _ = ...` and returned `()`,
    /// so the failure was invisible to callers.
    #[tokio::test]
    async fn register_session_surfaces_failure_on_destroyed_session() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();

        // Establish the session, then destroy it so re-registration must fail.
        adapter.register_session(sid.clone()).await.unwrap();
        let runtime_id = MeerkatMachine::logical_runtime_id(&sid);
        crate::traits::RuntimeControlPlane::destroy(&*adapter, &runtime_id)
            .await
            .unwrap();

        let result = adapter.register_session(sid.clone()).await;
        assert!(
            matches!(result, Err(RuntimeControlPlaneError::Internal(_))),
            "register_session on a destroyed session must surface a typed control-plane error, got {result:?}"
        );
    }

    /// Gate (#99): `register_mob_member` must propagate the typed registration
    /// failure rather than swallow it โ€” a mob member whose runtime cannot be
    /// registered must not be reported as provisioned.
    #[tokio::test]
    async fn register_mob_member_propagates_failure_on_destroyed_session() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();

        register_mob_member(&adapter, sid.clone()).await.unwrap();
        let runtime_id = MeerkatMachine::logical_runtime_id(&sid);
        crate::traits::RuntimeControlPlane::destroy(&*adapter, &runtime_id)
            .await
            .unwrap();

        let result = register_mob_member(&adapter, sid.clone()).await;
        assert!(
            result.is_err(),
            "register_mob_member must propagate the typed registration failure, got {result:?}"
        );
    }

    /// Gate (#41): `set_session_silent_intents` must surface the inner command's
    /// typed `Err` to the caller instead of dropping it with `let _ = ...`. A
    /// destroyed session makes the SetSilentIntents command return `Destroyed`.
    #[tokio::test]
    async fn set_session_silent_intents_surfaces_failure_on_destroyed_session() {
        let adapter = Arc::new(MeerkatMachine::ephemeral());
        let sid = SessionId::new();

        adapter.register_session(sid.clone()).await.unwrap();
        let runtime_id = MeerkatMachine::logical_runtime_id(&sid);
        crate::traits::RuntimeControlPlane::destroy(&*adapter, &runtime_id)
            .await
            .unwrap();

        let result = adapter
            .set_session_silent_intents(&sid, vec!["status".to_string()])
            .await;
        assert!(
            matches!(result, Err(RuntimeDriverError::Destroyed)),
            "set_session_silent_intents must surface the inner command failure, got {result:?}"
        );
    }
}