everruns-host 0.24.0

Shared host orchestration for Everruns execution adapters
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
//! Host-owned workspace, head, and session-environment contracts.
//!
//! A workspace is logical lineage. A head is one reopenable mutable view of
//! that lineage. Physical storage stays backend-owned and is projected into
//! execution through the existing [`SessionFileSystem`] contract.

use std::any::{Any, TypeId};
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use std::sync::{Arc, Mutex};

use async_trait::async_trait;
use everruns_core::session_files::SessionFileSystem;

use crate::compute::{Compute, ComputeCapabilities, Containment, ContainmentLevel, Durability};
use everruns_provider::typed_id::{SessionId, WorkspaceId};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use uuid::Uuid;

/// Stable, backend-defined SPI identifier.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct WorkspaceBackendId(String);

impl WorkspaceBackendId {
    pub fn new(value: impl Into<String>) -> Result<Self, WorkspaceError> {
        let value = value.into();
        if value.trim().is_empty() || value.len() > 128 {
            return Err(WorkspaceError::InvalidRequest(
                "workspace backend id must contain 1..=128 characters".into(),
            ));
        }
        Ok(Self(value))
    }

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

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

/// Stable identity of one mutable workspace head.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct WorkspaceHeadId(Uuid);

impl WorkspaceHeadId {
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }

    pub const fn from_uuid(value: Uuid) -> Self {
        Self(value)
    }

    pub const fn uuid(self) -> Uuid {
        self.0
    }
}

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

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

/// Backend-owned data sufficient to reopen the exact recorded head.
///
/// Callers persist this value opaquely. Backends must not place credentials
/// in `payload`; local persistence intentionally stores it as plain data.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct WorkspaceBinding {
    pub provider_id: WorkspaceBackendId,
    pub workspace_id: WorkspaceId,
    pub head_id: WorkspaceHeadId,
    pub access: WorkspaceHeadAccess,
    #[serde(default)]
    pub payload: Vec<u8>,
}

impl WorkspaceBinding {
    /// Maximum backend payload accepted by Framework persistence.
    pub const MAX_PAYLOAD_BYTES: usize = 64 * 1024;

    pub fn validate(&self) -> Result<(), WorkspaceError> {
        if self.payload.len() > Self::MAX_PAYLOAD_BYTES {
            return Err(WorkspaceError::InvalidRequest(
                "workspace binding payload is too large".into(),
            ));
        }
        Ok(())
    }
}

/// Whether a head is intended for one session or intentionally shared.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkspaceHeadAccess {
    #[default]
    Isolated,
    Shared,
}

/// Backend-neutral identity and base metadata for a logical workspace.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceDescriptor {
    pub id: WorkspaceId,
    pub name: String,
    pub metadata: BTreeMap<String, String>,
}

/// Backend-neutral identity and base metadata for a head.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceHeadDescriptor {
    pub id: WorkspaceHeadId,
    pub name: String,
    pub base: Option<String>,
    pub access: WorkspaceHeadAccess,
    pub metadata: BTreeMap<String, String>,
}

/// A backend-produced head resource before the Framework attaches lifecycle.
pub struct WorkspaceHeadResource {
    pub workspace: WorkspaceDescriptor,
    pub head: WorkspaceHeadDescriptor,
    pub binding: WorkspaceBinding,
    pub file_system: Arc<dyn SessionFileSystem>,
}

/// Request to create or fork one head.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceHeadRequest {
    pub name: String,
    pub base: Option<String>,
    pub access: WorkspaceHeadAccess,
}

/// Backend-neutral checkpoint metadata.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorkspaceCheckpoint {
    pub revision: String,
    pub metadata: BTreeMap<String, String>,
}

/// Backend-neutral mutable-head status.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WorkspaceHeadStatus {
    pub dirty: bool,
    pub conflicted: bool,
    pub archived: bool,
    pub metadata: BTreeMap<String, String>,
}

/// Backend-neutral diff summary for one mutable head.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct WorkspaceDiff {
    pub changed: bool,
    pub conflicted: bool,
    pub metadata: BTreeMap<String, String>,
}

