meerkat-runtime 0.5.2

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
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
//! Regression tests for comms → RuntimeDriver path.
//!
//! These tests mirror the 12 behavioral contracts from
//! meerkat-core/tests/regression_comms_host.rs but exercise them
//! through the v9 RuntimeDriver input acceptance path.
//!
//! Each test verifies:
//! - Correct PeerConvention mapping (CommsInputBridge)
//! - Correct PolicyDecision (DefaultPolicyTable)
//! - Correct wake/no-wake semantics
//! - Correct InputState lifecycle transitions

use meerkat_core::interaction::{
    InboxInteraction, InteractionContent, InteractionId, ResponseStatus,
};
use meerkat_runtime::comms_bridge::interaction_to_peer_input;
use meerkat_runtime::driver::ephemeral::EphemeralRuntimeDriver;
use meerkat_runtime::identifiers::LogicalRuntimeId;
use meerkat_runtime::input::{Input, InputDurability, PeerConvention};
use meerkat_runtime::input_state::InputLifecycleState;
use meerkat_runtime::policy_table::DefaultPolicyTable;
use meerkat_runtime::runtime_state::RuntimeState;
use meerkat_runtime::traits::RuntimeDriver;
use uuid::Uuid;

fn iid() -> InteractionId {
    InteractionId(Uuid::now_v7())
}

fn make_message(from: &str, body: &str) -> InboxInteraction {
    InboxInteraction {
        id: iid(),
        from: from.into(),
        content: InteractionContent::Message {
            body: body.into(),
            blocks: None,
        },
        rendered_text: format!("[{from}]: {body}"),
        handling_mode: meerkat_core::types::HandlingMode::Queue,
        render_metadata: None,
    }
}

fn make_message_with_blocks(from: &str, body: &str) -> InboxInteraction {
    InboxInteraction {
        id: iid(),
        from: from.into(),
        content: InteractionContent::Message {
            body: body.into(),
            blocks: Some(vec![
                meerkat_core::types::ContentBlock::Text { text: body.into() },
                meerkat_core::types::ContentBlock::Image {
                    media_type: "image/png".into(),
                    data: "abc123".into(),
                },
            ]),
        },
        rendered_text: format!("[{from}]: {body}"),
        handling_mode: meerkat_core::types::HandlingMode::Queue,
        render_metadata: None,
    }
}

fn make_response(from: &str, status: ResponseStatus) -> InboxInteraction {
    let in_reply_to = iid();
    InboxInteraction {
        id: iid(),
        from: from.into(),
        content: InteractionContent::Response {
            in_reply_to,
            status,
            result: serde_json::json!({"ok": true}),
        },
        rendered_text: format!("[{from}]: response ({status:?})"),
        handling_mode: meerkat_core::types::HandlingMode::Queue,
        render_metadata: None,
    }
}

fn make_request(from: &str, intent: &str) -> InboxInteraction {
    InboxInteraction {
        id: iid(),
        from: from.into(),
        content: InteractionContent::Request {
            intent: intent.into(),
            params: serde_json::json!({}),
        },
        rendered_text: format!("[{from}]: request ({intent})"),
        handling_mode: meerkat_core::types::HandlingMode::Queue,
        render_metadata: None,
    }
}

fn rid() -> LogicalRuntimeId {
    LogicalRuntimeId::new("test-runtime")
}

// ---------------------------------------------------------------------------
// §1: Completed response triggers continuation (wake) when idle
// ---------------------------------------------------------------------------
#[tokio::test]
async fn completed_response_idle_wakes() {
    let mut driver = EphemeralRuntimeDriver::new(rid());
    let interaction = make_response("peer-1", ResponseStatus::Completed);
    let input = interaction_to_peer_input(&interaction, &rid());

    // Verify bridge mapping
    if let Input::Peer(ref p) = input {
        assert!(matches!(
            p.convention,
            Some(PeerConvention::ResponseTerminal { .. })
        ));
        assert_eq!(p.header.durability, InputDurability::Durable);
    } else {
        panic!("Expected PeerInput");
    }

    // Verify policy: terminal response + idle → StageRunStart + WakeIfIdle
    let policy = DefaultPolicyTable::resolve(&input, true);
    assert_eq!(policy.apply_mode, meerkat_runtime::ApplyMode::StageRunStart);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::WakeIfIdle);

    // Verify driver behavior
    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
}

