awaken-runtime 0.6.0

Phase-based execution engine, plugin system, and agent loop for Awaken
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
774
use super::*;
use std::time::Duration;

use async_trait::async_trait;
use awaken_runtime_contract::contract::executor::{
    InferenceExecutionError, InferenceRequest, LlmExecutor,
};
use awaken_runtime_contract::contract::identity::RunIdentity;
use awaken_runtime_contract::contract::inference::{StopReason, StreamResult, TokenUsage};
use awaken_runtime_contract::contract::message::{Message, gen_message_id};
use tokio::sync::Notify;

use awaken_runtime_contract::contract::event_sink::{EventSink, NullEventSink};
use awaken_runtime_contract::contract::identity::RunOrigin;

use crate::cancellation::CancellationToken;
use crate::context::{
    COMPACTION_COMPLETED_EVENT, COMPACTION_FAILED_EVENT, COMPACTION_SKIP_REASON_MIN_SAVINGS_RATIO,
    COMPACTION_SKIPPED_EVENT, COMPACTION_STARTED_EVENT, CompactionConfig, CompactionConfigKey,
    CompactionPlugin, CompactionStateKey, ContextSummarizer, SummarizationError, TruncationState,
};
use crate::extensions::background::{BackgroundTaskManager, BackgroundTaskPlugin};
use crate::phase::{ExecutionEnv, PhaseRuntime};
use crate::plugins::Plugin;
use crate::registry::ResolvedAgent;
use crate::state::StateStore;

struct GatedSummarizer {
    gate: Arc<Notify>,
    summary: String,
    observed: Arc<std::sync::atomic::AtomicUsize>,
}

#[async_trait]
impl ContextSummarizer for GatedSummarizer {
    async fn summarize(
        &self,
        _transcript: &str,
        _previous_summary: Option<&str>,
        _executor: &dyn LlmExecutor,
    ) -> Result<String, SummarizationError> {
        self.observed
            .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        self.gate.notified().await;
        Ok(self.summary.clone())
    }
}

/// Summarizer that always fails. Used to drive the failure round-trip.
struct FailingSummarizer {
    gate: Arc<Notify>,
    message: String,
}

#[async_trait]
impl ContextSummarizer for FailingSummarizer {
    async fn summarize(
        &self,
        _transcript: &str,
        _previous_summary: Option<&str>,
        _executor: &dyn LlmExecutor,
    ) -> Result<String, SummarizationError> {
        self.gate.notified().await;
        Err(SummarizationError::Inference(self.message.clone()))
    }
}

/// Summarizer that records the transcript / previous_summary it received
/// so tests can assert what the spawn helper actually plumbed through.
struct CapturingSummarizer {
    gate: Arc<Notify>,
    captured_transcript: Arc<std::sync::Mutex<Option<String>>>,
    captured_previous: Arc<std::sync::Mutex<Option<Option<String>>>>,
}

#[async_trait]
impl ContextSummarizer for CapturingSummarizer {
    async fn summarize(
        &self,
        transcript: &str,
        previous_summary: Option<&str>,
        _executor: &dyn LlmExecutor,
    ) -> Result<String, SummarizationError> {
        *self.captured_transcript.lock().unwrap() = Some(transcript.to_string());
        *self.captured_previous.lock().unwrap() = Some(previous_summary.map(|s| s.to_string()));
        self.gate.notified().await;
        Ok("captured".into())
    }
}

struct NoopExecutor;

#[async_trait]
impl LlmExecutor for NoopExecutor {
    async fn execute(
        &self,
        _request: InferenceRequest,
    ) -> Result<StreamResult, InferenceExecutionError> {
        Ok(StreamResult {
            content: vec![],
            tool_calls: vec![],
            usage: Some(TokenUsage::default()),
            stop_reason: Some(StopReason::EndTurn),
            has_incomplete_tool_calls: false,
        })
    }
    fn name(&self) -> &str {
        "noop"
    }
}

fn make_long_messages() -> Vec<Arc<Message>> {
    let mut messages: Vec<Arc<Message>> = (0..6)
        .map(|i| {
            if i % 2 == 0 {
                Arc::new(Message::user("filler ".repeat(600)))
            } else {
                Arc::new(Message::assistant("ack"))
            }
        })
        .collect();
    messages.push(Arc::new(Message::user("recent")));
    messages
}

