bamboo-engine 2026.7.27

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
//! Minimal round prelude — provides `prepare_round` for lifecycle adapter
//! and `refresh_round_prompt_context` for the pipeline.

use std::sync::Arc;

use tokio_util::sync::CancellationToken;

use crate::runtime::config::AgentLoopConfig;
use crate::runtime::task_context::TaskLoopContext;
use bamboo_agent_core::tools::ToolExecutor;
use bamboo_agent_core::{AgentError, Role, Session};
use bamboo_llm::LLMProvider;
use bamboo_metrics::MetricsCollector;

use super::prompt_context::{
    refresh_external_memory_context, PromptMemoryRuntimeContext, PROMPT_MEMORY_OBSERVABILITY_KEY,
};
use super::session_setup::prompt_setup::{persist_prompt_snapshot_metadata, PromptAssemblyReport};
use bamboo_agent_core::PromptSnapshot;

/// Round-prelude frame bundling per-round identification and observability
/// parameters.  Passed into [`prepare_round`] to keep its parameter count
/// below the clippy threshold.
pub(crate) struct RoundPreludeFrame<'a> {
    pub round: usize,
    pub max_rounds: usize,
    pub debug_enabled: bool,
    pub cancel_token: &'a CancellationToken,
    pub metrics_collector: Option<&'a MetricsCollector>,
    pub session_id: &'a str,
    pub model_name: &'a str,
}

// ---- prompt_updates functions ----

const RUNTIME_PROMPT_FLAGS_KEY: &str = "runtime_prompt_component_flags";
const RUNTIME_PROMPT_LENGTHS_KEY: &str = "runtime_prompt_component_lengths";
const RUNTIME_PROMPT_SECTION_LAYOUT_KEY: &str = "runtime_prompt_section_layout";

pub(crate) async fn refresh_round_prompt_context(
    session: &mut Session,
    prompt_memory_flags: crate::runtime::config::PromptMemoryFlags,
    runtime_context: Option<&PromptMemoryRuntimeContext>,
    project_context_resolver: Option<&crate::project_context::ProjectContextResolver>,
) -> Result<(), AgentError> {
    refresh_project_context(session, project_context_resolver).await?;
    refresh_external_memory_context(
        session,
        prompt_memory_flags,
        runtime_context,
        project_context_resolver,
    )
    .await;
    // Task list, goal, plan-mode, and plan-runtime context are NOT injected into
    // the system message — they are built as dedicated volatile blocks directly
    // from session state during request assembly (cache-stable system prefix).

    let session_id = session.id.clone();
    let prompt_for_metadata = session
        .messages
        .iter_mut()
        .find(|message| matches!(message.role, Role::System))
        .map(|system_message| system_message.content.clone());

    if let Some(prompt) = prompt_for_metadata {
        persist_round_prompt_metadata(session, &prompt);
        log_round_prompt_refresh_summary(session_id.as_str(), &prompt);
    }
    Ok(())
}

async fn refresh_project_context(
    session: &mut Session,
    resolver: Option<&crate::project_context::ProjectContextResolver>,
) -> Result<(), AgentError> {
    let Some(resolver) = resolver else {
        return Ok(());
    };
    resolver
        .refresh_session_prompt(session)
        .await
        .map(|_| ())
        .map_err(|error| AgentError::ProjectContext(error.to_string()))
}

// ---- round_state functions ----

pub(super) fn update_task_round_state(
    task_context: &mut Option<TaskLoopContext>,
    round: usize,
    max_rounds: usize,
) {
    if let Some(ctx) = task_context.as_mut() {
        ctx.current_round = round as u32;
        ctx.max_rounds = max_rounds as u32;
    }
}

pub(super) fn build_round_id(session_id: &str, round: usize) -> String {
    format!("{}-round-{}", session_id, round + 1)
}

pub(super) fn log_round_start(
    debug_enabled: bool,
    session_id: &str,
    round: usize,
    max_rounds: usize,
    message_count: usize,
) {
    if debug_enabled {
        tracing::debug!(
            "[{}] round_start: {}",
            session_id,
            serde_json::json!({
                "round": round + 1,
                "total_rounds": max_rounds,
                "message_count": message_count,
            })
        );
    }
}

// ---- cancellation ----

fn ensure_not_cancelled(
    cancel_token: &CancellationToken,
    metrics_collector: Option<&MetricsCollector>,
    session_id: &str,
    message_count: usize,
) -> Result<(), AgentError> {
    if cancel_token.is_cancelled() {
        super::metrics_lifecycle::record_session_cancelled(
            metrics_collector,
            session_id,
            message_count as u32,
        );
        return Err(AgentError::Cancelled);
    }
    Ok(())
}

