meerkat-runtime 0.7.21

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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
#![allow(
    clippy::expect_used,
    clippy::large_futures,
    clippy::panic,
    clippy::unwrap_used
)]
//! Detached-wake contract tests for background shell job notification.
//!
//! These tests verify the current runtime-loop-owned detached-wake paths that
//! inject `Input::Continuation` into a quiescent session when background
//! operations reach terminal state.

use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering;
use std::time::Duration;

use meerkat_core::RunBoundaryReceiptDraft;
use meerkat_core::lifecycle::core_executor::{CoreApplyOutput, CoreExecutorError};
use meerkat_core::lifecycle::run_primitive::{RunApplyBoundary, RunPrimitive};
use meerkat_core::lifecycle::{CoreExecutor, RunId};
use meerkat_core::ops_lifecycle::{
    OperationKind, OperationResult, OperationSource, OperationSpec, OpsLifecycleRegistry,
};
use meerkat_core::types::{RunResult, SessionId, Usage};
use meerkat_runtime::{
    ContinuationInput, InputDurability, InputOrigin, InputVisibility, MeerkatMachine,
    RuntimeOpsLifecycleRegistry,
};
use tokio::sync::Notify;

async fn wait_for_apply_count(apply_count: &AtomicUsize, expected: usize, context: &'static str) {
    tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            if apply_count.load(Ordering::SeqCst) >= expected {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect(context);
}

fn background_spec(name: &str) -> OperationSpec {
    OperationSpec {
        id: meerkat_core::ops_lifecycle::OperationId::new(),
        kind: OperationKind::BackgroundToolOp,
        owner_session_id: SessionId::new(),
        display_name: name.into(),
        source_label: "test-detached-wake".into(),
        operation_source: None,
        child_session_id: None,
        expect_peer_channel: false,
    }
}

fn mob_member_spec(name: &str) -> OperationSpec {
    let child_session_id = SessionId::new();
    OperationSpec {
        id: meerkat_core::ops_lifecycle::OperationId::new(),
        kind: OperationKind::MobMemberChild,
        owner_session_id: SessionId::new(),
        display_name: name.into(),
        source_label: "test-detached-wake".into(),
        operation_source: Some(OperationSource::session_child(child_session_id.clone())),
        child_session_id: Some(child_session_id),
        expect_peer_channel: true,
    }
}

fn op_result(id: &meerkat_core::ops_lifecycle::OperationId, content: &str) -> OperationResult {
    OperationResult {
        id: id.clone(),
        content: content.into(),
        is_error: false,
        duration_ms: 42,
        tokens_used: 7,
    }
}

/// Simple executor that succeeds immediately and returns a RunResult.
struct ResultExecutor;

#[async_trait::async_trait]
impl CoreExecutor for ResultExecutor {
    async fn apply(
        &mut self,
        run_id: RunId,
        primitive: RunPrimitive,
    ) -> Result<CoreApplyOutput, CoreExecutorError> {
        Ok(CoreApplyOutput::with_run_result(
            RunBoundaryReceiptDraft {
                run_id,
                boundary: RunApplyBoundary::RunStart,
                contributing_input_ids: primitive.contributing_input_ids().to_vec(),
                conversation_digest: None,
                message_count: 0,
            },
            None,
            RunResult {
                text: "done".into(),
                session_id: SessionId::new(),
                usage: Usage::default(),
                turns: 1,
                tool_calls: 0,
                terminal_cause_kind: None,
                structured_output: None,
                extraction_error: None,
                schema_warnings: None,
                skill_diagnostics: None,
            },
        ))
    }
    async fn cancel_after_boundary(&mut self, _reason: String) -> Result<(), CoreExecutorError> {
        Ok(())
    }

    async fn stop_runtime_executor(&mut self, _reason: String) -> Result<(), CoreExecutorError> {
        Ok(())
    }
}

// ─── CHOKE-004-IT: Idle runtime wakes after background op terminal ───

#[tokio::test]
async fn choke_004_feed_backed_idle_runtime_injects_continuation_without_manual_trigger() {
    struct CountingExecutor {
        apply_count: Arc<AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl CoreExecutor for CountingExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            self.apply_count.fetch_add(1, Ordering::SeqCst);
            Ok(CoreApplyOutput::with_run_result(
                RunBoundaryReceiptDraft {
                    run_id,
                    boundary: RunApplyBoundary::RunStart,
                    contributing_input_ids: primitive.contributing_input_ids().to_vec(),
                    conversation_digest: None,
                    message_count: 0,
                },
                None,
                RunResult {
                    text: "done".into(),
                    session_id: SessionId::new(),
                    usage: Usage::default(),
                    turns: 1,
                    tool_calls: 0,
                    terminal_cause_kind: None,
                    structured_output: None,
                    extraction_error: None,
                    schema_warnings: None,
                    skill_diagnostics: None,
                },
            ))
        }

        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    let apply_count = Arc::new(AtomicUsize::new(0));
    let adapter = Arc::new(MeerkatMachine::ephemeral());
    let session_id = SessionId::new();

    adapter
        .register_session_with_executor(
            session_id.clone(),
            Box::new(CountingExecutor {
                apply_count: Arc::clone(&apply_count),
            }),
        )
        .await
        .expect("runtime executor registration should succeed");

    let registry = adapter
        .ops_lifecycle_registry(&session_id)
        .await
        .expect("session registry should exist");

    let spec = background_spec("idle-feed");
    let op_id = spec.id.clone();
    registry.register_operation(spec).unwrap();
    registry.provisioning_succeeded(&op_id).unwrap();
    registry
        .complete_operation(&op_id, op_result(&op_id, "done"))
        .unwrap();

    tokio::time::timeout(Duration::from_secs(2), async {
        loop {
            if apply_count.load(Ordering::SeqCst) >= 1 {
                break;
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
    })
    .await
    .expect("feed-backed idle wake should inject a continuation without manual trigger");

    assert_eq!(
        apply_count.load(Ordering::SeqCst),
        1,
        "background completion should produce exactly one continuation apply on the idle feed path"
    );
}

#[tokio::test]
async fn choke_004_idle_runtime_wakes_on_detached_op_completion() {
    struct CountingExecutor {
        apply_count: Arc<AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl CoreExecutor for CountingExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            self.apply_count.fetch_add(1, Ordering::SeqCst);
            let mut executor = ResultExecutor;
            executor.apply(run_id, primitive).await
        }
        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    let apply_count = Arc::new(AtomicUsize::new(0));
    let adapter = Arc::new(MeerkatMachine::ephemeral());
    let session_id = SessionId::new();

    // Register session with executor so runtime loop is running
    adapter
        .register_session_with_executor(
            session_id.clone(),
            Box::new(CountingExecutor {
                apply_count: Arc::clone(&apply_count),
            }),
        )
        .await
        .expect("runtime executor registration should succeed");

    // The runtime loop owns detached wake for registered sessions.

    let registry = adapter
        .ops_lifecycle_registry(&session_id)
        .await
        .expect("session registry should exist");

    let spec = background_spec("wake-on-complete");
    let op_id = spec.id.clone();
    registry.register_operation(spec).unwrap();
    registry.provisioning_succeeded(&op_id).unwrap();
    registry
        .complete_operation(&op_id, op_result(&op_id, "done"))
        .unwrap();

    // Trigger the runtime loop so it reaches the post-drain wake check and can
    // inject the continuation on the feed-backed path.
    use meerkat_runtime::{Input, InputDurability, InputHeader, PromptInput};
    let trigger_input = Input::Prompt(PromptInput {
        injected_context: Vec::new(),
        header: InputHeader {
            id: meerkat_core::lifecycle::InputId::new(),
            timestamp: chrono::Utc::now(),
            source: InputOrigin::Operator,
            durability: InputDurability::Durable,
            visibility: InputVisibility::default(),
            idempotency_key: None,
            supersession_key: None,
            correlation_id: None,
        },
        content: "trigger wake".into(),
        typed_turn_appends: Vec::new(),
        turn_metadata: None,
    });

    let (_, handle) = adapter
        .accept_input_with_completion(&session_id, trigger_input)
        .await
        .unwrap();

    // Wait for the turn to complete
    if let Some(handle) = handle {
        let _ = tokio::time::timeout(Duration::from_secs(2), handle.wait()).await;
    }

    wait_for_apply_count(
        &apply_count,
        2,
        "runtime loop should inject a detached-op continuation after the trigger turn",
    )
    .await;
}

// ─── CHOKE-004-IT-B: Five completions produce one coalesced wake ───

#[tokio::test]
async fn choke_004_five_completions_produce_one_coalesced_wake() {
    struct CountingExecutor {
        apply_count: Arc<AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl CoreExecutor for CountingExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            self.apply_count.fetch_add(1, Ordering::SeqCst);
            let mut executor = ResultExecutor;
            executor.apply(run_id, primitive).await
        }
        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    let apply_count = Arc::new(AtomicUsize::new(0));
    let adapter = Arc::new(MeerkatMachine::ephemeral());
    let session_id = SessionId::new();

    adapter
        .register_session_with_executor(
            session_id.clone(),
            Box::new(CountingExecutor {
                apply_count: Arc::clone(&apply_count),
            }),
        )
        .await
        .expect("runtime executor registration should succeed");

    // The runtime loop owns detached wake for registered sessions.

    let registry = adapter
        .ops_lifecycle_registry(&session_id)
        .await
        .expect("session registry should exist");

    let mut op_ids = Vec::new();
    for i in 0..5 {
        let spec = background_spec(&format!("coalesce-{i}"));
        let op_id = spec.id.clone();
        registry.register_operation(spec).unwrap();
        registry.provisioning_succeeded(&op_id).unwrap();
        op_ids.push(op_id);
    }

    // Complete all 5 operations — each sets pending=true, but pending is
    // already true after the first, so only one wake is needed.
    for op_id in &op_ids {
        registry
            .complete_operation(op_id, op_result(op_id, "done"))
            .unwrap();
    }

    // Trigger the runtime loop with a prompt so the idle-wake path fires
    use meerkat_runtime::{Input, InputHeader, PromptInput};
    let trigger_input = Input::Prompt(PromptInput {
        injected_context: Vec::new(),
        header: InputHeader {
            id: meerkat_core::lifecycle::InputId::new(),
            timestamp: chrono::Utc::now(),
            source: InputOrigin::Operator,
            durability: InputDurability::Durable,
            visibility: InputVisibility::default(),
            idempotency_key: None,
            supersession_key: None,
            correlation_id: None,
        },
        content: "trigger".into(),
        typed_turn_appends: Vec::new(),
        turn_metadata: None,
    });

    let (_, handle) = adapter
        .accept_input_with_completion(&session_id, trigger_input)
        .await
        .unwrap();

    if let Some(handle) = handle {
        let _ = tokio::time::timeout(Duration::from_secs(2), handle.wait()).await;
    }

    wait_for_apply_count(
        &apply_count,
        2,
        "runtime loop should coalesce five completions into one continuation",
    )
    .await;

    tokio::time::sleep(Duration::from_millis(75)).await;

    // 5 completions -> pending=true (set once, stays true) -> 1 notify -> 1 continuation.
    assert_eq!(
        apply_count.load(Ordering::SeqCst),
        2,
        "five completions should coalesce into one continuation after the trigger prompt"
    );
}

// ─── CHOKE-004-IT-C: Completion during Running defers wake ───

#[tokio::test]
async fn choke_004_completion_during_running_defers_wake() {
    use std::sync::atomic::AtomicUsize;

    struct SlowExecutor {
        apply_count: Arc<AtomicUsize>,
        first_apply_started: Arc<Notify>,
    }

    #[async_trait::async_trait]
    impl CoreExecutor for SlowExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            let call_index = self.apply_count.fetch_add(1, Ordering::SeqCst) + 1;
            // First call: sleep long enough for the op to complete during running
            if call_index == 1 {
                self.first_apply_started.notify_one();
                tokio::time::sleep(Duration::from_millis(300)).await;
            }
            Ok(CoreApplyOutput::with_run_result(
                RunBoundaryReceiptDraft {
                    run_id,
                    boundary: RunApplyBoundary::RunStart,
                    contributing_input_ids: primitive.contributing_input_ids().to_vec(),
                    conversation_digest: None,
                    message_count: 0,
                },
                None,
                RunResult {
                    text: "done".into(),
                    session_id: SessionId::new(),
                    usage: Usage::default(),
                    turns: 1,
                    tool_calls: 0,
                    terminal_cause_kind: None,
                    structured_output: None,
                    extraction_error: None,
                    schema_warnings: None,
                    skill_diagnostics: None,
                },
            ))
        }
        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    let apply_count = Arc::new(AtomicUsize::new(0));
    let first_apply_started = Arc::new(Notify::new());
    let adapter = Arc::new(MeerkatMachine::ephemeral());
    let session_id = SessionId::new();

    adapter
        .register_session_with_executor(
            session_id.clone(),
            Box::new(SlowExecutor {
                apply_count: apply_count.clone(),
                first_apply_started: Arc::clone(&first_apply_started),
            }),
        )
        .await
        .expect("runtime executor registration should succeed");

    // Waker task is spawned automatically during register_session_with_executor.

    let registry = adapter
        .ops_lifecycle_registry(&session_id)
        .await
        .expect("session registry should exist");

    let spec = background_spec("deferred-wake");
    let op_id = spec.id.clone();
    registry.register_operation(spec).unwrap();
    registry.provisioning_succeeded(&op_id).unwrap();

    // Start a turn (session becomes Running)
    use meerkat_runtime::{Input, InputHeader, PromptInput};
    let trigger = Input::Prompt(PromptInput {
        injected_context: Vec::new(),
        header: InputHeader {
            id: meerkat_core::lifecycle::InputId::new(),
            timestamp: chrono::Utc::now(),
            source: InputOrigin::Operator,
            durability: InputDurability::Durable,
            visibility: InputVisibility::default(),
            idempotency_key: None,
            supersession_key: None,
            correlation_id: None,
        },
        content: "start turn".into(),
        typed_turn_appends: Vec::new(),
        turn_metadata: None,
    });

    let (_, handle) = adapter
        .accept_input_with_completion(&session_id, trigger)
        .await
        .unwrap();

    tokio::time::timeout(Duration::from_secs(1), first_apply_started.notified())
        .await
        .expect("initial prompt apply should start");

    // Complete the op while the session is running (during the 300ms sleep)
    registry
        .complete_operation(&op_id, op_result(&op_id, "done-while-running"))
        .unwrap();

    // The completion-feed entry is visible at this point, but the runtime loop
    // hasn't reached the idle-wake path yet because the executor is still
    // sleeping and the session is not quiescent.

    // Wait for the first turn to complete
    if let Some(handle) = handle {
        let _ = tokio::time::timeout(Duration::from_secs(3), handle.wait()).await;
    }

    wait_for_apply_count(
        &apply_count,
        2,
        "runtime loop should inject deferred continuation after the prompt quiesces",
    )
    .await;

    // The executor should have been called at least twice:
    // 1. The initial prompt
    // 2. The deferred continuation (injected after quiescence)
    let calls = apply_count.load(Ordering::SeqCst);
    assert!(
        calls >= 2,
        "expected at least 2 executor calls (prompt + deferred continuation), got {calls}"
    );
}

// ─── CHOKE-004-IT-D: MobMemberChild completion does NOT trigger idle wake ───
//
// MobMemberChild completions already wake the session through comms-based
// terminal response injection. The CompletionFeed-based idle wake must filter
// them out to avoid duplicate continuation injections.

#[tokio::test]
async fn choke_004_mob_member_child_completion_does_not_trigger_idle_wake() {
    use std::sync::atomic::AtomicUsize;

    struct CountingExecutor {
        apply_count: Arc<AtomicUsize>,
    }

    #[async_trait::async_trait]
    impl CoreExecutor for CountingExecutor {
        async fn apply(
            &mut self,
            run_id: RunId,
            primitive: RunPrimitive,
        ) -> Result<CoreApplyOutput, CoreExecutorError> {
            self.apply_count.fetch_add(1, Ordering::SeqCst);
            let run_result = RunResult {
                text: "done".into(),
                session_id: SessionId::new(),
                usage: Usage::default(),
                turns: 1,
                tool_calls: 0,
                terminal_cause_kind: None,
                structured_output: None,
                extraction_error: None,
                schema_warnings: None,
                skill_diagnostics: None,
            };
            Ok(CoreApplyOutput::with_run_result(
                RunBoundaryReceiptDraft {
                    run_id,
                    boundary: RunApplyBoundary::RunStart,
                    contributing_input_ids: primitive.contributing_input_ids().to_vec(),
                    conversation_digest: None,
                    message_count: 0,
                },
                None,
                run_result,
            ))
        }
        async fn cancel_after_boundary(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }

        async fn stop_runtime_executor(
            &mut self,
            _reason: String,
        ) -> Result<(), CoreExecutorError> {
            Ok(())
        }
    }

    let apply_count = Arc::new(AtomicUsize::new(0));
    let adapter = Arc::new(MeerkatMachine::ephemeral());
    let session_id = SessionId::new();

    adapter
        .register_session_with_executor(
            session_id.clone(),
            Box::new(CountingExecutor {
                apply_count: apply_count.clone(),
            }),
        )
        .await
        .expect("runtime executor registration should succeed");

    let registry = adapter
        .ops_lifecycle_registry(&session_id)
        .await
        .expect("session registry should exist");

    // Register and complete a MobMemberChild operation
    let spec = mob_member_spec("delegate-no-idle-wake");
    let op_id = spec.id.clone();
    registry.register_operation(spec).unwrap();
    registry.provisioning_succeeded(&op_id).unwrap();
    registry
        .complete_operation(&op_id, op_result(&op_id, "delegate done"))
        .unwrap();

    // Trigger a prompt to flush any queued continuations
    use meerkat_runtime::{Input, InputHeader, PromptInput};
    let trigger = Input::Prompt(PromptInput {
        injected_context: Vec::new(),
        header: InputHeader {
            id: meerkat_core::lifecycle::InputId::new(),
            timestamp: chrono::Utc::now(),
            source: InputOrigin::Operator,
            durability: InputDurability::Durable,
            visibility: InputVisibility::default(),
            idempotency_key: None,
            supersession_key: None,
            correlation_id: None,
        },
        content: "flush".into(),
        typed_turn_appends: Vec::new(),
        turn_metadata: None,
    });

    let (_, handle) = adapter
        .accept_input_with_completion(&session_id, trigger)
        .await
        .unwrap();
    if let Some(handle) = handle {
        let _ = tokio::time::timeout(Duration::from_secs(2), handle.wait()).await;
    }
    tokio::time::sleep(Duration::from_millis(75)).await;

    // The executor should have been called exactly once (the flush prompt).
    // If MobMemberChild completion triggered an idle wake, we'd see 2+ calls
    // (the continuation + the flush).
    let calls = apply_count.load(Ordering::SeqCst);
    assert_eq!(
        calls, 1,
        "MobMemberChild completion should NOT trigger idle wake continuation; \
         expected 1 executor call (flush only), got {calls}"
    );
}

// ─── UNIT-003: ContinuationInput helper builds correct shape ───

#[test]
fn unit_003_continuation_helper_builds_derived_invisible_steer() {
    let continuation = ContinuationInput::detached_background_op_completed();

    assert_eq!(continuation.header.durability, InputDurability::Derived);
    assert!(!continuation.header.visibility.transcript_eligible);
    assert!(!continuation.header.visibility.operator_eligible);
    assert!(matches!(continuation.header.source, InputOrigin::System));
    assert_eq!(
        continuation.handling_mode,
        meerkat_core::types::HandlingMode::Steer
    );
    assert_eq!(continuation.reason, "detached_background_op_completed");
    assert!(continuation.request_id.is_none());
}

// ─── UNIT-004: Completion feed carries kind through so idle-wake can
//              filter BackgroundToolOp vs MobMemberChild ───

#[test]
fn unit_004_completion_feed_carries_operation_kind() {
    let registry = RuntimeOpsLifecycleRegistry::new();
    let feed = registry.completion_feed_handle();
    let baseline = feed.watermark();

    // Register and complete a BackgroundToolOp.
    let bg_spec = background_spec("bg-arms");
    let bg_id = bg_spec.id.clone();
    registry.register_operation(bg_spec).unwrap();
    registry.provisioning_succeeded(&bg_id).unwrap();
    registry
        .complete_operation(&bg_id, op_result(&bg_id, "bg done"))
        .unwrap();

    // Register and complete a MobMemberChild.
    let mob_spec = mob_member_spec("mob-no-arm");
    let mob_id = mob_spec.id.clone();
    registry.register_operation(mob_spec).unwrap();
    registry.provisioning_succeeded(&mob_id).unwrap();
    registry
        .complete_operation(&mob_id, op_result(&mob_id, "mob done"))
        .unwrap();

    let batch = feed.list_since(baseline);
    let kinds: Vec<_> = batch.entries.iter().map(|e| e.kind).collect();
    assert!(
        kinds.contains(&OperationKind::BackgroundToolOp),
        "idle-wake filter depends on BackgroundToolOp entries appearing in the feed"
    );
    assert!(
        kinds.contains(&OperationKind::MobMemberChild),
        "idle-wake filter depends on MobMemberChild entries appearing so it can skip them"
    );
}