fn default_policy() -> awaken_runtime_contract::contract::inference::ContextWindowPolicy {
    awaken_runtime_contract::contract::inference::ContextWindowPolicy {
        compaction_raw_suffix_messages: 1,
        ..Default::default()
    }
}

fn make_resolved_agent(
    manager: Arc<BackgroundTaskManager>,
    summarizer: Arc<dyn ContextSummarizer>,
) -> ResolvedAgent {
    ResolvedAgent::new(
        "test-agent",
        "test-model",
        "system prompt",
        Arc::new(NoopExecutor),
    )
    .with_context_summarizer(summarizer)
    .with_background_manager(manager)
}

fn set_compaction_config(agent: &mut ResolvedAgent, config: CompactionConfig) {
    Arc::make_mut(&mut agent.spec)
        .set_config::<CompactionConfigKey>(config)
        .unwrap();
}

fn make_phase_runtime(
    manager: &Arc<BackgroundTaskManager>,
) -> (PhaseRuntime, StateStore, ExecutionEnv) {
    let store = StateStore::new();
    let runtime = PhaseRuntime::new(store.clone()).expect("runtime");
    manager.set_store(store.clone());
    let plugin: Arc<dyn Plugin> = Arc::new(BackgroundTaskPlugin::new(manager.clone()));
    let env = ExecutionEnv::from_plugins(&[plugin], &Default::default()).unwrap();
    store.register_keys(&env.key_registrations).unwrap();
    store.install_plugin(CompactionPlugin::default()).unwrap();
    (runtime, store, env)
}

fn run_identity(thread_id: &str) -> RunIdentity {
    RunIdentity::new(
        thread_id.to_string(),
        None,
        gen_message_id(),
        None,
        "agent".to_string(),
        RunOrigin::User,
    )
}

async fn recv_inbox_event(rx: &mut crate::inbox::InboxReceiver) -> serde_json::Value {
    tokio::time::timeout(Duration::from_secs(2), rx.recv_or_cancel(None))
        .await
        .expect("event arrives in time")
        .expect("event present")
}

#[path = "compaction_lifecycle_tests.rs"]
mod lifecycle_tests;

#[test]
fn reserve_compaction_in_flight_allows_only_one_concurrent_reservation() {
    let store = StateStore::new();
    store
        .install_plugin(CompactionPlugin::default())
        .expect("compaction key registered");
    let workers = 16;
    let barrier = Arc::new(std::sync::Barrier::new(workers));
    let successes = Arc::new(std::sync::atomic::AtomicUsize::new(0));

    std::thread::scope(|scope| {
        for idx in 0..workers {
            let store = store.clone();
            let barrier = barrier.clone();
            let successes = successes.clone();
            scope.spawn(move || {
                barrier.wait();
                let reserved = reserve_compaction_in_flight(
                    &store,
                    crate::context::CompactionInFlight {
                        task_id: format!("task-{idx}"),
                        boundary_message_id: format!("boundary-{idx}"),
                        started_at_ms: idx as u64,
                    },
                )
                .expect("reservation should not error");
                if reserved {
                    successes.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                }
            });
        }
    });

    assert_eq!(
        successes.load(std::sync::atomic::Ordering::SeqCst),
        1,
        "CAS reservation must allow exactly one in-flight compaction"
    );
}

