bamboo-engine 2026.9.19

Execution engine and orchestration for the Bamboo agent framework
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
use bamboo_agent_core::{
    ContextBlock, ContextBlockPriority, ContextBlockStability, ContextBlockType, Message, Session,
};

/// Structured request envelope separating the stable instructions, the
/// session-stable prefix messages, and the per-round dynamic context blocks. The
/// engine reads these three runs straight into the canonical [`PromptIR`]; the
/// conversation window and the wire-specific projections live on the IR, not here.
#[derive(Debug, Clone, Default)]
#[cfg(test)]
pub struct PromptEnvelope {
    pub stable_instructions: String,
    pub stable_prefix_messages: Vec<Message>,
    pub dynamic_context_messages: Vec<Message>,
}

#[derive(Debug, Clone)]
pub struct StablePromptFrame {
    pub stable_instructions: String,
    pub stable_prefix_messages: Vec<Message>,
}

impl StablePromptFrame {
    pub fn new(
        stable_instructions: impl Into<String>,
        stable_prefix_messages: Vec<Message>,
    ) -> Self {
        Self {
            stable_instructions: stable_instructions.into(),
            stable_prefix_messages,
        }
    }
}

/// Tell the model which authoritative Session is executing this request.
///
/// The block is session-stable and joins the append-only context ledger after
/// the cross-session-invariant system/tool-guide prefix. The value is useful
/// for orientation only; tools derive authorization from `ToolCtx` instead.
pub(crate) fn build_session_identity_context_block(session: &Session) -> ContextBlock {
    // Render as a JSON string so even a legacy/imported identifier containing
    // whitespace or control characters remains inert data in the prompt.
    let encoded_session_id =
        serde_json::to_string(&session.id).expect("Session ID string is JSON serializable");
    ContextBlock::new(
        ContextBlockType::SessionIdentity,
        ContextBlockPriority::Critical,
        ContextBlockStability::SessionStable,
        "Current Session Identity",
        format!(
            "Current Session ID: {encoded_session_id}\nTools authorize the caller from trusted runtime context, not from this prompt value."
        ),
    )
}

/// Build the single provider-visible Workspace block from authoritative
/// session metadata. Project identity is included only in its redacted,
/// path-free form so the active workspace path appears exactly once.
pub(crate) fn build_workspace_context_block(session: &Session) -> Option<ContextBlock> {
    let workspace = super::prompt_setup::workspace_context_from_session(session)?;
    let project = session
        .metadata
        .get(crate::project_context::PROJECT_CONTEXT_RENDERED_KEY)
        .map(String::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty());
    let content = project
        .into_iter()
        .chain(std::iter::once(workspace.trim()))
        .collect::<Vec<_>>()
        .join("\n\n");

    Some(ContextBlock::new(
        ContextBlockType::Workspace,
        ContextBlockPriority::High,
        ContextBlockStability::RoundDynamic,
        "Project & Workspace",
        content,
    ))
}

/// Build repository instructions from the authoritative workspace metadata,
/// never from a marker parsed out of System text.
pub(crate) fn build_instruction_overlay_context_block(session: &Session) -> Option<ContextBlock> {
    let workspace = session.workspace_path_meta()?;
    let content =
        crate::runtime::context::instruction::build_instruction_prompt_context(workspace.trim())?;
    Some(ContextBlock::new(
        ContextBlockType::InstructionOverlay,
        ContextBlockPriority::Critical,
        ContextBlockStability::RoundDynamic,
        "Project Instructions",
        content,
    ))
}

#[cfg(test)]
pub(crate) fn render_context_block_message(block: &ContextBlock) -> Message {
    block.render_runtime_context_message()
}

/// Assemble a [`PromptEnvelope`] from the stable frame and the per-round dynamic
/// context blocks. The conversation window is threaded directly into the IR by the
/// caller, so it is not stored here.
#[cfg(test)]
pub(crate) fn assemble_prompt_envelope(
    stable: StablePromptFrame,
    dynamic_blocks: Vec<ContextBlock>,
) -> PromptEnvelope {
    let dynamic_context_messages: Vec<Message> = dynamic_blocks
        .iter()
        .map(render_context_block_message)
        .collect();

    PromptEnvelope {
        stable_instructions: stable.stable_instructions,
        stable_prefix_messages: stable.stable_prefix_messages,
        dynamic_context_messages,
    }
}