// ---------------------------------------------------------------------------
// §2: Accepted response injects context, no continuation (no wake)
// ---------------------------------------------------------------------------
#[tokio::test]
async fn accepted_response_no_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());
    let interaction = make_response("peer-1", ResponseStatus::Accepted);
    let input = interaction_to_peer_input(&interaction, &rid());

    // Verify bridge: Accepted → ResponseProgress
    if let Input::Peer(ref p) = input {
        assert!(matches!(
            p.convention,
            Some(PeerConvention::ResponseProgress { .. })
        ));
        assert_eq!(p.header.durability, InputDurability::Ephemeral);
    } else {
        panic!("Expected PeerInput");
    }

    // Verify policy per §17: progress → StageRunBoundary + NoWake + Coalesce + OnRunComplete
    let policy = DefaultPolicyTable::resolve(&input, true);
    assert_eq!(
        policy.apply_mode,
        meerkat_runtime::ApplyMode::StageRunBoundary
    );
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::None);
    assert_eq!(policy.queue_mode, meerkat_runtime::QueueMode::Coalesce);
    assert_eq!(
        policy.consume_point,
        meerkat_runtime::ConsumePoint::OnRunComplete
    );

    // Verify driver: accepted but no wake, queued (not immediately consumed)
    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(!driver.take_wake_requested());

    // Input should be queued (StageRunBoundary queues for boundary application)
    if let meerkat_runtime::AcceptOutcome::Accepted { input_id, .. } = &outcome {
        let state = driver.input_state(input_id).unwrap();
        assert_eq!(state.current_state(), InputLifecycleState::Queued);
    }
}

// ---------------------------------------------------------------------------
// §3: Failed response triggers continuation (wake) when idle
// ---------------------------------------------------------------------------
#[tokio::test]
async fn failed_response_idle_wakes() {
    let mut driver = EphemeralRuntimeDriver::new(rid());
    let interaction = make_response("peer-1", ResponseStatus::Failed);
    let input = interaction_to_peer_input(&interaction, &rid());

    // Verify bridge: Failed → ResponseTerminal
    if let Input::Peer(ref p) = input {
        assert!(matches!(
            p.convention,
            Some(PeerConvention::ResponseTerminal {
                status: meerkat_runtime::ResponseTerminalStatus::Failed,
                ..
            })
        ));
    } else {
        panic!("Expected PeerInput");
    }

    // Verify: terminal response + idle → wake
    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
}

// ---------------------------------------------------------------------------
// §4: Response + passthrough message: both queued
// ---------------------------------------------------------------------------
#[tokio::test]
async fn response_with_passthrough_message_both_queued() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    // Accept a completed response
    let resp = make_response("peer-1", ResponseStatus::Completed);
    let input1 = interaction_to_peer_input(&resp, &rid());
    driver.accept_input(input1).await.unwrap();

    // Accept a message
    let msg = make_message("peer-2", "hello");
    let input2 = interaction_to_peer_input(&msg, &rid());
    driver.accept_input(input2).await.unwrap();

    // Both should be queued
    assert_eq!(driver.queue().len(), 2);
    assert!(driver.take_wake_requested()); // Terminal response woke it
}