#[tokio::test]
async fn maybe_spawn_compaction_emits_event_after_summary_completes() {
    use awaken_runtime_contract::contract::inference::ContextWindowPolicy;

    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);

    let (inbox_tx, mut inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    let gate = Arc::new(Notify::new());
    let observed = Arc::new(std::sync::atomic::AtomicUsize::new(0));
    let summarizer = Arc::new(GatedSummarizer {
        gate: gate.clone(),
        summary: "synthetic summary text".into(),
        observed: observed.clone(),
    });

    let mut agent = make_resolved_agent(manager.clone(), summarizer);
    agent.env = env;
    let mut messages = make_long_messages();
    let identity = run_identity("thread-bg-compact");
    let cancel = CancellationToken::new();
    let policy = ContextWindowPolicy {
        compaction_raw_suffix_messages: 1,
        ..Default::default()
    };
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    let mut ctx = StepContext {
        agent: &mut agent,
        messages: &mut messages,
        runtime: &runtime,
        sink,
        checkpoint_store: None,
        commit: crate::loop_runner::CommitWiring::default(),
        run_identity: &identity,
        input_message_count: 0,
        cancellation_token: Some(&cancel),
        run_overrides: &None,
        total_input_tokens: &mut total_in,
        total_output_tokens: &mut total_out,
        truncation_state: &mut truncation,
        run_created_at: 0,
        thread_ctx: None,
    };

    // Summarizer is gated → spawn returns immediately, in_flight set,
    // background task is parked at the gate.
    let spawned = maybe_spawn_compaction(&mut ctx, &policy).await;
    assert!(spawned, "compaction should have been spawned");
    let mid_state = store.read::<CompactionStateKey>().unwrap();
    assert!(mid_state.is_compacting(), "in-flight must be set");
    let boundary_message_id = mid_state.in_flight.unwrap().boundary_message_id;
    let started = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(started["kind"], "custom");
    assert_eq!(started["event_type"], COMPACTION_STARTED_EVENT);
    assert_eq!(
        started["payload"]["boundary_message_id"].as_str(),
        Some(boundary_message_id.as_str())
    );

    // A second call must be a no-op while the first is still running.
    let again = maybe_spawn_compaction(&mut ctx, &policy).await;
    assert!(!again, "single-flight guard must reject second spawn");

    // Release the gate; wait for the inbox event to arrive.
    gate.notify_one();
    let payload = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(payload["kind"], "custom");
    assert_eq!(payload["event_type"], COMPACTION_COMPLETED_EVENT);
    assert_eq!(payload["payload"]["summary"], "synthetic summary text");
    assert_eq!(
        observed.load(std::sync::atomic::Ordering::SeqCst),
        1,
        "summarizer entered exactly once"
    );
}

/// Without a manager, spawn must be a no-op even if a summarizer is set.
/// This is the documented gating contract.
#[tokio::test]
async fn maybe_spawn_compaction_no_op_without_background_manager() {
    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);
    let (inbox_tx, _inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    // Build an agent with a summarizer but DROP the background manager.
    let summarizer: Arc<dyn ContextSummarizer> = Arc::new(GatedSummarizer {
        gate: Arc::new(Notify::new()),
        summary: "unused".into(),
        observed: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
    });
    let mut agent = ResolvedAgent::new(
        "test-agent",
        "test-model",
        "system prompt",
        Arc::new(NoopExecutor),
    )
    .with_context_summarizer(summarizer);
    agent.env = env;
    let mut messages = make_long_messages();
    let identity = run_identity("thread-no-mgr");
    let cancel = CancellationToken::new();
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    let mut ctx = StepContext {
        agent: &mut agent,
        messages: &mut messages,
        runtime: &runtime,
        sink,
        checkpoint_store: None,
        commit: crate::loop_runner::CommitWiring::default(),
        run_identity: &identity,
        input_message_count: 0,
        cancellation_token: Some(&cancel),
        run_overrides: &None,
        total_input_tokens: &mut total_in,
        total_output_tokens: &mut total_out,
        truncation_state: &mut truncation,
        run_created_at: 0,
        thread_ctx: None,
    };

    assert!(!maybe_spawn_compaction(&mut ctx, &default_policy()).await);
    assert!(
        !store
            .read::<CompactionStateKey>()
            .is_some_and(|s| s.is_compacting()),
        "no in-flight should be recorded"
    );
}

/// Without a summarizer, spawn must be a no-op — the manager alone is not
/// enough to enable compaction.
#[tokio::test]
async fn maybe_spawn_compaction_no_op_without_summarizer() {
    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);
    let (inbox_tx, _inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    let mut agent = ResolvedAgent::new(
        "test-agent",
        "test-model",
        "system prompt",
        Arc::new(NoopExecutor),
    )
    .with_background_manager(manager.clone());
    agent.env = env;
    let mut messages = make_long_messages();
    let identity = run_identity("thread-no-sum");
    let cancel = CancellationToken::new();
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    let mut ctx = StepContext {
        agent: &mut agent,
        messages: &mut messages,
        runtime: &runtime,
        sink,
        checkpoint_store: None,
        commit: crate::loop_runner::CommitWiring::default(),
        run_identity: &identity,
        input_message_count: 0,
        cancellation_token: Some(&cancel),
        run_overrides: &None,
        total_input_tokens: &mut total_in,
        total_output_tokens: &mut total_out,
        truncation_state: &mut truncation,
        run_created_at: 0,
        thread_ctx: None,
    };

    assert!(!maybe_spawn_compaction(&mut ctx, &default_policy()).await);
    assert!(
        !store
            .read::<CompactionStateKey>()
            .is_some_and(|s| s.is_compacting()),
        "no in-flight should be recorded"
    );
}