pub(crate) fn build_task_list_context_block(session: &Session) -> Option<ContextBlock> {
    let content = session.format_task_list_for_prompt();
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return None;
    }

    let title = session
        .task_list
        .as_ref()
        .map(|task_list| format!("Current Task List: {}", task_list.title.trim()))
        .filter(|value| !value.trim().is_empty())
        .unwrap_or_else(|| "Current Task List".to_string());

    Some(ContextBlock::new(
        ContextBlockType::TaskSnapshot,
        ContextBlockPriority::High,
        ContextBlockStability::RoundDynamic,
        title,
        trimmed,
    ))
}

/// Rebuild the exact active instruction workflow from its durable LKG snapshot.
/// This is a dedicated host context block, never a synthetic user message in
/// session history and never a catalog/live-filesystem re-resolution.
pub(crate) fn build_active_workflow_context_block(session: &Session) -> Option<ContextBlock> {
    let durable = session
        .metadata
        .get(bamboo_skills::ACTIVE_WORKFLOW_SNAPSHOT_METADATA_KEY)
        .and_then(|raw| serde_json::from_str::<bamboo_skills::DurableWorkflowActivation>(raw).ok())
        .filter(|durable| {
            durable.active.status == bamboo_skills::WorkflowActivationStatus::Active
        })?;
    let entry = durable.snapshot.skills.get(&durable.active.id)?;
    if durable.snapshot.skills.len() != 1
        || entry.revision != durable.active.revision
        || entry.catalog_entry.source != durable.active.source
        || entry.catalog_entry.kind != bamboo_skills::WorkflowKind::Instruction
    {
        return None;
    }
    let dynamic = durable
        .active
        .dynamic_context
        .iter()
        .map(|block| {
            serde_json::json!({
                "provider_id": block.provider_id,
                "provenance": block.provenance,
                "status": block.status,
                "content": block.content,
                "diagnostic": block.diagnostic,
            })
        })
        .collect::<Vec<_>>();
    Some(
        ContextBlock::new(
            ContextBlockType::WorkflowRuntime,
            ContextBlockPriority::Critical,
            ContextBlockStability::SessionStable,
            format!("Active Workflow: {}@{}", durable.active.id, durable.active.revision),
            format!(
                "workflow_id: {}\nsource: {:?}\nrevision: {}\nargs: {}\ncontext_fingerprint: {}\n\n### Instructions\n{}\n\n### Dynamic Context\n{}",
                durable.active.id,
                durable.active.source,
                durable.active.revision,
                durable.active.args,
                durable
                    .active
                    .context_fingerprint
                    .as_deref()
                    .unwrap_or("unavailable"),
                entry.definition.prompt,
                serde_json::to_string(&dynamic).unwrap_or_else(|_| "[]".to_string()),
            ),
        )
        .with_metadata(Some(serde_json::json!({
            "workflow_id": durable.active.id,
            "source": durable.active.source,
            "revision": durable.active.revision,
            "context_fingerprint": durable.active.context_fingerprint,
        }))),
    )
}

/// Build the per-round session-goal block directly from the active goal.
///
/// Placed by the caller in the volatile tail (alongside task/memory/plan) so the
/// goal — which changes per session/round — never sits in the cached system
/// prefix. Replaces the old `inject_goal_into_system_message` path, which leaked
/// the goal into the `base` system block. Returns `None` when there is no goal.
pub(crate) fn build_goal_context_block(goal: Option<&str>) -> Option<ContextBlock> {
    let objective = goal.map(str::trim).filter(|value| !value.is_empty())?;
    Some(ContextBlock::new(
        ContextBlockType::GoalState,
        ContextBlockPriority::Critical,
        ContextBlockStability::RoundDynamic,
        "Session Goal",
        crate::runtime::runner::prompt_context::render_goal_section(objective),
    ))
}

/// Build context injected by `SessionStart` hooks as a volatile block. The
/// source strings live in the current run's structured runtime state, so they
/// never mutate or invalidate the cached base system prompt.
pub(crate) fn build_agent_hook_context_block(session: &Session) -> Option<ContextBlock> {
    let contexts = &session.agent_runtime_state.as_ref()?.hook_contexts;
    let content = contexts
        .iter()
        .map(|text| text.trim())
        .filter(|text| !text.is_empty())
        .collect::<Vec<_>>()
        .join("\n\n---\n\n");
    if content.is_empty() {
        return None;
    }
    Some(ContextBlock::new(
        ContextBlockType::AgentHookContext,
        ContextBlockPriority::High,
        ContextBlockStability::RoundDynamic,
        "Session Hook Context",
        content,
    ))
}