// ---------------------------------------------------------------------------
// §5: Response after completed host turn triggers continuation
// ---------------------------------------------------------------------------
#[tokio::test]
async fn response_after_completed_turn_wakes() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    // Simulate a completed run by starting and completing
    let run_id = meerkat_core::lifecycle::RunId::new();
    driver.start_run(run_id.clone()).unwrap();
    driver.complete_run().unwrap();

    // Now idle — accept a terminal response
    let resp = make_response("peer-1", ResponseStatus::Completed);
    let input = interaction_to_peer_input(&resp, &rid());
    let outcome = driver.accept_input(input).await.unwrap();

    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested()); // Should wake idle runtime
}

// ---------------------------------------------------------------------------
// §6: Peer lifecycle batching — multiple peer_added collapse
// ---------------------------------------------------------------------------
#[tokio::test]
async fn peer_lifecycle_accepts_as_requests() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    // Silent intents (mob.peer_added) are PeerInput with Request convention
    let req1 = make_request("peer-1", "mob.peer_added");
    let input1 = interaction_to_peer_input(&req1, &rid());

    if let Input::Peer(ref p) = input1 {
        assert!(matches!(p.convention, Some(PeerConvention::Request { .. })));
    }

    // Policy: peer_request + idle → StageRunStart + WakeIfIdle
    let policy = DefaultPolicyTable::resolve(&input1, true);
    assert_eq!(policy.apply_mode, meerkat_runtime::ApplyMode::StageRunStart);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::WakeIfIdle);

    let outcome = driver.accept_input(input1).await.unwrap();
    assert!(outcome.is_accepted());
}

// ---------------------------------------------------------------------------
// §7: Peer lifecycle net-out: add + retire same peer cancels
// ---------------------------------------------------------------------------
#[tokio::test]
async fn peer_lifecycle_net_out_both_accepted() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    // Both arrive as separate inputs — the v9 path accepts both individually
    // (batching/coalescing happens at the queue level, not acceptance)
    let added = make_request("peer-1", "mob.peer_added");
    let retired = make_request("peer-1", "mob.peer_retired");

    let input1 = interaction_to_peer_input(&added, &rid());
    let input2 = interaction_to_peer_input(&retired, &rid());

    let o1 = driver.accept_input(input1).await.unwrap();
    let o2 = driver.accept_input(input2).await.unwrap();

    assert!(o1.is_accepted());
    assert!(o2.is_accepted());
    assert_eq!(driver.queue().len(), 2); // Both queued individually
}

// ---------------------------------------------------------------------------
// §8: Silent comms intent — no LLM turn (maps to Request, policy wakes)
// ---------------------------------------------------------------------------
#[tokio::test]
async fn silent_intent_maps_to_request_with_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    let interaction = make_request("coordinator", "mob.peer_added");
    let input = interaction_to_peer_input(&interaction, &rid());

    // Under v9, silent intents are PeerInput(Request). The runtime's policy
    // says WakeIfIdle for requests. The SILENT behavior is handled by the
    // SilentIntentOverride layer (not yet implemented in DefaultPolicyTable).
    // For now, verify the mapping is correct.
    let policy = DefaultPolicyTable::resolve(&input, true);
    assert_eq!(policy.apply_mode, meerkat_runtime::ApplyMode::StageRunStart);

    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
}

// ---------------------------------------------------------------------------
// §9: Non-silent comms intent triggers LLM turn
// ---------------------------------------------------------------------------
#[tokio::test]
async fn non_silent_intent_triggers_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    let interaction = make_request("coordinator", "custom.action");
    let input = interaction_to_peer_input(&interaction, &rid());

    let policy = DefaultPolicyTable::resolve(&input, true);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::WakeIfIdle);

    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
}

// ---------------------------------------------------------------------------
// §10: Message interaction triggers host-mode run
// ---------------------------------------------------------------------------
#[tokio::test]
async fn message_triggers_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    let interaction = make_message("peer-1", "hello world");
    let input = interaction_to_peer_input(&interaction, &rid());

    // peer_message + idle → StageRunStart + WakeIfIdle
    let policy = DefaultPolicyTable::resolve(&input, true);
    assert_eq!(policy.apply_mode, meerkat_runtime::ApplyMode::StageRunStart);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::WakeIfIdle);

    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
    assert_eq!(driver.queue().len(), 1);
}