/// When the message list is short, plan_compaction returns None and spawn
/// must NOT touch the in-flight marker. Avoids triggering background work
/// for a useless summary that would not save tokens.
#[tokio::test]
async fn maybe_spawn_compaction_no_op_when_no_useful_boundary() {
    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);
    let (inbox_tx, _inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    let summarizer: Arc<dyn ContextSummarizer> = Arc::new(GatedSummarizer {
        gate: Arc::new(Notify::new()),
        summary: "unused".into(),
        observed: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
    });
    let mut agent = make_resolved_agent(manager.clone(), summarizer);
    agent.env = env;
    // Three short messages: nowhere near MIN_COMPACTION_GAIN_TOKENS.
    let mut messages: Vec<Arc<Message>> = vec![
        Arc::new(Message::user("hello")),
        Arc::new(Message::assistant("hi")),
        Arc::new(Message::user("again")),
    ];
    let identity = run_identity("thread-tiny");
    let cancel = CancellationToken::new();
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    let mut ctx = StepContext {
        agent: &mut agent,
        messages: &mut messages,
        runtime: &runtime,
        sink,
        checkpoint_store: None,
        commit: crate::loop_runner::CommitWiring::default(),
        run_identity: &identity,
        input_message_count: 0,
        cancellation_token: Some(&cancel),
        run_overrides: &None,
        total_input_tokens: &mut total_in,
        total_output_tokens: &mut total_out,
        truncation_state: &mut truncation,
        run_created_at: 0,
        thread_ctx: None,
    };

    assert!(!maybe_spawn_compaction(&mut ctx, &default_policy()).await);
    assert!(
        !store
            .read::<CompactionStateKey>()
            .is_some_and(|s| s.is_compacting()),
        "in-flight must remain unset"
    );
}

/// End-to-end failure: spawn → summarizer errs → failure event flows
/// back → consume → in-flight cleared, no boundary recorded.
#[tokio::test]
async fn round_trip_failure_clears_in_flight() {
    use crate::context::try_consume_compaction_event;

    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);
    let (inbox_tx, mut inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    let gate = Arc::new(Notify::new());
    let summarizer: Arc<dyn ContextSummarizer> = Arc::new(FailingSummarizer {
        gate: gate.clone(),
        message: "upstream timeout".into(),
    });
    let mut agent = make_resolved_agent(manager.clone(), summarizer);
    agent.env = env;
    let mut messages = make_long_messages();
    let identity = run_identity("thread-failure");
    let cancel = CancellationToken::new();
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    {
        let mut ctx = StepContext {
            agent: &mut agent,
            messages: &mut messages,
            runtime: &runtime,
            sink: sink.clone(),
            checkpoint_store: None,
            commit: crate::loop_runner::CommitWiring::default(),
            run_identity: &identity,
            input_message_count: 0,
            cancellation_token: Some(&cancel),
            run_overrides: &None,
            total_input_tokens: &mut total_in,
            total_output_tokens: &mut total_out,
            truncation_state: &mut truncation,
            run_created_at: 0,
            thread_ctx: None,
        };
        assert!(maybe_spawn_compaction(&mut ctx, &default_policy()).await);
    }
    let mid = store.read::<CompactionStateKey>().unwrap();
    assert!(mid.is_compacting());
    let started = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(started["event_type"], COMPACTION_STARTED_EVENT);

    gate.notify_one();
    let payload = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(payload["event_type"], COMPACTION_FAILED_EVENT);
    let err_text = payload["payload"]["error"].as_str().expect("error string");
    assert!(
        err_text.contains("upstream timeout"),
        "error payload should surface underlying message: {err_text}"
    );

    let consumed = try_consume_compaction_event(&mut messages, &payload, runtime.store());
    assert!(consumed);
    let after = store.read::<CompactionStateKey>().unwrap();
    assert!(!after.is_compacting(), "in-flight cleared after failure");
    assert!(
        after.boundaries.is_empty(),
        "failure must not record a boundary"
    );
}