/// Build the per-round plan-mode block directly from session state (the active
/// `PlanModeState`), replacing the legacy inject-into-system + reparse path.
/// Returns `None` when plan mode is inactive.
pub(crate) fn build_plan_mode_context_block(session: &Session) -> Option<ContextBlock> {
    let text = crate::runtime::runner::prompt_context::render_plan_mode_section(session)?;
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(ContextBlock::new(
        ContextBlockType::PlanModeState,
        ContextBlockPriority::High,
        ContextBlockStability::RoundDynamic,
        "Plan Mode State",
        trimmed,
    ))
}

/// Build the per-round durable plan-execution block directly from session state
/// plus persisted plan artifacts, replacing the legacy inject + reparse path.
/// Returns `None` when plan mode is inactive.
pub(crate) fn build_plan_runtime_context_block(
    session: &Session,
    app_data_dir: Option<&std::path::Path>,
) -> Option<ContextBlock> {
    let text =
        crate::runtime::runner::prompt_context::render_plan_runtime_section(session, app_data_dir)?;
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(ContextBlock::new(
        ContextBlockType::PlanRuntimeState,
        ContextBlockPriority::High,
        ContextBlockStability::RoundDynamic,
        "Durable Plan Execution Context",
        trimmed,
    ))
}

/// Build the volatile external-memory block from the session field that the async
/// refresh populates (external memory is the one ASYNC volatile producer).
/// Returns `None` when there is no external memory this round.
pub(crate) fn build_external_memory_context_block(session: &Session) -> Option<ContextBlock> {
    let content = crate::runtime::runner::prompt_context::render_external_memory_section(session)?;
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(ContextBlock::new(
        ContextBlockType::ExternalMemory,
        ContextBlockPriority::Medium,
        ContextBlockStability::RoundDynamic,
        "External Memory (Persistent)",
        trimmed,
    ))
}

/// Per-round redacted Project resource inventory.
///
/// This intentionally rides the volatile tail instead of the system field:
/// watcher-driven `resource_revision` changes must not invalidate the
/// cacheable Project identity prefix.
pub(crate) fn build_project_resources_context_block(session: &Session) -> Option<ContextBlock> {
    let content = session
        .metadata
        .get(crate::project_context::PROJECT_RESOURCES_RENDERED_KEY)?;
    let trimmed = content.trim();
    if trimmed.is_empty() {
        return None;
    }
    Some(ContextBlock::new(
        ContextBlockType::ProjectResources,
        ContextBlockPriority::Medium,
        ContextBlockStability::RoundDynamic,
        "Project Shared Resources (redacted)",
        trimmed,
    ))
}

fn history_boundary_content(
    archive_boundaries: usize,
    archived_messages: usize,
    retained_recent_user_turns: usize,
) -> String {
    format!(
        "Earlier Session messages are stored exactly but omitted from the active model context.\n\
         Archive boundaries: {archive_boundaries}. Archived messages: {archived_messages}. \
         Recent complete user turns retained at the latest boundary: {retained_recent_user_turns}.\n\
         Use session_history_current with search_current to locate exact evidence, then \
         read_around or read_current for bounded raw history. Raw Session history is the \
         transcript authority. Memory is selective and may be stale; do not guess."
    )
}

fn history_boundary_block(
    archive_boundaries: usize,
    archived_messages: usize,
    retained_recent_user_turns: usize,
) -> ContextBlock {
    ContextBlock::new(
        ContextBlockType::HistoryBoundary,
        ContextBlockPriority::High,
        ContextBlockStability::RoundDynamic,
        "Archived Session History Boundary",
        history_boundary_content(
            archive_boundaries,
            archived_messages,
            retained_recent_user_turns,
        ),
    )
}