/// Errors exposed by workspace backends and lifecycle operations.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum WorkspaceError {
    #[error("invalid workspace request: {0}")]
    InvalidRequest(String),
    /// The workspace backend is not available.
    #[error("workspace backend is unavailable: {0}")]
    BackendUnavailable(String),
    /// Compatibility variant emitted by built-in backends during its deprecation window.
    #[deprecated(note = "use BackendUnavailable")]
    #[error("workspace backend is unavailable: {0}")]
    ProviderUnavailable(String),
    #[error("workspace or head was not found")]
    NotFound,
    #[error("workspace head is archived")]
    Archived,
    #[error("workspace head has a conflicting update")]
    Conflict,
    #[error("workspace binding does not match the requested backend, workspace, or head")]
    BindingMismatch,
    /// The workspace backend rejected the requested operation.
    #[error("workspace backend failed: {0}")]
    Backend(String),
    /// Compatibility variant emitted by built-in backends during its deprecation window.
    #[deprecated(note = "use Backend")]
    #[error("workspace backend failed: {0}")]
    Provider(String),
}

/// Open interface for physical workspace implementations.
///
/// Git worktrees are one implementation. Remote filesystems, containers, and
/// object-backed snapshots can implement the same trait without registering a
/// backend enum or exposing physical paths in the universal contract.
#[async_trait]
pub trait WorkspaceBackend: Send + Sync {
    fn id(&self) -> WorkspaceBackendId;

    async fn open_workspace(&self, locator: &str) -> Result<WorkspaceDescriptor, WorkspaceError>;

    /// Reopen a logical workspace using only its recorded opaque binding.
    async fn open_workspace_from_binding(
        &self,
        binding: &WorkspaceBinding,
    ) -> Result<WorkspaceDescriptor, WorkspaceError>;

    async fn create_head(
        &self,
        workspace: &WorkspaceDescriptor,
        request: WorkspaceHeadRequest,
    ) -> Result<WorkspaceHeadResource, WorkspaceError>;

    async fn reopen_head(
        &self,
        binding: &WorkspaceBinding,
    ) -> Result<WorkspaceHeadResource, WorkspaceError>;

    async fn checkpoint(
        &self,
        binding: &WorkspaceBinding,
    ) -> Result<WorkspaceCheckpoint, WorkspaceError>;

    async fn status(
        &self,
        binding: &WorkspaceBinding,
    ) -> Result<WorkspaceHeadStatus, WorkspaceError>;

    async fn diff(&self, binding: &WorkspaceBinding) -> Result<WorkspaceDiff, WorkspaceError>;

    /// Archive a head while retaining its backend-owned contents.
    async fn archive(&self, binding: &WorkspaceBinding) -> Result<(), WorkspaceError>;

    /// Explicitly destroy backend-owned head storage.
    ///
    /// Backends must never call this from `Drop`. Backend-specific durable
    /// lineage such as a Git branch is retained unless the backend documents
    /// a separate, explicit deletion operation.
    async fn destroy(&self, binding: &WorkspaceBinding) -> Result<(), WorkspaceError>;
}

/// One logical workspace opened through a backend.
#[derive(Clone)]
pub struct Workspace {
    backend: Arc<dyn WorkspaceBackend>,
    descriptor: WorkspaceDescriptor,
}

impl Workspace {
    pub fn from_descriptor(
        backend: Arc<dyn WorkspaceBackend>,
        descriptor: WorkspaceDescriptor,
    ) -> Self {
        Self {
            backend,
            descriptor,
        }
    }

    pub async fn open(
        backend: Arc<dyn WorkspaceBackend>,
        locator: impl AsRef<str>,
    ) -> Result<Self, WorkspaceError> {
        let descriptor = backend.open_workspace(locator.as_ref()).await?;
        Ok(Self {
            backend,
            descriptor,
        })
    }

    pub fn id(&self) -> WorkspaceId {
        self.descriptor.id
    }

    pub fn name(&self) -> &str {
        &self.descriptor.name
    }

    pub fn metadata(&self) -> &BTreeMap<String, String> {
        &self.descriptor.metadata
    }

    pub fn head(&self, name: impl Into<String>) -> WorkspaceHeadBuilder {
        WorkspaceHeadBuilder {
            workspace: self.clone(),
            name: name.into(),
            base: None,
            access: WorkspaceHeadAccess::Isolated,
        }
    }

    pub async fn reopen(
        &self,
        binding: &WorkspaceBinding,
    ) -> Result<WorkspaceHead, WorkspaceError> {
        if binding.provider_id != self.backend.id() || binding.workspace_id != self.id() {
            return Err(WorkspaceError::BindingMismatch);
        }
        let resource = self.backend.reopen_head(binding).await?;
        self.attach(resource, Some(binding))
    }

