bamboo-domain 2026.8.13

Domain models and shared types 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
//! Stable Project identity and persistence DTOs.
//!
//! A Project is deliberately not derived from a workspace path. Workspaces are
//! mutable execution contexts, while [`ProjectId`] is the opaque durable key
//! used by sessions and Project-shared resources.

use std::collections::BTreeMap;
use std::fmt;
use std::str::FromStr;

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;

pub const PROJECT_MANIFEST_SCHEMA_VERSION: u32 = 2;
pub const PROJECT_INDEX_SCHEMA_VERSION: u32 = 2;

fn initial_project_revision() -> u64 {
    1
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[error("invalid project id: {0}")]
pub struct InvalidProjectId(pub String);

/// Opaque, path-safe, stable Project identity.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ProjectId(String);

impl ProjectId {
    pub const MAX_LEN: usize = 64;

    pub fn new() -> Self {
        Self(Uuid::new_v4().to_string())
    }

    pub fn parse(value: impl Into<String>) -> Result<Self, InvalidProjectId> {
        let value = value.into();
        let valid = !value.is_empty()
            && value.len() <= Self::MAX_LEN
            && value
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-' || byte == b'_');
        if valid {
            Ok(Self(value))
        } else {
            Err(InvalidProjectId(value))
        }
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn into_string(self) -> String {
        self.0
    }
}

impl Default for ProjectId {
    fn default() -> Self {
        Self::new()
    }
}

impl fmt::Display for ProjectId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.0)
    }
}

impl AsRef<str> for ProjectId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl FromStr for ProjectId {
    type Err = InvalidProjectId;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Self::parse(value)
    }
}

impl TryFrom<String> for ProjectId {
    type Error = InvalidProjectId;

    fn try_from(value: String) -> Result<Self, Self::Error> {
        Self::parse(value)
    }
}

impl From<ProjectId> for String {
    fn from(value: ProjectId) -> Self {
        value.into_string()
    }
}

impl Serialize for ProjectId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.as_str())
    }
}