// ---- prompt metadata ----

fn persist_round_prompt_metadata(session: &mut Session, prompt: &str) {
    // Task list and external memory are sourced from session state/field (not
    // reparsed from system-message markers), since they ride volatile blocks now.
    let task_list_text = session.format_task_list_for_prompt();
    let external_memory = super::prompt_context::render_external_memory_section(session);
    let sections = build_round_prompt_sections(
        prompt,
        &task_list_text,
        external_memory.as_deref().unwrap_or_default(),
    );
    let report = PromptAssemblyReport::from_sections(sections, prompt);
    session.metadata.insert(
        RUNTIME_PROMPT_FLAGS_KEY.to_string(),
        report.component_flags_value(),
    );
    session.metadata.insert(
        RUNTIME_PROMPT_LENGTHS_KEY.to_string(),
        report.component_lengths_value(),
    );
    session.metadata.insert(
        RUNTIME_PROMPT_SECTION_LAYOUT_KEY.to_string(),
        report.section_layout_value(),
    );

    let task_list = (!task_list_text.trim().is_empty()).then(|| task_list_text.clone());

    let mut snapshot = super::session_setup::prompt_setup::read_prompt_snapshot_metadata(session)
        .unwrap_or_else(|| PromptSnapshot {
            base_system_prompt: session
                .metadata
                .get("base_system_prompt")
                .cloned()
                .unwrap_or_default(),
            enhancement_prompt: session.enhance_prompt(),
            project_context: super::session_setup::prompt_setup::extract_project_context(prompt),
            workspace_context: session.workspace_path_meta().and_then(|workspace_path| {
                crate::runtime::context::build_workspace_prompt_context(&workspace_path)
            }),
            instruction_context: session.workspace_path_meta().and_then(|workspace_path| {
                crate::runtime::context::instruction::build_instruction_prompt_context(
                    &workspace_path,
                )
            }),
            env_context: None,
            skill_context: None,
            tool_guide_context: None,
            dream_notebook: None,
            session_memory_note: None,
            project_memory_index: None,
            relevant_durable_memories: None,
            project_dream: None,
            global_dream_fallback: None,
            prompt_memory_observability: None,
            external_memory: None,
            task_list: None,
            effective_system_prompt: prompt.trim().to_string(),
        });
    let external_memory_parts =
        bamboo_agent_core::parse_prompt_external_memory_sections(external_memory.as_deref());
    snapshot.dream_notebook = external_memory_parts.dream_notebook;
    snapshot.session_memory_note = external_memory_parts.session_memory_note;
    snapshot.project_memory_index = external_memory_parts.project_memory_index;
    snapshot.relevant_durable_memories = external_memory_parts.relevant_durable_memories;
    snapshot.project_dream = external_memory_parts.project_dream;
    snapshot.global_dream_fallback = external_memory_parts.global_dream_fallback;
    snapshot.prompt_memory_observability = session
        .metadata
        .get(PROMPT_MEMORY_OBSERVABILITY_KEY)
        .and_then(|raw| {
            serde_json::from_str::<bamboo_agent_core::PromptMemoryObservability>(raw).ok()
        });
    snapshot.external_memory = external_memory;
    snapshot.task_list = task_list;
    snapshot.effective_system_prompt = prompt.trim().to_string();
    persist_prompt_snapshot_metadata(session, snapshot);
}

fn build_round_prompt_sections(
    prompt: &str,
    task_list: &str,
    external_memory: &str,
) -> Vec<super::session_setup::prompt_setup::PromptSection> {
    use super::session_setup::prompt_setup::{PromptLayer, PromptSection};

    vec![
        PromptSection::new("round_base_prompt", PromptLayer::CoreStatic, false, prompt),
        PromptSection::new(
            "external_memory",
            PromptLayer::EnvironmentWorkspace,
            true,
            external_memory,
        ),
        PromptSection::new(
            "task_list",
            PromptLayer::EnvironmentWorkspace,
            true,
            task_list,
        ),
    ]
}

fn log_round_prompt_refresh_summary(session_id: &str, prompt: &str) {
    tracing::info!(
        "[{}] Round prompt refresh summary: effective_len={} chars",
        session_id,
        prompt.len(),
    );
}

// ---- Main prepare_round function (for lifecycle adapter) ----