    fn attach(
        &self,
        resource: WorkspaceHeadResource,
        expected: Option<&WorkspaceBinding>,
    ) -> Result<WorkspaceHead, WorkspaceError> {
        resource.binding.validate()?;
        if resource.workspace.id != self.id()
            || resource.binding.provider_id != self.backend.id()
            || resource.binding.workspace_id != self.id()
            || resource.binding.head_id != resource.head.id
            || resource.binding.access != resource.head.access
            || expected.is_some_and(|expected| expected != &resource.binding)
        {
            return Err(WorkspaceError::BindingMismatch);
        }
        Ok(WorkspaceHead {
            backend: self.backend.clone(),
            workspace: resource.workspace,
            descriptor: resource.head,
            binding: resource.binding,
            file_system: resource.file_system,
        })
    }
}

impl fmt::Debug for Workspace {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Workspace")
            .field("backend", &self.backend.id())
            .field("descriptor", &self.descriptor)
            .finish()
    }
}

/// Builder for explicit isolated or shared heads.
pub struct WorkspaceHeadBuilder {
    workspace: Workspace,
    name: String,
    base: Option<String>,
    access: WorkspaceHeadAccess,
}

impl WorkspaceHeadBuilder {
    pub fn from_revision(mut self, revision: impl Into<String>) -> Self {
        self.base = Some(revision.into());
        self
    }

    /// Opt into concurrent sessions addressing the same mutable head.
    pub fn shared(mut self) -> Self {
        self.access = WorkspaceHeadAccess::Shared;
        self
    }

    pub async fn create(self) -> Result<WorkspaceHead, WorkspaceError> {
        if self.name.trim().is_empty() || self.name.len() > 256 {
            return Err(WorkspaceError::InvalidRequest(
                "workspace head name must contain 1..=256 characters".into(),
            ));
        }
        let resource = self
            .workspace
            .backend
            .create_head(
                &self.workspace.descriptor,
                WorkspaceHeadRequest {
                    name: self.name,
                    base: self.base,
                    access: self.access,
                },
            )
            .await?;
        self.workspace.attach(resource, None)
    }
}

/// One stable, reopenable mutable view of a workspace.
#[derive(Clone)]
pub struct WorkspaceHead {
    backend: Arc<dyn WorkspaceBackend>,
    workspace: WorkspaceDescriptor,
    descriptor: WorkspaceHeadDescriptor,
    binding: WorkspaceBinding,
    file_system: Arc<dyn SessionFileSystem>,
}

impl WorkspaceHead {
    /// Backend that owns this head. Applications normally use lifecycle
    /// methods on the head; the facade uses this handle to make typed resume
    /// available for the Agent lifetime.
    pub fn backend(&self) -> Arc<dyn WorkspaceBackend> {
        self.backend.clone()
    }

    #[deprecated(note = "use WorkspaceHead::backend")]
    pub fn provider(&self) -> Arc<dyn WorkspaceBackend> {
        self.backend()
    }

    pub fn workspace_id(&self) -> WorkspaceId {
        self.workspace.id
    }

    pub fn id(&self) -> WorkspaceHeadId {
        self.descriptor.id
    }

    pub fn name(&self) -> &str {
        &self.descriptor.name
    }

    pub fn base(&self) -> Option<&str> {
        self.descriptor.base.as_deref()
    }

    pub fn access(&self) -> WorkspaceHeadAccess {
        self.descriptor.access
    }

    pub fn binding(&self) -> &WorkspaceBinding {
        &self.binding
    }

    pub fn file_system(&self) -> Arc<dyn SessionFileSystem> {
        self.file_system.clone()
    }

    pub async fn checkpoint(&self) -> Result<WorkspaceCheckpoint, WorkspaceError> {
        self.backend.checkpoint(&self.binding).await
    }

    pub async fn status(&self) -> Result<WorkspaceHeadStatus, WorkspaceError> {
        self.backend.status(&self.binding).await
    }

    pub async fn diff(&self) -> Result<WorkspaceDiff, WorkspaceError> {
        self.backend.diff(&self.binding).await
    }

    pub async fn archive(&self) -> Result<(), WorkspaceError> {
        self.backend.archive(&self.binding).await
    }

    pub async fn destroy(self) -> Result<(), WorkspaceError> {
        self.backend.destroy(&self.binding).await
    }

    /// Create a new isolated head from this head's current checkpoint.
    pub async fn fork(&self, name: impl Into<String>) -> Result<WorkspaceHead, WorkspaceError> {
        let checkpoint = self.checkpoint().await?;
        Workspace {
            backend: self.backend.clone(),
            descriptor: self.workspace.clone(),
        }
        .head(name)
        .from_revision(checkpoint.revision)
        .create()
        .await
    }
}