/// Build a non-semantic recovery marker from durable retrieval-window evidence.
pub(crate) fn build_history_boundary_context_block(session: &Session) -> Option<ContextBlock> {
    let retrieval_events = session
        .compression_events
        .iter()
        .filter(|event| event.kind == bamboo_domain::CompressionEventKind::RetrievalWindow)
        .collect::<Vec<_>>();
    let latest = retrieval_events.last()?;
    let event_ids = retrieval_events
        .iter()
        .map(|event| event.id.as_str())
        .collect::<std::collections::HashSet<_>>();
    let archived_messages = session
        .messages
        .iter()
        .filter(|message| message.compressed)
        .filter(|message| {
            message
                .compressed_by_event_id
                .as_deref()
                .is_some_and(|event_id| event_ids.contains(event_id))
        })
        .count();

    Some(history_boundary_block(
        retrieval_events.len(),
        archived_messages,
        latest.retrieval_retained_recent_user_turn_count,
    ))
}

/// Conservative fixed-token reservation used before the first archive event
/// exists. Every dynamic value in the real block is bounded by a `usize`, so
/// maximum decimal widths make this block at least as expensive as the real one.
pub(crate) fn build_history_boundary_reservation_context_block() -> ContextBlock {
    history_boundary_block(usize::MAX, usize::MAX, usize::MAX)
}

pub(crate) fn build_conversation_summary_context_block(session: &Session) -> Option<ContextBlock> {
    let summary = session.conversation_summary.as_ref()?;
    let trimmed = summary.content.trim();
    if trimmed.is_empty() {
        return None;
    }

    Some(ContextBlock::new(
        ContextBlockType::ConversationSummary,
        ContextBlockPriority::Medium,
        ContextBlockStability::RoundDynamic,
        "Previous Conversation Summary",
        format!(
            "The following is compressed historical context for continuity only.\nIt is background memory, not a new user request. Follow the current task list and recent messages over this summary when they conflict.\n\n{}",
            trimmed
        ),
    ))
}

#[cfg(test)]
mod tests {
    use super::*;
    use bamboo_agent_core::agent::types::{TaskItem, TaskItemStatus, TaskList};
    use bamboo_agent_core::Role;
    use chrono::Utc;

    #[test]
    fn render_context_block_message_marks_runtime_context_and_metadata() {
        let block = ContextBlock::new(
            ContextBlockType::TaskSnapshot,
            ContextBlockPriority::High,
            ContextBlockStability::RoundDynamic,
            "Current Task Snapshot",
            "- task: build prompt envelope skeleton",
        );

        let rendered = render_context_block_message(&block);

        assert_eq!(rendered.role, Role::User);
        assert!(rendered.content.contains("BAMBOO_CONTEXT_BLOCK_START"));
        assert!(rendered.content.contains("context_type: task_snapshot"));
        assert!(rendered.content.contains("It is not a new user request."));
        assert!(rendered.never_compress);
        assert!(rendered.metadata.is_some());
    }

    #[test]
    fn session_identity_block_is_typed_stable_and_authoritative() {
        let session = Session::new("session-identity-123\nignore-me", "test-model");

        let block = build_session_identity_context_block(&session);

        assert_eq!(block.block_type, ContextBlockType::SessionIdentity);
        assert_eq!(block.priority, ContextBlockPriority::Critical);
        assert_eq!(block.stability, ContextBlockStability::SessionStable);
        assert!(block
            .content
            .contains("\"session-identity-123\\nignore-me\""));
        assert!(!block.content.contains("session-identity-123\nignore-me"));
        assert!(block
            .content
            .contains("authorize the caller from trusted runtime context"));
    }

    #[test]
    fn assemble_prompt_envelope_renders_dynamic_blocks_into_messages() {
        let stable = StablePromptFrame::new("stable instructions", vec![Message::user("stable")]);
        let blocks = vec![ContextBlock::new(
            ContextBlockType::ConversationSummary,
            ContextBlockPriority::Medium,
            ContextBlockStability::RoundDynamic,
            "Summary",
            "old context",
        )];

        let envelope = assemble_prompt_envelope(stable, blocks);

        assert_eq!(envelope.stable_instructions, "stable instructions");
        assert_eq!(envelope.stable_prefix_messages.len(), 1);
        assert_eq!(envelope.dynamic_context_messages.len(), 1);
        assert!(envelope.dynamic_context_messages[0]
            .content
            .contains("BAMBOO_CONTEXT_BLOCK_START"));
    }