pub(crate) async fn prepare_round(
    session: &mut Session,
    task_context: &mut Option<TaskLoopContext>,
    config: &AgentLoopConfig,
    llm: Arc<dyn LLMProvider>,
    _tools: &dyn ToolExecutor,
    frame: &RoundPreludeFrame<'_>,
) -> Result<String, AgentError> {
    // Bind frame fields as locals so the rest of the function body stays unchanged.
    let round = frame.round;
    let max_rounds = frame.max_rounds;
    let cancel_token = frame.cancel_token;
    let metrics_collector = frame.metrics_collector;
    let session_id = frame.session_id;
    let model_name = frame.model_name;
    let debug_enabled = frame.debug_enabled;

    let runtime_context = PromptMemoryRuntimeContext {
        llm: config.background_model_provider.clone().unwrap_or(llm),
        background_model_name: config.background_model_name.clone(),
    };
    refresh_round_prompt_context(
        session,
        config.prompt_memory_flags,
        Some(&runtime_context),
        config.project_context_resolver.as_deref(),
    )
    .await?;
    update_task_round_state(task_context, round, max_rounds);

    let round_id = build_round_id(session_id, round);
    log_round_start(
        debug_enabled,
        session_id,
        round,
        max_rounds,
        session.messages.len(),
    );
    ensure_not_cancelled(
        cancel_token,
        metrics_collector,
        session_id,
        session.messages.len(),
    )?;

    super::metrics_lifecycle::record_round_started(
        metrics_collector,
        &round_id,
        session_id,
        model_name,
    );

    Ok(round_id)
}

#[cfg(test)]
mod project_prompt_tests {
    use async_trait::async_trait;
    use bamboo_agent_core::{Message, Session};
    use bamboo_domain::{ProjectId, ProjectResourceSummary, WorkspaceBinding};

    use crate::project_context::{
        ProjectContextError, ProjectContextResolver, ProjectContextSource, ProjectDescriptor,
    };

    struct StaticSource(ProjectDescriptor);

    #[async_trait]
    impl ProjectContextSource for StaticSource {
        async fn find_project(
            &self,
            project_id: &ProjectId,
        ) -> Result<Option<ProjectDescriptor>, ProjectContextError> {
            Ok((&self.0.id == project_id).then(|| self.0.clone()))
        }
    }

    struct OwnedWorkspaceSource {
        descriptor: ProjectDescriptor,
        owner: ProjectId,
    }

    #[async_trait]
    impl ProjectContextSource for OwnedWorkspaceSource {
        async fn find_project(
            &self,
            project_id: &ProjectId,
        ) -> Result<Option<ProjectDescriptor>, ProjectContextError> {
            Ok((&self.descriptor.id == project_id).then(|| self.descriptor.clone()))
        }

        async fn find_workspace_owner(
            &self,
            _workspace: &std::path::Path,
        ) -> Result<Option<ProjectId>, ProjectContextError> {
            Ok(Some(self.owner.clone()))
        }
    }