// ---------------------------------------------------------------------------
// §11: Request interaction triggers host-mode run
// ---------------------------------------------------------------------------
#[tokio::test]
async fn request_triggers_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    let interaction = make_request("peer-1", "analyze");
    let input = interaction_to_peer_input(&interaction, &rid());

    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
}

#[tokio::test]
async fn request_prompt_uses_rendered_text_projection() {
    let interaction = make_request("peer-1", "custom.action");
    let input = interaction_to_peer_input(&interaction, &rid());

    if let Input::Peer(peer) = input {
        assert_eq!(peer.body, interaction.rendered_text);
    } else {
        panic!("Expected PeerInput");
    }
}

#[tokio::test]
async fn response_prompt_uses_rendered_text_projection() {
    let interaction = make_response("peer-1", ResponseStatus::Completed);
    let input = interaction_to_peer_input(&interaction, &rid());

    if let Input::Peer(peer) = input {
        assert_eq!(peer.body, interaction.rendered_text);
    } else {
        panic!("Expected PeerInput");
    }
}

#[tokio::test]
async fn message_blocks_survive_bridge() {
    let interaction = make_message_with_blocks("peer-1", "look");
    let input = interaction_to_peer_input(&interaction, &rid());

    if let Input::Peer(peer) = input {
        assert!(peer.blocks.is_some());
        // peer.body is the canonical rendered projection, while blocks preserve
        // the original multimodal content.
        assert_eq!(peer.body, interaction.rendered_text);
    } else {
        panic!("Expected PeerInput");
    }
}

// ---------------------------------------------------------------------------
// §12: Empty inbox — no turns
// ---------------------------------------------------------------------------
#[tokio::test]
async fn no_input_no_wake() {
    let driver = EphemeralRuntimeDriver::new(rid());
    // No accept_input called — queue empty, no wake
    assert!(driver.queue().is_empty());
    assert_eq!(driver.runtime_state(), RuntimeState::Idle);
}

// ---------------------------------------------------------------------------
// Additional: Message while running — queue policy, no wake
// ---------------------------------------------------------------------------
#[tokio::test]
async fn message_while_running_queues_without_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    // Start a run
    driver
        .start_run(meerkat_core::lifecycle::RunId::new())
        .unwrap();

    let interaction = make_message("peer-1", "hello");
    let input = interaction_to_peer_input(&interaction, &rid());

    // peer_message + running → StageRunStart + NoWake (queue semantics)
    let policy = DefaultPolicyTable::resolve(&input, false);
    assert_eq!(policy.apply_mode, meerkat_runtime::ApplyMode::StageRunStart);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::None);

    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(!driver.take_wake_requested());
}

// ---------------------------------------------------------------------------
// Additional: Terminal response while running — checkpoint, no wake
// ---------------------------------------------------------------------------
#[tokio::test]
async fn terminal_response_while_running_no_wake() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    driver
        .start_run(meerkat_core::lifecycle::RunId::new())
        .unwrap();

    let interaction = make_response("peer-1", ResponseStatus::Completed);
    let input = interaction_to_peer_input(&interaction, &rid());

    // peer_response_terminal + running → StageRunStart + NoWake (per §17)
    let policy = DefaultPolicyTable::resolve(&input, false);
    assert_eq!(policy.apply_mode, meerkat_runtime::ApplyMode::StageRunStart);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::None);

    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(!driver.take_wake_requested());
}