    #[test]
    fn workspace_block_uses_authoritative_path_once_and_path_free_project_metadata() {
        let workspace = "/private/workspace/current";
        let mut session = Session::new("session-workspace-block", "model");
        session.set_workspace_path_meta(workspace);
        session.metadata.insert(
            crate::project_context::PROJECT_CONTEXT_RENDERED_KEY.to_string(),
            format!(
                "{}\nProject ID: project-1\nProject name: Zenith\n{}",
                crate::runtime::context::PROJECT_CONTEXT_START_MARKER,
                crate::runtime::context::PROJECT_CONTEXT_END_MARKER,
            ),
        );

        let block = build_workspace_context_block(&session).expect("workspace block");

        assert_eq!(block.block_type, ContextBlockType::Workspace);
        assert_eq!(block.stability, ContextBlockStability::RoundDynamic);
        assert_eq!(block.content.matches(workspace).count(), 1);
        assert!(block.content.contains("Project ID: project-1"));
        assert!(!block.content.contains("Project path:"));
        assert!(!block.content.contains("Project home"));
    }

    #[test]
    fn build_task_list_context_block_uses_formatted_prompt_content() {
        let mut session = Session::new("session-task-block", "model");
        session.task_list = Some(TaskList {
            session_id: session.id.clone(),
            title: "Agent Tasks".to_string(),
            items: vec![TaskItem {
                id: "task-1".to_string(),
                description: "Implement prompt envelope".to_string(),
                status: TaskItemStatus::InProgress,
                ..TaskItem::default()
            }],
            created_at: Utc::now(),
            updated_at: Utc::now(),
        });

        let block = build_task_list_context_block(&session).expect("task block should exist");

        assert_eq!(block.block_type, ContextBlockType::TaskSnapshot);
        assert_eq!(block.priority, ContextBlockPriority::High);
        assert!(block.content.contains("Current Task List"));
        assert!(block.content.contains("Implement prompt envelope"));
    }

    #[test]
    fn build_external_memory_context_block_reads_session_field() {
        let mut session = Session::new("session-external-memory-block", "model");
        session.metadata.insert(
            crate::runtime::runner::prompt_context::EXTERNAL_MEMORY_RENDERED_KEY.to_string(),
            "## External Memory (Persistent)\n\nSession note body".to_string(),
        );

        let block = build_external_memory_context_block(&session)
            .expect("external memory block should exist");

        assert_eq!(block.block_type, ContextBlockType::ExternalMemory);
        assert_eq!(block.priority, ContextBlockPriority::Medium);
        assert!(block.content.contains("## External Memory (Persistent)"));
        assert!(block.content.contains("Session note body"));
        // No external memory field → no block.
        assert!(build_external_memory_context_block(&Session::new("s2", "model")).is_none());
    }

    #[test]
    fn project_resources_context_block_is_round_dynamic_and_redacted() {
        let mut session = Session::new("project-resources", "model");
        session.metadata.insert(
            crate::project_context::PROJECT_RESOURCES_RENDERED_KEY.to_string(),
            "Project ID: project-1\nResource revision: 3\n- Skills: status=available, items=2"
                .to_string(),
        );
        let block =
            build_project_resources_context_block(&session).expect("project resource block");
        assert_eq!(block.block_type, ContextBlockType::ProjectResources);
        assert_eq!(block.stability, ContextBlockStability::RoundDynamic);
        assert!(block.content.contains("Resource revision: 3"));
        assert!(!block.content.contains("secret"));
    }

    #[test]
    fn build_agent_hook_context_block_reads_runtime_state_as_volatile_context() {
        let mut session = Session::new("session-hook-block", "model");
        let mut state = bamboo_domain::AgentRuntimeState::new("run-hook");
        state.hook_contexts = vec!["first hook context".to_string(), "second".to_string()];
        session.agent_runtime_state = Some(state);

        let block = build_agent_hook_context_block(&session).expect("hook block should exist");

        assert_eq!(block.block_type, ContextBlockType::AgentHookContext);
        assert_eq!(block.priority, ContextBlockPriority::High);
        assert_eq!(block.stability, ContextBlockStability::RoundDynamic);
        assert!(block.content.contains("first hook context"));
        assert!(block.content.contains("second"));
        assert!(build_agent_hook_context_block(&Session::new("empty", "model")).is_none());
    }

