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
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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
//! Stable Project identity and shared-resource resolution.
//!
//! A Project is not a workspace.  The Project id carried by a session is the
//! authority for memory and shared resources; the workspace is only the
//! mutable filesystem execution context.  This module is the single engine
//! seam for resolving those two identities together.

use std::path::{Path, PathBuf};
use std::sync::Arc;

use async_trait::async_trait;
use bamboo_agent_core::Session;
use bamboo_domain::{ProjectId, ProjectResourceKind, ProjectResourceSummary, WorkspaceBinding};
use serde::{Deserialize, Serialize};

pub const PROJECT_ID_METADATA_KEY: &str = "project_id";
pub const PROJECT_RESOURCES_RENDERED_KEY: &str = "project_resources_rendered";

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceBindingStatus {
    Registered,
    Unregistered,
}

impl WorkspaceBindingStatus {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Registered => "registered",
            Self::Unregistered => "unregistered",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectDescriptor {
    pub id: ProjectId,
    pub name: String,
    pub home: PathBuf,
    pub workspace_bindings: Vec<WorkspaceBinding>,
    pub resources: ProjectResourceSummary,
    pub memory_read_roots: ProjectMemoryReadRoots,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectMemoryReadRoots {
    pub primary: PathBuf,
    pub legacy_aliases: Vec<bamboo_memory::memory_store::LegacyProjectMemoryReadRoot>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedProjectContext {
    pub project: ProjectDescriptor,
    pub workspace: Option<PathBuf>,
    pub binding_status: WorkspaceBindingStatus,
}

impl ResolvedProjectContext {
    pub fn resource_scope(&self) -> ProjectResourceScope {
        ProjectResourceScope {
            project_id: self.project.id.clone(),
            project_home: self.project.home.clone(),
            workspace: self.workspace.clone(),
            binding_status: self.binding_status,
            resource_revision: self.project.resources.resource_revision,
        }
    }

    pub fn render_resource_inventory(&self) -> String {
        let mut entries = self.project.resources.resources.clone();
        entries.sort_by_key(|entry| entry.kind);
        let rendered = entries
            .into_iter()
            .map(|entry| {
                format!(
                    "- {:?}: status={}, items={}",
                    entry.kind,
                    if entry.present { "available" } else { "empty" },
                    entry.item_count
                )
            })
            .collect::<Vec<_>>()
            .join("\n");
        format!(
            "Project ID: {}\nResource revision: {}\n{}",
            self.project.id,
            self.project.resources.resource_revision,
            if rendered.is_empty() {
                "No Project-shared resources are currently advertised.".to_string()
            } else {
                rendered
            }
        )
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ProjectContextError {
    #[error("project context source failed: {0}")]
    Source(String),
    #[error("project context source returned '{actual}' for requested project '{requested}'")]
    IdentityMismatch { requested: String, actual: String },
    #[error(
        "workspace '{workspace}' belongs to Project '{owner_project_id}', not session Project '{session_project_id}'"
    )]
    WorkspaceConflict {
        workspace: String,
        owner_project_id: ProjectId,
        session_project_id: ProjectId,
    },
    #[error("workspace '{workspace}' belongs to Project '{owner_project_id}', but the session is Unassigned")]
    UnassignedWorkspaceConflict {
        workspace: String,
        owner_project_id: ProjectId,
    },
    #[error("session carries an invalid Project identity '{raw}': {message}")]
    InvalidProjectIdentity { raw: String, message: String },
    #[error("assigned Project '{project_id}' is unavailable")]
    ProjectUnavailable { project_id: ProjectId },
    #[error("workspace '{workspace}' is invalid: {message}")]
    WorkspaceInvalid { workspace: String, message: String },
}

/// Adapter implemented by the authoritative Project registry.
///
/// The engine deliberately depends on this redacted descriptor rather than on
/// registry persistence details. Secret settings and credential values must
/// never be added to this interface.
#[async_trait]
pub trait ProjectContextSource: Send + Sync {
    async fn find_project(
        &self,
        project_id: &ProjectId,
    ) -> Result<Option<ProjectDescriptor>, ProjectContextError>;

    async fn list_projects(&self) -> Result<Vec<ProjectDescriptor>, ProjectContextError> {
        Ok(Vec::new())
    }

    /// Resolve the global Project owner for an exact workspace. Sources that
    /// cannot provide a registry-wide answer remain backward compatible.
    async fn find_workspace_owner(
        &self,
        _workspace: &Path,
    ) -> Result<Option<ProjectId>, ProjectContextError> {
        Ok(None)
    }
}

#[derive(Clone)]
pub struct ProjectContextResolver {
    source: Arc<dyn ProjectContextSource>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionProjectIdentity {
    Unassigned,
    Assigned(ProjectId),
    Invalid { raw: String, message: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ProjectMemoryScope {
    Assigned {
        project_id: ProjectId,
        legacy_aliases: Vec<bamboo_memory::memory_store::LegacyProjectMemoryReadRoot>,
    },
    LegacyReadOnly(String),
}

impl ProjectMemoryScope {
    pub fn key(&self) -> &str {
        match self {
            Self::Assigned { project_id, .. } => project_id.as_str(),
            Self::LegacyReadOnly(project_key) => project_key,
        }
    }

    pub fn scoped_store(
        &self,
        store: &bamboo_memory::memory_store::MemoryStore,
    ) -> bamboo_memory::memory_store::MemoryStore {
        match self {
            Self::Assigned {
                project_id,
                legacy_aliases,
            } => store.for_project_with_legacy_read_roots(project_id, legacy_aliases.clone()),
            Self::LegacyReadOnly(_) => store.clone(),
        }
    }
}

impl ProjectContextResolver {
    pub fn new(source: Arc<dyn ProjectContextSource>) -> Self {
        Self { source }
    }

    /// Return the stable, opaque Project id persisted on the session.
    ///
    /// The domain accessor dual-writes this compatibility key. Keeping the
    /// read centralized here prevents memory, Dream, prompt, and resource
    /// callers from independently falling back to mutable workspace identity.
    pub fn project_id_from_session(session: &Session) -> Option<ProjectId> {
        match Self::session_project_identity(session) {
            SessionProjectIdentity::Assigned(project_id) => Some(project_id),
            SessionProjectIdentity::Invalid { raw, message } => {
                tracing::warn!(
                    session_id = %session.id,
                    "ignoring invalid persisted Project id '{raw}': {message}"
                );
                None
            }
            SessionProjectIdentity::Unassigned => None,
        }
    }

    /// Parse persisted Project membership into an authoritative three-state
    /// value. Whitespace is normalized exactly like the rebuildable storage
    /// index. Callers with security/resource consequences must distinguish
    /// `Invalid` from truly `Unassigned`.
    pub fn session_project_identity(session: &Session) -> SessionProjectIdentity {
        let Some(raw) = session.project_id_meta() else {
            return SessionProjectIdentity::Unassigned;
        };
        let normalized = raw.trim();
        match ProjectId::parse(normalized) {
            Ok(project_id) => SessionProjectIdentity::Assigned(project_id),
            Err(error) => SessionProjectIdentity::Invalid {
                raw,
                message: error.to_string(),
            },
        }
    }

    /// Resolve the Project id used for memory reads.
    ///
    /// Assigned sessions always use their stable Project id. The path-derived
    /// fallback is read-compatibility for unassigned legacy sessions only; new
    /// sessions and writes must use [`Self::project_id_from_session`].
    pub fn memory_read_scope_for_session(session: &Session) -> Option<String> {
        Self::memory_read_identity_for_session(session).map(|scope| scope.key().to_string())
    }

    pub fn memory_read_identity_for_session(session: &Session) -> Option<ProjectMemoryScope> {
        match Self::session_project_identity(session) {
            SessionProjectIdentity::Assigned(project_id) => Some(ProjectMemoryScope::Assigned {
                project_id,
                legacy_aliases: Vec::new(),
            }),
            SessionProjectIdentity::Unassigned => session
                .workspace_path_meta()
                .map(PathBuf::from)
                .or_else(|| {
                    bamboo_tools::tools::workspace_state::get_workspace(session.id.as_str())
                })
                .map(|path| {
                    ProjectMemoryScope::LegacyReadOnly(
                        bamboo_memory::memory_store::project_key_from_path(&path),
                    )
                }),
            SessionProjectIdentity::Invalid { .. } => None,
        }
    }

    pub async fn resolve_memory_read_scope(
        &self,
        session: &Session,
        workspace: Option<&Path>,
    ) -> Result<Option<ProjectMemoryScope>, ProjectContextError> {
        match Self::session_project_identity(session) {
            SessionProjectIdentity::Unassigned => {
                return Ok(Self::memory_read_identity_for_session(session));
            }
            SessionProjectIdentity::Invalid { raw, message } => {
                return Err(ProjectContextError::InvalidProjectIdentity { raw, message });
            }
            SessionProjectIdentity::Assigned(_) => {}
        }
        Ok(self
            .resolve(session, workspace)
            .await?
            .map(|context| ProjectMemoryScope::Assigned {
                project_id: context.project.id,
                legacy_aliases: context.project.memory_read_roots.legacy_aliases,
            }))
    }

    pub async fn list_memory_read_scopes(
        &self,
    ) -> Result<Vec<ProjectMemoryScope>, ProjectContextError> {
        Ok(self
            .source
            .list_projects()
            .await?
            .into_iter()
            .map(|project| ProjectMemoryScope::Assigned {
                project_id: project.id,
                legacy_aliases: project.memory_read_roots.legacy_aliases,
            })
            .collect())
    }

    /// Resolve the only valid Project write scope.
    ///
    /// Unassigned legacy sessions intentionally return `None`: their
    /// path-derived scopes are read/migration aliases and must never receive
    /// new Project memory or Dream writes.
    pub fn memory_write_scope_for_session(session: &Session) -> Option<String> {
        match Self::session_project_identity(session) {
            SessionProjectIdentity::Assigned(project_id) => Some(project_id.into_string()),
            SessionProjectIdentity::Unassigned | SessionProjectIdentity::Invalid { .. } => None,
        }
    }

    pub async fn resolve(
        &self,
        session: &Session,
        workspace: Option<&Path>,
    ) -> Result<Option<ResolvedProjectContext>, ProjectContextError> {
        let workspace = Self::resolve_workspace_candidate(session, workspace)?;
        self.resolve_with_final_workspace(session, workspace).await
    }

    /// Resolve the exact workspace the runtime will use without publishing it.
    ///
    /// This is shared by HTTP preflight, SDK/execute prompt refresh, and the
    /// Workspace tool so configured/session-default fallbacks cannot bypass
    /// Project ownership checks.
    pub fn resolve_workspace_candidate(
        session: &Session,
        workspace: Option<&Path>,
    ) -> Result<Option<PathBuf>, ProjectContextError> {
        let preferred = workspace
            .map(Path::to_path_buf)
            .or_else(|| session.workspace_path_meta().map(PathBuf::from));
        bamboo_agent_core::workspace_state::resolve_session_workspace_candidate(
            &session.id,
            preferred,
        )
        .map(|candidate| resolve_final_workspace(&candidate))
        .transpose()
    }

    async fn resolve_with_final_workspace(
        &self,
        session: &Session,
        workspace: Option<PathBuf>,
    ) -> Result<Option<ResolvedProjectContext>, ProjectContextError> {
        let project_id = match Self::session_project_identity(session) {
            SessionProjectIdentity::Assigned(project_id) => project_id,
            SessionProjectIdentity::Invalid { raw, message } => {
                return Err(ProjectContextError::InvalidProjectIdentity { raw, message });
            }
            SessionProjectIdentity::Unassigned => {
                if let Some(candidate) = workspace.as_deref() {
                    if let Some(owner_project_id) =
                        self.source.find_workspace_owner(candidate).await?
                    {
                        return Err(ProjectContextError::UnassignedWorkspaceConflict {
                            workspace: candidate.to_string_lossy().into_owned(),
                            owner_project_id,
                        });
                    }
                }
                return Ok(None);
            }
        };
        let project = self
            .source
            .find_project(&project_id)
            .await?
            .ok_or_else(|| ProjectContextError::ProjectUnavailable {
                project_id: project_id.clone(),
            })?;
        if project.id != project_id {
            return Err(ProjectContextError::IdentityMismatch {
                requested: project_id.to_string(),
                actual: project.id.to_string(),
            });
        }

        let binding_status = match workspace.as_deref() {
            Some(candidate) => match self.source.find_workspace_owner(candidate).await? {
                Some(owner) if owner == project.id => WorkspaceBindingStatus::Registered,
                Some(owner) => {
                    return Err(ProjectContextError::WorkspaceConflict {
                        workspace: candidate.to_string_lossy().into_owned(),
                        owner_project_id: owner,
                        session_project_id: project.id.clone(),
                    });
                }
                None if project
                    .workspace_bindings
                    .iter()
                    .any(|binding| path_is_within_binding(Path::new(&binding.path), candidate)) =>
                {
                    WorkspaceBindingStatus::Registered
                }
                None => WorkspaceBindingStatus::Unregistered,
            },
            None => WorkspaceBindingStatus::Unregistered,
        };

        Ok(Some(ResolvedProjectContext {
            project,
            workspace,
            binding_status,
        }))
    }

    pub async fn workspace_owner(
        &self,
        workspace: &Path,
    ) -> Result<Option<ProjectId>, ProjectContextError> {
        self.source.find_workspace_owner(workspace).await
    }

    /// Resolve and persist the stable Project and mutable Workspace prompt
    /// markers immediately.
    ///
    /// Session-create and chat APIs call this before their first response so a
    /// freshly-created assigned session is already self-describing when read
    /// back, rather than waiting for the first execution round. The round
    /// prelude calls the same helper to keep the markers current.
    pub async fn refresh_session_prompt(
        &self,
        session: &mut Session,
    ) -> Result<Option<ResolvedProjectContext>, ProjectContextError> {
        self.refresh_session_prompt_inner(session, true).await
    }

    /// Resolve Project/Workspace prompt markers on an in-memory snapshot
    /// without changing runtime workspace state.
    ///
    /// Read APIs use this for sessions that have never entered the runner
    /// (for example a disabled schedule or a child created with
    /// `auto_run=false`). The caller is expected to discard the temporary
    /// session after building the response.
    pub async fn refresh_session_prompt_read_only(
        &self,
        session: &mut Session,
    ) -> Result<Option<ResolvedProjectContext>, ProjectContextError> {
        self.refresh_session_prompt_inner(session, false).await
    }

    async fn refresh_session_prompt_inner(
        &self,
        session: &mut Session,
        sync_runtime_workspace: bool,
    ) -> Result<Option<ResolvedProjectContext>, ProjectContextError> {
        let workspace = Self::resolve_workspace_candidate(session, None)?;
        let resolved = self
            .resolve_with_final_workspace(session, workspace.clone())
            .await?;
        if let Some(workspace) = workspace.as_deref() {
            let final_workspace = if sync_runtime_workspace {
                bamboo_tools::tools::workspace_state::publish_resolved_workspace(
                    &session.id,
                    workspace.into(),
                )
            } else {
                workspace.to_path_buf()
            };
            session.set_workspace_path_meta(bamboo_config::paths::path_to_display_string(
                &final_workspace,
            ));
        }
        let current = session
            .messages
            .iter()
            .find(|message| matches!(message.role, bamboo_agent_core::Role::System))
            .map(|message| message.content.clone())
            .or_else(|| session.metadata.get("base_system_prompt").cloned())
            .unwrap_or_default();
        let mut updated =
            crate::runtime::context::upsert_project_prompt_context(&current, resolved.as_ref());

        if let Some(context) = resolved.as_ref() {
            session.metadata.insert(
                PROJECT_RESOURCES_RENDERED_KEY.to_string(),
                context.render_resource_inventory(),
            );
        } else {
            session.metadata.remove(PROJECT_RESOURCES_RENDERED_KEY);
        }
        let workspace_display = workspace
            .as_deref()
            .map(bamboo_config::paths::path_to_display_string);
        updated = crate::runtime::context::upsert_workspace_prompt_context(
            &updated,
            workspace_display.as_deref(),
            resolved
                .as_ref()
                .map(|context| context.binding_status)
                .unwrap_or(WorkspaceBindingStatus::Unregistered),
        );

        if let Some(system_message) = session
            .messages
            .iter_mut()
            .find(|message| matches!(message.role, bamboo_agent_core::Role::System))
        {
            system_message.content = updated;
        } else if !updated.trim().is_empty() {
            session
                .messages
                .insert(0, bamboo_agent_core::Message::system(updated));
        }
        crate::runner::refresh_prompt_snapshot(session);

        Ok(resolved)
    }
}

fn resolve_final_workspace(workspace: &Path) -> Result<PathBuf, ProjectContextError> {
    if workspace.exists() && !workspace.is_dir() {
        return Err(ProjectContextError::WorkspaceInvalid {
            workspace: workspace.to_string_lossy().into_owned(),
            message: "path is not a directory".to_string(),
        });
    }
    let canonical = std::fs::canonicalize(workspace).unwrap_or_else(|_| workspace.to_path_buf());
    let final_workspace = bamboo_agent_core::workspace_state::preview_workspace_path(canonical);
    if final_workspace.exists() && !final_workspace.is_dir() {
        return Err(ProjectContextError::WorkspaceInvalid {
            workspace: final_workspace.to_string_lossy().into_owned(),
            message: "resolved path is not a directory".to_string(),
        });
    }
    Ok(std::fs::canonicalize(&final_workspace).unwrap_or(final_workspace))
}

fn path_is_within_binding(binding: &Path, candidate: &Path) -> bool {
    match (
        std::fs::canonicalize(binding),
        std::fs::canonicalize(candidate),
    ) {
        (Ok(binding), Ok(candidate)) => candidate == binding || candidate.starts_with(binding),
        _ => candidate == binding || candidate.starts_with(binding),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectResourceLayer {
    Project,
    Workspace,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectResourceCandidate {
    pub kind: ProjectResourceKind,
    pub layer: ProjectResourceLayer,
    pub path: PathBuf,
    pub exists: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectResourceDiagnostic {
    pub project_id: ProjectId,
    pub resource_revision: u64,
    pub workspace_binding_status: WorkspaceBindingStatus,
    pub candidates: Vec<ProjectResourceCandidate>,
}

/// Stable Project-home resources plus the current workspace overlay.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProjectResourceScope {
    pub project_id: ProjectId,
    pub project_home: PathBuf,
    pub workspace: Option<PathBuf>,
    pub binding_status: WorkspaceBindingStatus,
    pub resource_revision: u64,
}

impl ProjectResourceScope {
    pub fn project_memory_root(&self) -> PathBuf {
        self.project_home.join("memory").join("v1")
    }

    pub fn project_skills_dir(&self) -> PathBuf {
        self.project_home.join("skills")
    }

    pub fn project_mode_skills_dir(&self, mode: &str) -> PathBuf {
        self.project_home.join(format!("skills-{mode}"))
    }

    pub fn workspace_skills_dir(&self) -> Option<PathBuf> {
        self.workspace
            .as_ref()
            .map(|workspace| workspace.join(".bamboo").join("skills"))
    }

    pub fn workspace_mode_skills_dir(&self, mode: &str) -> Option<PathBuf> {
        self.workspace
            .as_ref()
            .map(|workspace| workspace.join(".bamboo").join(format!("skills-{mode}")))
    }

    pub fn project_commands_dir(&self) -> PathBuf {
        self.project_home.join("commands")
    }

    pub fn workspace_commands_dir(&self) -> Option<PathBuf> {
        let workspace = self.workspace.as_deref()?;
        let boundary = nearest_git_boundary(workspace).unwrap_or_else(|| workspace.to_path_buf());
        Some(boundary.join(".bamboo").join("commands"))
    }

    /// Ordinary resource precedence is Project first, then the more-specific
    /// workspace overlay. Security policies must use their dedicated managed /
    /// deny / trust merge logic instead of this shadowing order.
    pub fn candidates(&self, kind: ProjectResourceKind) -> Vec<ProjectResourceCandidate> {
        let mut paths = match kind {
            ProjectResourceKind::Settings => vec![(
                ProjectResourceLayer::Project,
                self.project_home.join("settings.json"),
            )],
            ProjectResourceKind::Memory => {
                vec![(ProjectResourceLayer::Project, self.project_memory_root())]
            }
            ProjectResourceKind::Skills => {
                let mut values = vec![(ProjectResourceLayer::Project, self.project_skills_dir())];
                if let Some(path) = self.workspace_skills_dir() {
                    values.push((ProjectResourceLayer::Workspace, path));
                }
                values
            }
            ProjectResourceKind::Commands => {
                let mut values = vec![(ProjectResourceLayer::Project, self.project_commands_dir())];
                if let Some(path) = self.workspace_commands_dir() {
                    values.push((ProjectResourceLayer::Workspace, path));
                }
                values
            }
            ProjectResourceKind::Artifacts => vec![(
                ProjectResourceLayer::Project,
                self.project_home.join("artifacts"),
            )],
            ProjectResourceKind::State => vec![(
                ProjectResourceLayer::Project,
                self.project_home.join("state"),
            )],
        };

        paths
            .drain(..)
            .map(|(layer, path)| ProjectResourceCandidate {
                kind,
                layer,
                exists: path.exists(),
                path,
            })
            .collect()
    }

    pub fn diagnostic(&self) -> ProjectResourceDiagnostic {
        let mut candidates = Vec::new();
        for kind in [
            ProjectResourceKind::Settings,
            ProjectResourceKind::Memory,
            ProjectResourceKind::Skills,
            ProjectResourceKind::Commands,
            ProjectResourceKind::Artifacts,
            ProjectResourceKind::State,
        ] {
            candidates.extend(self.candidates(kind));
        }
        ProjectResourceDiagnostic {
            project_id: self.project_id.clone(),
            resource_revision: self.resource_revision,
            workspace_binding_status: self.binding_status,
            candidates,
        }
    }
}

fn nearest_git_boundary(start: &Path) -> Option<PathBuf> {
    start
        .ancestors()
        .find(|candidate| {
            let git = candidate.join(".git");
            git.is_dir() || git.is_file()
        })
        .map(Path::to_path_buf)
}

#[cfg(test)]
mod tests {
    use super::*;

    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: &Path,
        ) -> Result<Option<ProjectId>, ProjectContextError> {
            Ok(Some(self.owner.clone()))
        }
    }

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

        let first = resolver
            .resolve(&session, Some(&main))
            .await
            .expect("resolve")
            .expect("assigned");
        let second = resolver
            .resolve(&session, Some(&worktree))
            .await
            .expect("resolve")
            .expect("assigned");
        assert_eq!(first.project.id, second.project.id);
        assert_eq!(first.project.home, second.project.home);
        assert_eq!(second.binding_status, WorkspaceBindingStatus::Registered);
    }

    #[tokio::test]
    async fn prompt_refresh_removes_stale_project_and_updates_unassigned_workspace() {
        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("project-prompt-refresh").expect("Project id");
        let descriptor = ProjectDescriptor {
            id: project_id.clone(),
            name: "Prompt Project".to_string(),
            home: directory.path().join("projects/project-prompt-refresh"),
            workspace_bindings: vec![WorkspaceBinding {
                path: workspace.to_string_lossy().into_owned(),
                label: None,
                git_common_dir: None,
            }],
            resources: bamboo_domain::ProjectResourceSummary {
                project_id: project_id.clone(),
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: ProjectMemoryReadRoots {
                primary: directory
                    .path()
                    .join("projects/project-prompt-refresh/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver = ProjectContextResolver::new(Arc::new(StaticSource(descriptor)));
        let mut session = Session::new("prompt-project-switch", "test");
        session
            .messages
            .insert(0, bamboo_agent_core::Message::system("base"));
        session.set_project_id_meta(project_id.to_string());
        session.set_workspace_path_meta(workspace.to_string_lossy().into_owned());

        resolver
            .refresh_session_prompt(&mut session)
            .await
            .expect("assigned refresh");
        let assigned = &session.messages[0].content;
        assert_eq!(assigned.matches("BAMBOO_PROJECT_CONTEXT_START").count(), 1);
        assert!(assigned.contains("Binding status: registered"));

        session.clear_project_id_meta();
        resolver
            .refresh_session_prompt(&mut session)
            .await
            .expect("unassigned refresh");
        let unassigned = &session.messages[0].content;
        assert_eq!(
            unassigned.matches("BAMBOO_PROJECT_CONTEXT_START").count(),
            0
        );
        assert_eq!(
            unassigned.matches("BAMBOO_WORKSPACE_CONTEXT_START").count(),
            1
        );
        assert!(unassigned.contains("Binding status: unregistered"));
        assert!(!session
            .metadata
            .contains_key(PROJECT_RESOURCES_RENDERED_KEY));
    }

    #[tokio::test]
    async fn workspace_owned_by_another_project_fails_closed() {
        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("project-a").expect("project id");
        let owner = ProjectId::parse("project-b").expect("owner id");
        let descriptor = ProjectDescriptor {
            id: project_id.clone(),
            name: "Project A".to_string(),
            home: directory.path().join("projects/project-a"),
            workspace_bindings: vec![WorkspaceBinding {
                path: workspace.to_string_lossy().into_owned(),
                label: None,
                git_common_dir: None,
            }],
            resources: bamboo_domain::ProjectResourceSummary {
                project_id: project_id.clone(),
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: ProjectMemoryReadRoots {
                primary: directory.path().join("projects/project-a/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver = ProjectContextResolver::new(Arc::new(OwnedWorkspaceSource {
            descriptor,
            owner: owner.clone(),
        }));
        let mut session = Session::new("session-conflict", "test");
        session.set_project_id_meta(project_id.to_string());

        let error = resolver
            .resolve(&session, Some(&workspace))
            .await
            .expect_err("cross-Project workspace must fail closed");
        assert!(matches!(
            error,
            ProjectContextError::WorkspaceConflict {
                owner_project_id,
                session_project_id,
                ..
            } if owner_project_id == owner && session_project_id == project_id
        ));

        let safe_workspace = directory.path().join("safe");
        std::fs::create_dir_all(&safe_workspace).expect("safe workspace");
        let safe_canonical = safe_workspace.canonicalize().expect("canonical safe");
        bamboo_tools::tools::workspace_state::set_workspace(&session.id, safe_canonical.clone());
        session.set_workspace_path_meta(workspace.to_string_lossy().into_owned());
        let error = resolver
            .refresh_session_prompt(&mut session)
            .await
            .expect_err("refresh must validate before publishing workspace");
        assert!(matches!(
            error,
            ProjectContextError::WorkspaceConflict { .. }
        ));
        assert_eq!(
            bamboo_tools::tools::workspace_state::get_workspace(&session.id).as_deref(),
            Some(safe_canonical.as_path()),
            "a post-preflight ownership change must not publish the rejected workspace"
        );
    }

    #[tokio::test]
    async fn malformed_project_identity_never_falls_back_to_legacy_workspace_scope() {
        let directory = tempfile::tempdir().expect("tempdir");
        let workspace = directory.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace");
        let descriptor_id = ProjectId::parse("descriptor").expect("Project id");
        let descriptor = ProjectDescriptor {
            id: descriptor_id.clone(),
            name: "Descriptor".to_string(),
            home: directory.path().join("projects/descriptor"),
            workspace_bindings: Vec::new(),
            resources: bamboo_domain::ProjectResourceSummary {
                project_id: descriptor_id.clone(),
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: ProjectMemoryReadRoots {
                primary: directory.path().join("projects/descriptor/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver = ProjectContextResolver::new(Arc::new(StaticSource(descriptor)));
        let mut session = Session::new("malformed", "test");
        session.set_project_id_meta("../malformed");
        session.set_workspace_path_meta(workspace.to_string_lossy().into_owned());

        assert!(ProjectContextResolver::memory_read_identity_for_session(&session).is_none());
        assert!(matches!(
            resolver.resolve(&session, Some(&workspace)).await,
            Err(ProjectContextError::InvalidProjectIdentity { .. })
        ));
        assert!(matches!(
            resolver
                .resolve_memory_read_scope(&session, Some(&workspace))
                .await,
            Err(ProjectContextError::InvalidProjectIdentity { .. })
        ));
    }

    #[tokio::test]
    async fn unassigned_session_cannot_resolve_a_project_owned_workspace() {
        let directory = tempfile::tempdir().expect("tempdir");
        let workspace = directory.path().join("workspace");
        std::fs::create_dir_all(&workspace).expect("workspace");
        let descriptor_id = ProjectId::parse("descriptor").expect("Project id");
        let owner = ProjectId::parse("owner").expect("owner Project id");
        let descriptor = ProjectDescriptor {
            id: descriptor_id.clone(),
            name: "Descriptor".to_string(),
            home: directory.path().join("projects/descriptor"),
            workspace_bindings: Vec::new(),
            resources: bamboo_domain::ProjectResourceSummary {
                project_id: descriptor_id,
                resource_revision: 1,
                resources: Vec::new(),
            },
            memory_read_roots: ProjectMemoryReadRoots {
                primary: directory.path().join("projects/descriptor/memory/v1"),
                legacy_aliases: Vec::new(),
            },
        };
        let resolver = ProjectContextResolver::new(Arc::new(OwnedWorkspaceSource {
            descriptor,
            owner: owner.clone(),
        }));
        let session = Session::new("unassigned", "test");

        assert!(matches!(
            resolver.resolve(&session, Some(&workspace)).await,
            Err(ProjectContextError::UnassignedWorkspaceConflict {
                owner_project_id,
                ..
            }) if owner_project_id == owner
        ));
    }

    #[test]
    fn project_identity_parser_trims_like_the_storage_index() {
        let mut session = Session::new("whitespace", "test");
        session.set_project_id_meta("  project-1  ");
        assert_eq!(
            ProjectContextResolver::session_project_identity(&session),
            SessionProjectIdentity::Assigned(ProjectId::parse("project-1").unwrap())
        );
    }

    #[test]
    fn resource_diagnostic_distinguishes_project_and_workspace_layers() {
        let directory = tempfile::tempdir().expect("tempdir");
        let project_home = directory.path().join("project-home");
        let workspace = directory.path().join("workspace");
        std::fs::create_dir_all(project_home.join("skills")).expect("project skills");
        std::fs::create_dir_all(workspace.join(".bamboo/skills")).expect("workspace skills");
        let scope = ProjectResourceScope {
            project_id: ProjectId::parse("project-1").expect("project id"),
            project_home,
            workspace: Some(workspace),
            binding_status: WorkspaceBindingStatus::Registered,
            resource_revision: 4,
        };

        let candidates = scope.candidates(ProjectResourceKind::Skills);
        assert_eq!(candidates.len(), 2);
        assert_eq!(candidates[0].layer, ProjectResourceLayer::Project);
        assert_eq!(candidates[1].layer, ProjectResourceLayer::Workspace);
        assert!(candidates.iter().all(|candidate| candidate.exists));
    }

    #[test]
    fn workspace_commands_resolve_from_nearest_git_boundary() {
        let directory = tempfile::tempdir().expect("tempdir");
        let repository = directory.path().join("repo");
        let nested = repository.join("nested/path");
        std::fs::create_dir_all(repository.join(".git")).expect("git");
        std::fs::create_dir_all(&nested).expect("nested");
        let scope = ProjectResourceScope {
            project_id: ProjectId::parse("project-1").expect("project id"),
            project_home: directory.path().join("project-home"),
            workspace: Some(nested),
            binding_status: WorkspaceBindingStatus::Registered,
            resource_revision: 1,
        };
        assert_eq!(
            scope.workspace_commands_dir(),
            Some(repository.join(".bamboo/commands"))
        );
    }

    #[test]
    fn unassigned_legacy_scope_is_read_only() {
        let mut session = Session::new("legacy-session", "legacy");
        session.set_workspace_path_meta("/tmp/legacy-workspace");
        assert!(ProjectContextResolver::memory_read_scope_for_session(&session).is_some());
        assert!(ProjectContextResolver::memory_write_scope_for_session(&session).is_none());
    }
}