/// Snapshot isolation: messages appended to the live list AFTER spawn
/// must not appear in the transcript handed to the summarizer. The plan
/// captures the transcript at trigger time and the background closure
/// owns it for the duration of the LLM call.
#[tokio::test]
async fn background_summarizer_uses_snapshot_not_live_messages() {
    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);
    let (inbox_tx, mut inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    let gate = Arc::new(Notify::new());
    let captured_transcript = Arc::new(std::sync::Mutex::new(None));
    let captured_previous = Arc::new(std::sync::Mutex::new(None));
    let summarizer: Arc<dyn ContextSummarizer> = Arc::new(CapturingSummarizer {
        gate: gate.clone(),
        captured_transcript: captured_transcript.clone(),
        captured_previous: captured_previous.clone(),
    });
    let mut agent = make_resolved_agent(manager.clone(), summarizer);
    agent.env = env;
    let mut messages = make_long_messages();
    let identity = run_identity("thread-snapshot");
    let cancel = CancellationToken::new();
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    {
        let mut ctx = StepContext {
            agent: &mut agent,
            messages: &mut messages,
            runtime: &runtime,
            sink: sink.clone(),
            checkpoint_store: None,
            commit: crate::loop_runner::CommitWiring::default(),
            run_identity: &identity,
            input_message_count: 0,
            cancellation_token: Some(&cancel),
            run_overrides: &None,
            total_input_tokens: &mut total_in,
            total_output_tokens: &mut total_out,
            truncation_state: &mut truncation,
            run_created_at: 0,
            thread_ctx: None,
        };
        assert!(maybe_spawn_compaction(&mut ctx, &default_policy()).await);
    }

    // Mutate the live list AFTER spawn — this must NOT reach the summarizer.
    messages.push(Arc::new(Message::user(
        "POSTSPAWN-MARKER-do-not-include-me",
    )));

    gate.notify_one();
    let started = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(started["event_type"], COMPACTION_STARTED_EVENT);
    let completed = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(completed["event_type"], COMPACTION_COMPLETED_EVENT);

    let transcript = captured_transcript.lock().unwrap().clone().unwrap();
    assert!(
        !transcript.contains("POSTSPAWN-MARKER"),
        "snapshot leaked live messages: {transcript}"
    );
    assert!(
        transcript.contains("filler"),
        "snapshot must contain pre-spawn content"
    );

    // Sanity: in-flight cleared after we drain the event in real flow,
    // but here we only consumed via inbox_rx so the marker may still be set.
    let _ = store; // suppress unused warning
}