    #[tokio::test]
    async fn per_round_resolution_injects_project_once_and_refreshes_only_workspace() {
        let directory = tempfile::tempdir().expect("tempdir");
        let first = directory.path().join("main");
        let second = directory.path().join("worktree");
        std::fs::create_dir_all(&first).expect("first");
        std::fs::create_dir_all(&second).expect("second");
        let project_id = ProjectId::parse("project-1").expect("project id");
        let descriptor = ProjectDescriptor {
            id: project_id.clone(),
            name: "Zenith".to_string(),
            home: directory.path().join("projects/project-1"),
            workspace_bindings: vec![
                WorkspaceBinding {
                    path: first.to_string_lossy().to_string(),
                    label: None,
                    git_common_dir: None,
                },
                WorkspaceBinding {
                    path: second.to_string_lossy().to_string(),
                    label: None,
                    git_common_dir: None,
                },
            ],
            resources: ProjectResourceSummary {
                project_id: project_id.clone(),
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: crate::project_context::ProjectMemoryReadRoots {
                primary: directory.path().join("projects/project-1/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver = ProjectContextResolver::new(std::sync::Arc::new(StaticSource(descriptor)));
        let mut session = Session::new("session-1", "model");
        session.set_project_id_meta(project_id.to_string());
        session.set_workspace_path_meta(first.to_string_lossy().to_string());
        session.add_message(Message::system("Base"));

        super::refresh_project_context(&mut session, Some(&resolver))
            .await
            .expect("first Project refresh");
        let first_prompt = session.messages[0].content.clone();
        let project_block = first_prompt
            .split(crate::runtime::context::PROJECT_CONTEXT_START_MARKER)
            .nth(1)
            .and_then(|tail| {
                tail.split(crate::runtime::context::PROJECT_CONTEXT_END_MARKER)
                    .next()
            })
            .expect("project body")
            .to_string();

        session.set_workspace_path_meta(second.to_string_lossy().to_string());
        super::refresh_project_context(&mut session, Some(&resolver))
            .await
            .expect("second Project refresh");
        let second_prompt = &session.messages[0].content;
        assert_eq!(
            second_prompt
                .matches(crate::runtime::context::PROJECT_CONTEXT_START_MARKER)
                .count(),
            1
        );
        assert_eq!(
            second_prompt
                .matches(crate::runtime::context::WORKSPACE_CONTEXT_START_MARKER)
                .count(),
            1
        );
        assert!(second_prompt.contains(&project_block));
        let second = bamboo_config::paths::path_to_display_string(
            &second.canonicalize().expect("canonical second workspace"),
        );
        assert!(
            second_prompt.contains(&format!("Workspace path: {second}")),
            "second workspace was not refreshed in prompt: {second_prompt}"
        );
    }

    #[tokio::test]
    async fn round_project_refresh_fails_closed_for_invalid_missing_and_cross_project_context() {
        let directory = tempfile::tempdir().expect("tempdir");
        let workspace = directory.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace");
        let project_id = ProjectId::parse("round-project").expect("project id");
        let descriptor = ProjectDescriptor {
            id: project_id.clone(),
            name: "Round Project".to_string(),
            home: directory.path().join("projects/round-project"),
            workspace_bindings: Vec::new(),
            resources: ProjectResourceSummary {
                project_id: project_id.clone(),
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: crate::project_context::ProjectMemoryReadRoots {
                primary: directory.path().join("projects/round-project/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver =
            ProjectContextResolver::new(std::sync::Arc::new(StaticSource(descriptor.clone())));

        let mut invalid = Session::new("round-invalid-project", "model");
        invalid
            .metadata
            .insert("project_id".to_string(), "../invalid".to_string());
        let error = super::refresh_project_context(&mut invalid, Some(&resolver))
            .await
            .expect_err("invalid identity must stop the round");
        assert!(matches!(
            error,
            bamboo_agent_core::AgentError::ProjectContext(ref message)
                if message.contains("invalid Project identity")
        ));

        let mut missing = Session::new("round-missing-project", "model");
        missing.set_project_id_meta("missing-project");
        let error = super::refresh_project_context(&mut missing, Some(&resolver))
            .await
            .expect_err("missing assigned Project must stop the round");
        assert!(matches!(
            error,
            bamboo_agent_core::AgentError::ProjectContext(ref message)
                if message.contains("unavailable")
        ));

        let foreign_owner = ProjectId::parse("foreign-owner").expect("foreign Project id");
        let owned_resolver =
            ProjectContextResolver::new(std::sync::Arc::new(OwnedWorkspaceSource {
                descriptor,
                owner: foreign_owner,
            }));
        let mut cross_project = Session::new("round-cross-project", "model");
        cross_project.set_project_id_meta(project_id);
        cross_project.set_workspace_path_meta(workspace.to_string_lossy().into_owned());
        let error = super::refresh_project_context(&mut cross_project, Some(&owned_resolver))
            .await
            .expect_err("cross-Project workspace must stop the round");
        assert!(matches!(
            error,
            bamboo_agent_core::AgentError::ProjectContext(ref message)
                if message.contains("belongs to Project")
        ));
    }

    #[tokio::test]
    async fn round_project_refresh_keeps_unassigned_unbound_legacy_session_executable() {
        let directory = tempfile::tempdir().expect("tempdir");
        let project_id = ProjectId::parse("unrelated-project").expect("project id");
        let descriptor = ProjectDescriptor {
            id: project_id.clone(),
            name: "Unrelated".to_string(),
            home: directory.path().join("projects/unrelated-project"),
            workspace_bindings: Vec::new(),
            resources: ProjectResourceSummary {
                project_id,
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: crate::project_context::ProjectMemoryReadRoots {
                primary: directory
                    .path()
                    .join("projects/unrelated-project/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver = ProjectContextResolver::new(std::sync::Arc::new(StaticSource(descriptor)));
        let mut session = Session::new("round-unassigned-legacy", "model");
        session.add_message(Message::system("legacy base prompt"));

        super::refresh_project_context(&mut session, Some(&resolver))
            .await
            .expect("unassigned unbound legacy session remains executable");
        assert_eq!(session.messages[0].content, "legacy base prompt");
    }
}