impl fmt::Debug for WorkspaceHead {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("WorkspaceHead")
            .field("backend", &self.backend.id())
            .field("workspace", &self.workspace)
            .field("descriptor", &self.descriptor)
            .field("binding", &self.binding)
            .finish_non_exhaustive()
    }
}

/// Session execution resources: the workspace head every file tool addresses,
/// the compute that runs commands against it, and what that compute may touch.
///
/// Compute and containment were an open extension seam until EVE-1042; they are
/// named members now because a caller has to be able to read them without
/// guessing a type. An Environment with no compute is still valid: plenty of
/// agents only ever read and write files.
#[derive(Clone)]
pub struct Environment {
    head: WorkspaceHead,
    compute: Option<Arc<dyn Compute>>,
    containment: Containment,
    extensions: Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
}

impl Environment {
    /// Create an Environment containing one workspace head and no extensions.
    pub fn new(head: WorkspaceHead) -> Self {
        Self {
            head,
            compute: None,
            containment: Containment::none(),
            extensions: Arc::new(HashMap::new()),
        }
    }

    pub fn builder() -> EnvironmentBuilder {
        EnvironmentBuilder::default()
    }

    pub fn workspace_head(&self) -> &WorkspaceHead {
        &self.head
    }

    /// The compute this session runs commands on, if it has any.
    pub fn compute(&self) -> Option<Arc<dyn Compute>> {
        self.compute.clone()
    }

    /// What commands may touch. Without compute this is
    /// [`Containment::none`] and says nothing, since nothing runs.
    pub fn containment(&self) -> &Containment {
        &self.containment
    }

    /// What this environment can actually do. A file-only environment can do
    /// none of it, which is the honest answer rather than an absent one.
    pub fn capabilities(&self) -> ComputeCapabilities {
        self.compute
            .as_ref()
            .map(|compute| compute.capabilities())
            .unwrap_or_default()
    }

    /// What survives losing the compute. Read from the target, never claimed by
    /// a profile, so nothing can promise recovery a provider cannot deliver.
    pub fn durability(&self) -> Durability {
        self.compute
            .as_ref()
            .map(|compute| compute.durability())
            .unwrap_or(Durability::Checkpointed)
    }

    pub fn extension<T: Any + Send + Sync>(&self) -> Option<Arc<T>> {
        self.extensions
            .get(&TypeId::of::<T>())
            .and_then(|value| value.clone().downcast().ok())
    }
}

impl fmt::Debug for Environment {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Environment")
            .field("head", &self.head)
            .field(
                "compute",
                &self.compute.as_ref().map(|compute| compute.id()),
            )
            .field("containment", &self.containment.level)
            .field("extension_count", &self.extensions.len())
            .finish()
    }
}

#[derive(Default)]
pub struct EnvironmentBuilder {
    head: Option<WorkspaceHead>,
    compute: Option<Arc<dyn Compute>>,
    containment: Option<Containment>,
    extensions: HashMap<TypeId, Arc<dyn Any + Send + Sync>>,
}

impl EnvironmentBuilder {
    pub fn workspace(mut self, head: WorkspaceHead) -> Self {
        self.head = Some(head);
        self
    }

    /// Select where commands run.
    pub fn compute(mut self, compute: Arc<dyn Compute>) -> Self {
        self.compute = Some(compute);
        self
    }

    /// State what commands may touch.
    ///
    /// Stating it is the point: an omitted field that silently means "nothing
    /// contains this" is how a trusted-operator default becomes an accident.
    /// Omit it only to accept whatever the target enforces.
    pub fn containment(mut self, containment: Containment) -> Self {
        self.containment = Some(containment);
        self
    }

    pub fn extension<T: Any + Send + Sync>(mut self, value: Arc<T>) -> Self {
        self.extensions.insert(TypeId::of::<T>(), value);
        self
    }

    /// Attach a typed resource constructed from the selected head.
    ///
    /// Compute providers use this form when their process, container, or
    /// remote mount must address the exact same head as Framework file tools.
    /// Call [`workspace`](Self::workspace) first.
    pub fn workspace_extension<T: Any + Send + Sync>(
        mut self,
        create: impl FnOnce(&WorkspaceHead) -> Arc<T>,
    ) -> Result<Self, EnvironmentError> {
        let head = self
            .head
            .as_ref()
            .ok_or(EnvironmentError::MissingWorkspace)?;
        self.extensions.insert(TypeId::of::<T>(), create(head));
        Ok(self)
    }