/// Cumulative summarization: when an internal_system <conversation-summary>
/// already exists in the message list, plan_compaction extracts it and
/// the spawn helper hands it to the summarizer as previous_summary so the
/// next pass produces an incremental update rather than re-summarizing
/// already-summarized content.
#[tokio::test]
async fn previous_summary_is_passed_to_summarizer_on_subsequent_pass() {
    let manager = Arc::new(BackgroundTaskManager::new());
    let (runtime, store, env) = make_phase_runtime(&manager);
    let (inbox_tx, mut inbox_rx) = crate::inbox::inbox_channel();
    manager.set_owner_inbox(inbox_tx);

    let gate = Arc::new(Notify::new());
    let captured_transcript = Arc::new(std::sync::Mutex::new(None));
    let captured_previous = Arc::new(std::sync::Mutex::new(None));
    let summarizer: Arc<dyn ContextSummarizer> = Arc::new(CapturingSummarizer {
        gate: gate.clone(),
        captured_transcript: captured_transcript.clone(),
        captured_previous: captured_previous.clone(),
    });
    let mut agent = make_resolved_agent(manager.clone(), summarizer);
    agent.env = env;

    // Pre-existing summary at the head, then plenty of content after.
    let mut messages: Vec<Arc<Message>> = Vec::new();
    messages.push(Arc::new(Message::internal_system(
        "<conversation-summary>\nFirst pass summary text\n</conversation-summary>",
    )));
    for i in 0..6 {
        if i % 2 == 0 {
            messages.push(Arc::new(Message::user("filler ".repeat(600))));
        } else {
            messages.push(Arc::new(Message::assistant("ack")));
        }
    }
    messages.push(Arc::new(Message::user("recent")));

    let identity = run_identity("thread-cumulative");
    let cancel = CancellationToken::new();
    let mut total_in = 0u64;
    let mut total_out = 0u64;
    let mut truncation = TruncationState::default();
    let sink: Arc<dyn EventSink> = Arc::new(NullEventSink);

    {
        let mut ctx = StepContext {
            agent: &mut agent,
            messages: &mut messages,
            runtime: &runtime,
            sink: sink.clone(),
            checkpoint_store: None,
            commit: crate::loop_runner::CommitWiring::default(),
            run_identity: &identity,
            input_message_count: 0,
            cancellation_token: Some(&cancel),
            run_overrides: &None,
            total_input_tokens: &mut total_in,
            total_output_tokens: &mut total_out,
            truncation_state: &mut truncation,
            run_created_at: 0,
            thread_ctx: None,
        };
        assert!(maybe_spawn_compaction(&mut ctx, &default_policy()).await);
    }

    gate.notify_one();
    let started = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(started["event_type"], COMPACTION_STARTED_EVENT);
    let completed = recv_inbox_event(&mut inbox_rx).await;
    assert_eq!(completed["event_type"], COMPACTION_COMPLETED_EVENT);

    let prev = captured_previous.lock().unwrap().clone().unwrap();
    assert_eq!(
        prev.as_deref(),
        Some("First pass summary text"),
        "summarizer must receive the existing summary for cumulative update"
    );
    let _ = store;
}

/// Robustness: completion event with a missing/empty summary or boundary
/// id must not panic and must still clear the in-flight marker. Defends
/// against a faulty background task that emits a malformed payload.
#[test]
fn try_consume_compaction_event_handles_malformed_payload() {
    use crate::context::{
        CompactionInFlight, CompactionStateKey, record_compaction_in_flight,
        try_consume_compaction_event,
    };
    use crate::state::MutationBatch;
    use serde_json::json;

    let store = StateStore::new();
    store.install_plugin(CompactionPlugin::default()).unwrap();

    let mut messages: Vec<Arc<Message>> = vec![Arc::new(Message::user("only one"))];
    let mut batch = MutationBatch::new();
    batch.update::<CompactionStateKey>(record_compaction_in_flight(CompactionInFlight {
        task_id: "bg_77".into(),
        boundary_message_id: "any".into(),
        started_at_ms: 1,
    }));
    store.commit(batch).unwrap();
    assert!(store.read::<CompactionStateKey>().unwrap().is_compacting());

    // Missing payload entirely.
    let bad = json!({
        "kind": "custom",
        "task_id": "bg_77",
        "event_type": "context.compacted",
    });
    let consumed = try_consume_compaction_event(&mut messages, &bad, &store);
    assert!(consumed, "malformed compaction event still consumed");
    let state = store.read::<CompactionStateKey>().unwrap();
    assert!(
        !state.is_compacting(),
        "in-flight cleared even with malformed payload"
    );
    assert!(
        state.boundaries.is_empty(),
        "no boundary recorded for malformed payload"
    );
    assert_eq!(
        messages.len(),
        1,
        "live messages untouched on malformed payload"
    );
}

/// Persisted-state durability: CompactionInFlight must round-trip through
/// JSON so a process restart preserves the marker. The orchestrator
/// relies on the marker reaching the next process to suppress a
/// duplicate compaction during recovery.
#[test]
fn compaction_in_flight_serde_roundtrips() {
    use crate::context::{CompactionInFlight, CompactionState};

    let state = CompactionState {
        in_flight: Some(CompactionInFlight {
            task_id: "bg_persisted".into(),
            boundary_message_id: "msg-id-stable".into(),
            started_at_ms: 4242,
        }),
        ..CompactionState::default()
    };

    let json = serde_json::to_string(&state).expect("serialize");
    let parsed: CompactionState = serde_json::from_str(&json).expect("deserialize");
    let live = parsed.in_flight.expect("in-flight survives roundtrip");
    assert_eq!(live.task_id, "bg_persisted");
    assert_eq!(live.boundary_message_id, "msg-id-stable");
    assert_eq!(live.started_at_ms, 4242);
}