impl<'de> Deserialize<'de> for ProjectId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let value = String::deserialize(deserializer)?;
        Self::parse(value).map_err(serde::de::Error::custom)
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectStatus {
    #[default]
    Active,
    Archived,
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectPathStatus {
    Configured,
    NeedsSelection,
    #[default]
    NeedsConfiguration,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceBinding {
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_common_dir: Option<String>,
}

/// Authoritative `${BAMBOO_DATA_DIR}/projects/<id>/project.json`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectManifest {
    pub schema_version: u32,
    pub id: ProjectId,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default)]
    pub status: ProjectStatus,
    /// Canonical user source/work folder used when an assigned session has no
    /// explicit or persisted workspace. This is distinct from Bamboo's private
    /// `${BAMBOO_DATA_DIR}/projects/<id>` Project home.
    ///
    /// Legacy v1 manifests may remain unconfigured (`None`) until the user
    /// selects a path. New active Projects must be created with this field.
    #[serde(default)]
    pub project_path: Option<String>,
    /// Explicit migration/configuration state. Consumers must not infer a
    /// primary path from `workspace_bindings` ordering or labels.
    #[serde(default)]
    pub project_path_status: ProjectPathStatus,
    /// Additional registered workspaces/worktrees. `project_path` is itself an
    /// authoritative registered root and is not duplicated in this collection.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub workspace_bindings: Vec<WorkspaceBinding>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub legacy_project_keys: Vec<String>,
    /// CAS token for metadata and workspace binding updates.
    #[serde(default = "initial_project_revision")]
    pub revision: u64,
    /// Revision of the Project-shared resource inventory.
    #[serde(default = "initial_project_revision")]
    pub resource_revision: u64,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl ProjectManifest {
    pub fn new(
        id: ProjectId,
        name: impl Into<String>,
        description: Option<String>,
        now: DateTime<Utc>,
    ) -> Self {
        Self {
            schema_version: PROJECT_MANIFEST_SCHEMA_VERSION,
            id,
            name: name.into(),
            description,
            status: ProjectStatus::Active,
            project_path: None,
            project_path_status: ProjectPathStatus::NeedsConfiguration,
            workspace_bindings: Vec::new(),
            legacy_project_keys: Vec::new(),
            revision: 1,
            resource_revision: 1,
            created_at: now,
            updated_at: now,
        }
    }

    /// Every workspace root owned by this Project, with the primary
    /// `project_path` first when configured.
    pub fn workspace_roots(&self) -> impl Iterator<Item = &str> {
        self.project_path.iter().map(String::as_str).chain(
            self.workspace_bindings
                .iter()
                .map(|binding| binding.path.as_str()),
        )
    }

    pub fn workspace_count(&self) -> usize {
        usize::from(self.project_path.is_some()) + self.workspace_bindings.len()
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectIndexEntry {
    pub id: ProjectId,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    pub status: ProjectStatus,
    #[serde(default)]
    pub project_path: Option<String>,
    #[serde(default)]
    pub project_path_status: ProjectPathStatus,
    pub revision: u64,
    pub resource_revision: u64,
    pub workspace_count: usize,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
}

impl From<&ProjectManifest> for ProjectIndexEntry {
    fn from(manifest: &ProjectManifest) -> Self {
        Self {
            id: manifest.id.clone(),
            name: manifest.name.clone(),
            description: manifest.description.clone(),
            status: manifest.status,
            project_path: manifest.project_path.clone(),
            project_path_status: manifest.project_path_status,
            revision: manifest.revision,
            resource_revision: manifest.resource_revision,
            workspace_count: manifest.workspace_count(),
            created_at: manifest.created_at,
            updated_at: manifest.updated_at,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectIndex {
    pub schema_version: u32,
    pub revision: u64,
    pub updated_at: DateTime<Utc>,
    pub projects: BTreeMap<ProjectId, ProjectIndexEntry>,
}

impl ProjectIndex {
    pub fn empty(now: DateTime<Utc>) -> Self {
        Self {
            schema_version: PROJECT_INDEX_SCHEMA_VERSION,
            revision: 0,
            updated_at: now,
            projects: BTreeMap::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProjectResourceKind {
    Settings,
    Skills,
    Commands,
    Memory,
    Artifacts,
    State,
}

/// Redacted inventory entry. It intentionally contains no file contents,
/// environment values, headers, credential references, or secrets.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectResourceEntry {
    pub kind: ProjectResourceKind,
    pub present: bool,
    pub item_count: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProjectResourceSummary {
    pub project_id: ProjectId,
    pub resource_revision: u64,
    pub resources: Vec<ProjectResourceEntry>,
}

/// Legacy session input for the migration dry-run seam. Callers may provide
/// canonical/Git/key evidence explicitly; the server can enrich only omitted
/// evidence from a readable `workspace_path`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacySessionProjectInput {
    pub session_id: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub workspace_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub canonical_path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git_common_dir: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub legacy_project_keys: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LegacyProjectMatchBasis {
    ExactCanonicalBinding,
    GitCommonDir,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyProjectAssignment {
    pub session_id: String,
    pub project_id: ProjectId,
    pub basis: LegacyProjectMatchBasis,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyProjectSuggestion {
    pub basis: LegacyProjectMatchBasis,
    pub session_ids: Vec<String>,
    pub workspace_paths: Vec<String>,
    pub legacy_project_keys: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyProjectUnassigned {
    pub session_id: String,
    pub reason: String,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyProjectDryRunReport {
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub assignments: Vec<LegacyProjectAssignment>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub suggestions: Vec<LegacyProjectSuggestion>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unassigned: Vec<LegacyProjectUnassigned>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub diagnostics: Vec<String>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LegacyMemoryMigrationPhase {
    Copying,
    Verified,
    Committed,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LegacyMemoryFileDisposition {
    Pending,
    Staged,
    Copied,
    ExistingIdentical,
    TargetConflict,
    /// The source remains untouched as a read-only legacy record, but is not
    /// copied into Project primary storage because canonical validation failed.
    SkippedInvalid,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyMemoryMigrationFile {
    /// Slash-separated relative path below the legacy/project memory roots.
    pub relative_path: String,
    pub size: u64,
    pub sha256: String,
    pub disposition: LegacyMemoryFileDisposition,
    /// Redacted validation diagnostic. This describes why an individual
    /// source record was isolated without embedding its contents.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub diagnostic: Option<String>,
}

/// Durable status returned by the actual copy -> verify -> commit migration.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyMemoryMigrationReport {
    pub project_id: ProjectId,
    pub legacy_project_key: String,
    pub transaction_id: String,
    pub phase: LegacyMemoryMigrationPhase,
    pub files: Vec<LegacyMemoryMigrationFile>,
    pub started_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub committed_at: Option<DateTime<Utc>>,
}

/// Read-compatibility alias. The Project-home root always has precedence; the
/// legacy scope is read-only and only fills entries absent from the new root.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LegacyMemoryReadAlias {
    pub legacy_project_key: String,
    pub read_only: bool,
    pub project_home_precedence: bool,
    pub source_available: bool,
    pub migration_committed: bool,
}

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

    #[test]
    fn project_id_is_opaque_and_path_safe() {
        for valid in ["01JABCDEF0123456789ABCDEFG", "uuid-like_value-1"] {
            let id: ProjectId = valid.parse().unwrap();
            assert_eq!(id.as_str(), valid);
            let encoded = serde_json::to_string(&id).unwrap();
            assert_eq!(serde_json::from_str::<ProjectId>(&encoded).unwrap(), id);
        }

        for invalid in ["", ".", "..", "../escape", "a/b", r"a\b", "with space"] {
            assert!(invalid.parse::<ProjectId>().is_err(), "{invalid}");
        }
    }

    #[test]
    fn manifest_additive_fields_have_safe_defaults() {
        let value = serde_json::json!({
            "schema_version": 1,
            "id": "01JABCDEF0123456789ABCDEFG",
            "name": "Zenith",
            "created_at": "2026-01-01T00:00:00Z",
            "updated_at": "2026-01-01T00:00:00Z"
        });
        let manifest: ProjectManifest = serde_json::from_value(value).unwrap();
        assert_eq!(manifest.status, ProjectStatus::Active);
        assert!(manifest.project_path.is_none());
        assert_eq!(
            manifest.project_path_status,
            ProjectPathStatus::NeedsConfiguration
        );
        assert!(manifest.workspace_bindings.is_empty());
        assert!(manifest.legacy_project_keys.is_empty());
        assert_eq!(manifest.revision, 1);
        assert_eq!(manifest.resource_revision, 1);
    }
}