    pub fn build(self) -> Result<Environment, EnvironmentError> {
        let head = self.head.ok_or(EnvironmentError::MissingWorkspace)?;
        let enforced = self
            .compute
            .as_ref()
            .map(|compute| compute.enforced_containment())
            .unwrap_or(ContainmentLevel::None);

        let containment = match self.containment {
            // Nothing asked for, so record what the target already enforces.
            None => match enforced {
                ContainmentLevel::Isolated => Containment::isolated(),
                ContainmentLevel::Native => Containment::native(),
                ContainmentLevel::None => Containment::none(),
            },
            Some(requested) => {
                // Claiming less than the target enforces would make the profile
                // lie about a boundary that is there regardless; claiming more
                // would promise one that nothing implements yet. Both are
                // errors rather than a silent correction.
                if requested.level < enforced {
                    return Err(EnvironmentError::ContainmentWeakerThanTarget {
                        requested: requested.level,
                        enforced,
                    });
                }
                if requested.level > enforced {
                    return Err(EnvironmentError::ContainmentUnavailable {
                        requested: requested.level,
                    });
                }
                requested
            }
        };

        Ok(Environment {
            head,
            compute: self.compute,
            containment,
            extensions: Arc::new(self.extensions),
        })
    }
}

/// Why an Environment could not be assembled.
#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum EnvironmentError {
    #[error("environment requires a workspace head")]
    MissingWorkspace,
    #[error(
        "containment `{requested}` is weaker than the `{enforced}` this target enforces; \
         a target's own boundary cannot be opted out of"
    )]
    ContainmentWeakerThanTarget {
        requested: ContainmentLevel,
        enforced: ContainmentLevel,
    },
    #[error("containment `{requested}` is not implemented for this target yet")]
    ContainmentUnavailable { requested: ContainmentLevel },
}

impl From<EnvironmentError> for WorkspaceError {
    /// Facade paths that assemble a default Environment still return
    /// `WorkspaceError`. Assembly failures are request errors from their point
    /// of view, and the message keeps the specific reason.
    fn from(error: EnvironmentError) -> Self {
        Self::InvalidRequest(error.to_string())
    }
}

/// Durable compare-and-set store for a session's opaque environment binding.
#[async_trait]
pub trait EnvironmentBindingStore: Send + Sync {
    async fn load(
        &self,
        session_id: SessionId,
    ) -> Result<Option<WorkspaceBinding>, EnvironmentBindingError>;

    async fn bind(
        &self,
        session_id: SessionId,
        binding: &WorkspaceBinding,
    ) -> Result<(), EnvironmentBindingError>;
}

#[derive(Clone, Debug, Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum EnvironmentBindingError {
    #[error("session is already bound to a different workspace head")]
    Conflict,
    #[error("environment binding store is unavailable")]
    Unavailable,
    #[error("persisted environment binding is corrupt")]
    Corrupt,
}

/// Process-local binding store used by the default embedded Agent lifecycle.
#[derive(Default)]
pub struct InMemoryEnvironmentBindingStore {
    bindings: Mutex<HashMap<SessionId, WorkspaceBinding>>,
}

#[async_trait]
impl EnvironmentBindingStore for InMemoryEnvironmentBindingStore {
    async fn load(
        &self,
        session_id: SessionId,
    ) -> Result<Option<WorkspaceBinding>, EnvironmentBindingError> {
        Ok(self
            .bindings
            .lock()
            .map_err(|_| EnvironmentBindingError::Unavailable)?
            .get(&session_id)
            .cloned())
    }

    async fn bind(
        &self,
        session_id: SessionId,
        binding: &WorkspaceBinding,
    ) -> Result<(), EnvironmentBindingError> {
        if binding.payload.len() > WorkspaceBinding::MAX_PAYLOAD_BYTES {
            return Err(EnvironmentBindingError::Corrupt);
        }
        let mut bindings = self
            .bindings
            .lock()
            .map_err(|_| EnvironmentBindingError::Unavailable)?;
        match bindings.get(&session_id) {
            Some(recorded) if recorded != binding => Err(EnvironmentBindingError::Conflict),
            Some(_) => Ok(()),
            None => {
                let incompatible_claim = bindings.iter().any(|(recorded_session, recorded)| {
                    recorded_session != &session_id
                        && recorded.provider_id == binding.provider_id
                        && recorded.workspace_id == binding.workspace_id
                        && recorded.head_id == binding.head_id
                        && (binding.access == WorkspaceHeadAccess::Isolated
                            || recorded.access == WorkspaceHeadAccess::Isolated)
                });
                if incompatible_claim {
                    return Err(EnvironmentBindingError::Conflict);
                }
                bindings.insert(session_id, binding.clone());
                Ok(())
            }
        }
    }
}