    #[test]
    fn build_plan_mode_context_block_renders_from_session_state() {
        use bamboo_domain::session::runtime_state::{
            AgentRuntimeState, PlanModeState, PlanModeStatus,
        };
        let mut session = Session::new("session-plan-mode-block", "model");
        session.agent_runtime_state = Some(AgentRuntimeState::new("run-1"));
        session.agent_runtime_state.as_mut().unwrap().plan_mode = Some(PlanModeState {
            entered_at: chrono::Utc::now(),
            pre_permission_mode: "default".to_string(),
            plan_file_path: None,
            status: PlanModeStatus::Exploring,
        });

        let block = build_plan_mode_context_block(&session).expect("plan mode block should exist");

        assert_eq!(block.block_type, ContextBlockType::PlanModeState);
        assert_eq!(block.priority, ContextBlockPriority::High);
        assert!(block.content.contains("PLAN MODE ACTIVE"));
        // Inactive plan mode → no block.
        assert!(build_plan_mode_context_block(&Session::new("s2", "model")).is_none());
    }

    #[test]
    fn build_plan_runtime_context_block_renders_from_session_state() {
        use bamboo_domain::session::runtime_state::{
            AgentRuntimeState, PlanModeState, PlanModeStatus,
        };
        let mut session = Session::new("session-plan-runtime-block", "model");
        session.agent_runtime_state = Some(AgentRuntimeState::new("run-1"));
        session.agent_runtime_state.as_mut().unwrap().plan_mode = Some(PlanModeState {
            entered_at: chrono::Utc::now(),
            pre_permission_mode: "default".to_string(),
            plan_file_path: None,
            status: PlanModeStatus::Designing,
        });

        let block = build_plan_runtime_context_block(&session, None)
            .expect("plan runtime block should exist");

        assert_eq!(block.block_type, ContextBlockType::PlanRuntimeState);
        assert_eq!(block.priority, ContextBlockPriority::High);
        assert!(block.content.contains("DURABLE PLAN EXECUTION CONTEXT"));
        // Inactive plan mode → no block.
        assert!(build_plan_runtime_context_block(&Session::new("s2", "model"), None).is_none());
    }

    #[test]
    fn build_conversation_summary_context_block_wraps_summary_content() {
        let mut session = Session::new("session-summary-block", "model");
        session.conversation_summary = Some(bamboo_agent_core::ConversationSummary::new(
            "Older work was compressed.",
            3,
            120,
        ));

        let block =
            build_conversation_summary_context_block(&session).expect("summary block should exist");

        assert_eq!(block.block_type, ContextBlockType::ConversationSummary);
        assert_eq!(block.priority, ContextBlockPriority::Medium);
        assert!(block.content.contains("compressed historical context"));
        assert!(block.content.contains("Older work was compressed."));
    }

    #[test]
    fn history_boundary_rehydrates_without_raw_history_content() {
        let mut session = Session::new("session-history-boundary", "model");
        let mut event = bamboo_domain::CompressionEvent::new(
            1,
            1,
            82.0,
            58.0,
            0,
            bamboo_domain::CompressionTriggerType::Auto,
            0.0,
            None,
            0,
        );
        event.kind = bamboo_domain::CompressionEventKind::RetrievalWindow;
        event.retrieval_retained_recent_user_turn_count = 3;
        let event_id = event.id.clone();
        let mut archived = Message::user("private archived transcript body");
        archived.compressed = true;
        archived.compressed_by_event_id = Some(event_id);
        session.messages.push(archived);
        session.compression_events.push(event);

        let block = build_history_boundary_context_block(&session).expect("history boundary");
        assert_eq!(block.block_type, ContextBlockType::HistoryBoundary);
        assert_eq!(block.stability, ContextBlockStability::RoundDynamic);
        assert!(block.content.contains("Archived messages: 1"));
        assert!(block.content.contains("session_history_current"));
        assert!(block
            .content
            .contains("Memory is selective and may be stale"));
        assert!(!block.content.contains("private archived transcript body"));

        let bytes = serde_json::to_vec(&session).unwrap();
        let restored: Session = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(
            build_history_boundary_context_block(&restored)
                .expect("boundary after reload")
                .content,
            block.content
        );
        assert!(
            build_history_boundary_reservation_context_block()
                .content
                .len()
                >= block.content.len()
        );
    }

    #[test]
    fn history_boundary_is_absent_without_retrieval_event() {
        assert!(build_history_boundary_context_block(&Session::new("plain", "model")).is_none());
    }
}