// ---------------------------------------------------------------------------
// §13: Terminal response produces exactly one Peer input — no synthetic Continuation
// ---------------------------------------------------------------------------
#[tokio::test]
async fn drain_terminal_response_produces_exactly_one_peer_input() {
    let mut driver = EphemeralRuntimeDriver::new(rid());

    // Build a terminal response interaction and convert to runtime input.
    let interaction = make_response("peer-1", ResponseStatus::Completed);
    let input = interaction_to_peer_input(&interaction, &rid());

    // The bridge must produce a Peer input, not a Continuation.
    assert!(
        matches!(&input, Input::Peer(_)),
        "terminal response must map to Peer, got {:?}",
        input.kind_id()
    );

    // Accept through the driver.
    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());

    // Exactly 1 input in the queue — zero Continuations.
    assert_eq!(
        driver.queue().len(),
        1,
        "terminal response must produce exactly 1 queued input"
    );

    // Verify the queued input is a Peer with ResponseTerminal convention.
    let queued_ids = driver.queue().input_ids();
    let queued_state = driver.input_state(&queued_ids[0]).unwrap();
    if let Some(Input::Peer(peer)) = &queued_state.persisted_input {
        assert!(
            matches!(
                peer.convention,
                Some(PeerConvention::ResponseTerminal { .. })
            ),
            "queued input must be ResponseTerminal"
        );
    }
}

// ---------------------------------------------------------------------------
// §14: Terminal response + Steer handling_mode while running
// ---------------------------------------------------------------------------
#[tokio::test]
async fn terminal_response_with_steer_policy_while_running() {
    // Build a terminal response with Steer handling_mode.
    let in_reply_to = iid();
    let interaction = InboxInteraction {
        id: iid(),
        from: "peer-1".into(),
        content: InteractionContent::Response {
            in_reply_to,
            status: ResponseStatus::Completed,
            result: serde_json::json!({"ok": true}),
        },
        rendered_text: "[peer-1]: response (Completed)".into(),
        handling_mode: meerkat_core::types::HandlingMode::Steer,
        render_metadata: None,
    };
    let input = interaction_to_peer_input(&interaction, &rid());

    // While running: explicit steer keeps WakeMode::None at the policy layer,
    // but ingress still requests immediate processing via the typed steer signal.
    let policy = DefaultPolicyTable::resolve(&input, false);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::None);
    assert_eq!(
        policy.routing_disposition,
        meerkat_runtime::RoutingDisposition::Steer
    );

    // Verify driver behavior while running.
    let mut driver = EphemeralRuntimeDriver::new(rid());
    driver
        .start_run(meerkat_core::lifecycle::RunId::new())
        .unwrap();
    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
}

// ---------------------------------------------------------------------------
// §15: Terminal response + Steer handling_mode while idle
// ---------------------------------------------------------------------------
#[tokio::test]
async fn terminal_response_with_steer_policy_while_idle() {
    // Build a terminal response with Steer handling_mode.
    let in_reply_to = iid();
    let interaction = InboxInteraction {
        id: iid(),
        from: "peer-1".into(),
        content: InteractionContent::Response {
            in_reply_to,
            status: ResponseStatus::Completed,
            result: serde_json::json!({"ok": true}),
        },
        rendered_text: "[peer-1]: response (Completed)".into(),
        handling_mode: meerkat_core::types::HandlingMode::Steer,
        render_metadata: None,
    };
    let input = interaction_to_peer_input(&interaction, &rid());

    // While idle: should get WakeIfIdle + Steer.
    let policy = DefaultPolicyTable::resolve(&input, true);
    assert_eq!(policy.wake_mode, meerkat_runtime::WakeMode::WakeIfIdle);
    assert_eq!(
        policy.routing_disposition,
        meerkat_runtime::RoutingDisposition::Steer
    );

    // Verify driver behavior while idle.
    let mut driver = EphemeralRuntimeDriver::new(rid());
    let outcome = driver.accept_input(input).await.unwrap();
    assert!(outcome.is_accepted());
    assert!(driver.take_wake_requested());
}