agent-workspace-contract 0.7.0

Transport-neutral contracts for Agent Infra workspace APIs
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
//! Persistence ports and typed metadata deltas for Environment aggregates.

use super::*;
use crate::{CommandSpec, PortUrl, ProviderPortTarget};

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub enum EnvironmentIdempotencyState {
    Pending,
    Completed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct EnvironmentIdempotencyRecord {
    pub id: String,
    pub scope: ResourceScope,
    pub action: String,
    /// SHA-256 of the caller-provided key; the key itself is never persisted.
    pub key_hash: String,
    pub request_hash: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub resource_id: Option<String>,
    pub state: EnvironmentIdempotencyState,
    /// Runtime instance currently allowed to enter Provider I/O.
    pub claim_owner: String,
    /// A dead instance can be taken over only after this lease expires.
    pub claim_expires_at_ms: u64,
    pub attempt: u32,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub result_json: Option<String>,
    pub started_at_ms: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub completed_at_ms: Option<u64>,
}

/// Durable metadata snapshot for one tenant/project scope.
///
/// Provider bytes and credentials are deliberately absent. Repositories may
/// store each collection in a dedicated table while exposing one CAS unit to
/// the application service so fencing and revision changes commit together.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields, rename_all = "camelCase")]
pub struct EnvironmentMetadataSnapshot {
    #[serde(default)]
    pub user_computers: Vec<crate::UserComputerBinding>,
    #[serde(default)]
    pub conversation_spaces: Vec<crate::ConversationSpaceBinding>,
    #[serde(default)]
    pub workspace_bindings: Vec<crate::WorkspacePolicyBinding>,
    #[serde(default)]
    pub workspace_policies: Vec<crate::WorkspacePolicyRecord>,
    pub version: u64,
    #[serde(default)]
    pub computers: Vec<ComputerRecord>,
    #[serde(default)]
    pub spaces: Vec<SpaceRecord>,
    #[serde(default)]
    pub sandboxes: Vec<SandboxRecord>,
    #[serde(default)]
    pub managed_workloads: Vec<ManagedWorkload>,
    #[serde(default)]
    pub snapshots: Vec<SnapshotRecord>,
    #[serde(default)]
    pub templates: Vec<TemplateVersionRecord>,
    #[serde(default)]
    pub grants: Vec<SpaceGrant>,
    #[serde(default)]
    pub sessions: Vec<SpaceCollaborationSession>,
    #[serde(default)]
    pub tickets: Vec<SpaceAccessTicketRecord>,
    #[serde(default)]
    pub leases: Vec<SpaceWriteLease>,
    #[serde(default)]
    pub fencing_tokens: BTreeMap<String, u64>,
    #[serde(default)]
    pub delegations: Vec<DelegationRecord>,
    #[serde(default)]
    pub change_sets: Vec<SpaceChangeSetRecord>,
    #[serde(default)]
    pub idempotency: Vec<EnvironmentIdempotencyRecord>,
}

/// Incremental metadata changes for one aggregate collection.
///
/// Upserts and deletes are committed under the enclosing scope-version CAS;
/// unchanged aggregates never cross the repository boundary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvironmentMetadataCollectionPatch<T> {
    pub upserts: Vec<T>,
    pub deletes: Vec<String>,
}

impl<T> Default for EnvironmentMetadataCollectionPatch<T> {
    fn default() -> Self {
        Self {
            upserts: Vec::new(),
            deletes: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EnvironmentFencingTokenPatch {
    pub upserts: BTreeMap<String, u64>,
    pub deletes: Vec<String>,
}

/// Typed delta for one tenant/project Environment aggregate set.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EnvironmentMetadataPatch {
    pub user_computers: EnvironmentMetadataCollectionPatch<crate::UserComputerBinding>,
    pub conversation_spaces: EnvironmentMetadataCollectionPatch<crate::ConversationSpaceBinding>,
    pub workspace_bindings: EnvironmentMetadataCollectionPatch<crate::WorkspacePolicyBinding>,
    pub workspace_policies: EnvironmentMetadataCollectionPatch<crate::WorkspacePolicyRecord>,
    pub version: u64,
    pub computers: EnvironmentMetadataCollectionPatch<ComputerRecord>,
    pub spaces: EnvironmentMetadataCollectionPatch<SpaceRecord>,
    pub sandboxes: EnvironmentMetadataCollectionPatch<SandboxRecord>,
    pub managed_workloads: EnvironmentMetadataCollectionPatch<ManagedWorkload>,
    pub snapshots: EnvironmentMetadataCollectionPatch<SnapshotRecord>,
    pub templates: EnvironmentMetadataCollectionPatch<TemplateVersionRecord>,
    pub grants: EnvironmentMetadataCollectionPatch<SpaceGrant>,
    pub sessions: EnvironmentMetadataCollectionPatch<SpaceCollaborationSession>,
    pub tickets: EnvironmentMetadataCollectionPatch<SpaceAccessTicketRecord>,
    pub leases: EnvironmentMetadataCollectionPatch<SpaceWriteLease>,
    pub fencing_tokens: EnvironmentFencingTokenPatch,
    pub delegations: EnvironmentMetadataCollectionPatch<DelegationRecord>,
    pub change_sets: EnvironmentMetadataCollectionPatch<SpaceChangeSetRecord>,
    pub idempotency: EnvironmentMetadataCollectionPatch<EnvironmentIdempotencyRecord>,
}

impl EnvironmentMetadataPatch {
    pub fn between(
        before: &EnvironmentMetadataSnapshot,
        after: &EnvironmentMetadataSnapshot,
    ) -> Self {
        Self {
            version: after.version,
            user_computers: collection_patch(&before.user_computers, &after.user_computers, |v| {
                v.id.clone()
            }),
            conversation_spaces: collection_patch(
                &before.conversation_spaces,
                &after.conversation_spaces,
                |v| v.id.clone(),
            ),
            workspace_bindings: collection_patch(
                &before.workspace_bindings,
                &after.workspace_bindings,
                |value| value.id.clone(),
            ),
            workspace_policies: collection_patch(
                &before.workspace_policies,
                &after.workspace_policies,
                |value| value.id.clone(),
            ),
            computers: collection_patch(&before.computers, &after.computers, |value| {
                value.id.clone()
            }),
            spaces: collection_patch(&before.spaces, &after.spaces, |value| value.id.clone()),
            sandboxes: collection_patch(&before.sandboxes, &after.sandboxes, |value| {
                value.id.clone()
            }),
            managed_workloads: collection_patch(
                &before.managed_workloads,
                &after.managed_workloads,
                |value| value.id.clone(),
            ),
            snapshots: collection_patch(&before.snapshots, &after.snapshots, |value| {
                value.id.clone()
            }),
            templates: collection_patch(&before.templates, &after.templates, |value| {
                format!("{}\0{}", value.template_id, value.version)
            }),
            grants: collection_patch(&before.grants, &after.grants, |value| value.id.clone()),
            sessions: collection_patch(&before.sessions, &after.sessions, |value| value.id.clone()),
            tickets: collection_patch(&before.tickets, &after.tickets, |value| value.id.clone()),
            leases: collection_patch(&before.leases, &after.leases, |value| value.id.clone()),
            fencing_tokens: map_patch(&before.fencing_tokens, &after.fencing_tokens),
            delegations: collection_patch(&before.delegations, &after.delegations, |value| {
                value.id.clone()
            }),
            change_sets: collection_patch(&before.change_sets, &after.change_sets, |value| {
                value.id.clone()
            }),
            idempotency: collection_patch(&before.idempotency, &after.idempotency, |value| {
                value.id.clone()
            }),
        }
    }

    pub fn changed_aggregate_count(&self) -> usize {
        let collections = [
            patch_size(&self.workspace_bindings),
            patch_size(&self.user_computers),
            patch_size(&self.conversation_spaces),
            patch_size(&self.workspace_policies),
            patch_size(&self.computers),
            patch_size(&self.spaces),
            patch_size(&self.sandboxes),
            patch_size(&self.managed_workloads),
            patch_size(&self.snapshots),
            patch_size(&self.templates),
            patch_size(&self.grants),
            patch_size(&self.sessions),
            patch_size(&self.tickets),
            patch_size(&self.leases),
            patch_size(&self.delegations),
            patch_size(&self.change_sets),
            patch_size(&self.idempotency),
        ];
        collections.into_iter().sum::<usize>()
            + self.fencing_tokens.upserts.len()
            + self.fencing_tokens.deletes.len()
    }
}

fn collection_patch<T: Clone + PartialEq>(
    before: &[T],
    after: &[T],
    id: impl Fn(&T) -> String,
) -> EnvironmentMetadataCollectionPatch<T> {
    let previous = before
        .iter()
        .map(|value| (id(value), value))
        .collect::<BTreeMap<_, _>>();
    let current = after
        .iter()
        .map(|value| (id(value), value))
        .collect::<BTreeMap<_, _>>();
    EnvironmentMetadataCollectionPatch {
        upserts: current
            .iter()
            .filter(|(key, value)| previous.get(*key).is_none_or(|old| *old != **value))
            .map(|(_, value)| (*value).clone())
            .collect(),
        deletes: previous
            .keys()
            .filter(|key| !current.contains_key(*key))
            .cloned()
            .collect(),
    }
}

fn map_patch(
    before: &BTreeMap<String, u64>,
    after: &BTreeMap<String, u64>,
) -> EnvironmentFencingTokenPatch {
    EnvironmentFencingTokenPatch {
        upserts: after
            .iter()
            .filter(|(key, value)| before.get(*key).is_none_or(|old| old != *value))
            .map(|(key, value)| (key.clone(), *value))
            .collect(),
        deletes: before
            .keys()
            .filter(|key| !after.contains_key(*key))
            .cloned()
            .collect(),
    }
}

fn patch_size<T>(patch: &EnvironmentMetadataCollectionPatch<T>) -> usize {
    patch.upserts.len() + patch.deletes.len()
}

/// Existence checks reveal no foreign aggregate or owner metadata.
#[derive(Debug, Clone, Copy)]
pub enum EnvironmentResourceKind {
    Computer,
    Space,
}

#[async_trait]
pub trait EnvironmentMetadataRepository: Send + Sync + Debug {
    async fn resource_exists_outside_scope(
        &self,
        kind: EnvironmentResourceKind,
        id: &str,
        scope: &ResourceScope,
    ) -> Result<bool>;
    async fn load(&self, scope: &ResourceScope) -> Result<EnvironmentMetadataSnapshot>;

    /// Stable tenant/project pagination for background lifecycle reconciliation.
    async fn list_scopes(
        &self,
        after: Option<&ResourceScope>,
        limit: usize,
    ) -> Result<Vec<ResourceScope>>;

    /// Atomically replace metadata when the stored scope version equals
    /// `expected_version`. Returns false on a concurrent writer conflict.
    async fn compare_and_swap(
        &self,
        scope: &ResourceScope,
        expected_version: u64,
        snapshot: &EnvironmentMetadataSnapshot,
    ) -> Result<bool>;

    /// Atomically apply only changed aggregates when the stored scope version
    /// equals `expected_version`.
    async fn compare_and_patch(
        &self,
        scope: &ResourceScope,
        expected_version: u64,
        patch: &EnvironmentMetadataPatch,
    ) -> Result<bool>;
}

/// Command metadata and output are stored independently from the Environment
/// aggregate snapshot. This keeps output appends O(chunks) instead of copying
/// every resource in a tenant/project scope.
#[async_trait]
pub trait EnvironmentCommandRepository: Send + Sync + Debug {
    async fn store_computer_command(
        &self,
        request: StoreComputerCommandRequest,
    ) -> Result<StoreComputerCommandOutcome>;

    async fn get_computer_command(
        &self,
        scope: &ResourceScope,
        computer_id: &str,
        command_id: &str,
    ) -> Result<Option<ComputerCommandResource>>;

    async fn transition_computer_command(
        &self,
        request: ComputerCommandTransition,
    ) -> Result<ComputerCommandResource>;

    async fn complete_computer_command(
        &self,
        request: CompleteComputerCommandRequest,
    ) -> Result<ComputerCommandResource>;

    async fn computer_command_output(
        &self,
        scope: &ResourceScope,
        computer_id: &str,
        command_id: &str,
        after: u64,
        limit: usize,
    ) -> Result<ComputerCommandOutputPage>;
}

/// Production Environment persistence owns both aggregate metadata and the
/// independently indexed command log.
pub trait EnvironmentRepository:
    EnvironmentMetadataRepository + EnvironmentCommandRepository
{
}
impl<T> EnvironmentRepository for T where
    T: EnvironmentMetadataRepository + EnvironmentCommandRepository
{
}

#[async_trait]
pub trait ComputerProvider: Send + Sync + Debug {
    fn kind(&self) -> &str;
    fn capabilities(&self) -> ProviderCapabilities;
    fn validate_create(&self, _request: &ProviderComputerRequest) -> Result<()> {
        Ok(())
    }
    async fn create_computer(
        &self,
        scope: &ResourceScope,
        request: &ProviderComputerRequest,
        idempotency_key: &str,
    ) -> Result<ProviderResourceRef>;
    async fn delete_computer(&self, external_id: &str, idempotency_key: &str) -> Result<()>;
    async fn port_url(&self, computer_external_id: &str, port: u16) -> Result<PortUrl> {
        let _ = (computer_external_id, port);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support preview URLs",
        )
        .into())
    }
    async fn port_target(
        &self,
        computer_external_id: &str,
        port: u16,
        path: &str,
        query: Option<&str>,
    ) -> Result<ProviderPortTarget> {
        let _ = (computer_external_id, port, path, query);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support proxied preview traffic",
        )
        .into())
    }
    async fn create_space_directory(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        request: &ProviderSpaceRequest,
        idempotency_key: &str,
    ) -> Result<()> {
        let _ = (
            computer_external_id,
            space_directory,
            request,
            idempotency_key,
        );
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support Space directories",
        )
        .into())
    }
    async fn delete_space_directory(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        idempotency_key: &str,
    ) -> Result<()> {
        let _ = (computer_external_id, space_directory, idempotency_key);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support Space directories",
        )
        .into())
    }
    async fn read_file(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        path: &str,
    ) -> Result<ProviderFileContent> {
        let _ = (computer_external_id, space_directory, path);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support file reads",
        )
        .into())
    }
    async fn write_file(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        path: &str,
        content: &[u8],
        expected_provider_revision: Option<&str>,
        idempotency_key: &str,
    ) -> Result<ProviderWriteResult> {
        let _ = (
            computer_external_id,
            space_directory,
            path,
            content,
            expected_provider_revision,
            idempotency_key,
        );
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support file writes",
        )
        .into())
    }
    async fn delete_file(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        path: &str,
        idempotency_key: &str,
    ) -> Result<()> {
        let _ = (computer_external_id, space_directory, path, idempotency_key);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support file deletes",
        )
        .into())
    }
    async fn list_files(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        path: &str,
    ) -> Result<Vec<ProviderFileEntry>> {
        let _ = (computer_external_id, space_directory, path);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support directory listing",
        )
        .into())
    }
    async fn source_archive(
        &self,
        computer_external_id: &str,
        space_directory: &str,
    ) -> Result<ProviderSourceArchive> {
        let _ = (computer_external_id, space_directory);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support source archives",
        )
        .into())
    }
    async fn create_change_set(
        &self,
        computer_external_id: &str,
        source_space_directory: &str,
        target_space_directory: &str,
        idempotency_key: &str,
    ) -> Result<String> {
        let _ = (
            computer_external_id,
            source_space_directory,
            target_space_directory,
            idempotency_key,
        );
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support change sets",
        )
        .into())
    }
    async fn apply_change_set(
        &self,
        computer_external_id: &str,
        source_space_directory: &str,
        target_space_directory: &str,
        provider_change_ref: &str,
        idempotency_key: &str,
    ) -> Result<ProviderWriteResult> {
        let _ = (
            computer_external_id,
            source_space_directory,
            target_space_directory,
            provider_change_ref,
            idempotency_key,
        );
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support change sets",
        )
        .into())
    }
    async fn exec_command(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        command: &CommandSpec,
    ) -> Result<ProviderCommandOutput> {
        let _ = (computer_external_id, space_directory, command);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "computer does not support managed commands",
        )
        .into())
    }
    /// Set mode/owner/group on a Space path through the Provider file API.
    /// Prefer this over user-level `chmod`/`chown` when Provider file writes create
    /// root-owned files that the sandbox user cannot mutate.
    async fn set_space_path_permissions(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        path: &str,
        mode: &str,
        owner: Option<&str>,
        group: Option<&str>,
    ) -> Result<()> {
        let _ = (
            computer_external_id,
            space_directory,
            path,
            mode,
            owner,
            group,
        );
        Ok(())
    }
    async fn exec_managed_command(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        command_id: &str,
        command: &CommandSpec,
    ) -> Result<ProviderCommandOutput> {
        let _ = command_id;
        self.exec_command(computer_external_id, space_directory, command)
            .await
    }
    async fn resume_managed_command(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        command_id: &str,
        command: &CommandSpec,
    ) -> Result<Option<ProviderCommandOutput>> {
        let _ = (computer_external_id, space_directory, command_id, command);
        Ok(None)
    }
    async fn retry_managed_command(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        command_id: &str,
        command: &CommandSpec,
    ) -> Result<Option<ProviderCommandOutput>> {
        self.resume_managed_command(computer_external_id, space_directory, command_id, command)
            .await
    }
    async fn cancel_command(
        &self,
        computer_external_id: &str,
        space_directory: &str,
        command_id: &str,
    ) -> Result<()> {
        let _ = (computer_external_id, space_directory, command_id);
        Ok(())
    }
}

#[async_trait]
pub trait SandboxProvider: Send + Sync + Debug {
    fn kind(&self) -> &str;
    fn capabilities(&self) -> ProviderCapabilities;
    fn validate_create(&self, _request: &ProviderSandboxRequest) -> Result<()> {
        Ok(())
    }
    async fn create_sandbox(
        &self,
        scope: &ResourceScope,
        request: &ProviderSandboxRequest,
        idempotency_key: &str,
    ) -> Result<ProviderResourceRef>;
    async fn stop_sandbox(&self, external_id: &str, idempotency_key: &str) -> Result<()>;
    async fn write_file(
        &self,
        external_id: &str,
        path: &str,
        content: &[u8],
        expected_provider_revision: Option<&str>,
        idempotency_key: &str,
    ) -> Result<ProviderWriteResult> {
        let _ = (
            external_id,
            path,
            content,
            expected_provider_revision,
            idempotency_key,
        );
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "sandbox does not support file writes",
        )
        .into())
    }
    async fn read_file(&self, external_id: &str, path: &str) -> Result<ProviderFileContent> {
        let _ = (external_id, path);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "sandbox does not support file reads",
        )
        .into())
    }
    async fn exec_command(
        &self,
        external_id: &str,
        command: &CommandSpec,
    ) -> Result<ProviderCommandOutput> {
        let _ = (external_id, command);
        Err(EnvironmentDomainError::new(
            EnvironmentErrorCode::CapabilityUnsupported,
            "sandbox does not support managed commands",
        )
        .into())
    }
    /// Set mode/owner/group on a Sandbox path through the Provider file API.
    async fn set_path_permissions(
        &self,
        external_id: &str,
        path: &str,
        mode: &str,
        owner: Option<&str>,
        group: Option<&str>,
    ) -> Result<()> {
        let _ = (external_id, path, mode, owner, group);
        Ok(())
    }
    async fn exec_managed_command(
        &self,
        external_id: &str,
        command_id: &str,
        command: &CommandSpec,
    ) -> Result<ProviderCommandOutput> {
        let _ = command_id;
        self.exec_command(external_id, command).await
    }
    async fn resume_managed_command(
        &self,
        external_id: &str,
        command_id: &str,
        command: &CommandSpec,
    ) -> Result<Option<ProviderCommandOutput>> {
        let _ = (external_id, command_id, command);
        Ok(None)
    }
    async fn retry_managed_command(
        &self,
        external_id: &str,
        command_id: &str,
        command: &CommandSpec,
    ) -> Result<Option<ProviderCommandOutput>> {
        self.resume_managed_command(external_id, command_id, command)
            .await
    }
    async fn cancel_command(&self, external_id: &str, command_id: &str) -> Result<()> {
        let _ = (external_id, command_id);
        Ok(())
    }
}

#[async_trait]
pub trait SpaceProvider: Send + Sync + Debug {
    fn kind(&self) -> &str;
    fn capabilities(&self) -> ProviderCapabilities;
    async fn create_space(
        &self,
        scope: &ResourceScope,
        request: &ProviderSpaceRequest,
        idempotency_key: &str,
    ) -> Result<ProviderResourceRef>;
    async fn read_file(&self, external_id: &str, path: &str) -> Result<ProviderFileContent>;
    async fn write_file(
        &self,
        external_id: &str,
        path: &str,
        content: &[u8],
        expected_provider_revision: Option<&str>,
        idempotency_key: &str,
    ) -> Result<ProviderWriteResult>;
    async fn create_change_set(
        &self,
        source_external_id: &str,
        target_external_id: &str,
        idempotency_key: &str,
    ) -> Result<String>;
    async fn apply_change_set(
        &self,
        source_external_id: &str,
        target_external_id: &str,
        provider_change_ref: &str,
        idempotency_key: &str,
    ) -> Result<ProviderWriteResult>;
    async fn delete_space(&self, external_id: &str, idempotency_key: &str) -> Result<()>;
}

#[async_trait]
pub trait SnapshotProviderPort: Send + Sync + Debug {
    fn kind(&self) -> &str;
    async fn capture_snapshot(
        &self,
        source: &ProviderSnapshotSource,
        idempotency_key: &str,
    ) -> Result<ProviderResourceRef>;
    async fn delete_snapshot(
        &self,
        snapshot_external_id: &str,
        idempotency_key: &str,
    ) -> Result<()>;
}

#[async_trait]
pub trait TemplateProviderPort: Send + Sync + Debug {
    fn kind(&self) -> &str;
    async fn inspect_template(&self, external_id: &str) -> Result<ProviderCapabilities>;
}

pub trait EnvironmentProviderRegistry: Send + Sync + Debug {
    fn computer(&self, provider: &str) -> Result<Arc<dyn ComputerProvider>>;
    fn sandbox(&self, provider: &str) -> Result<Arc<dyn SandboxProvider>>;
    fn space(&self, provider: &str) -> Result<Arc<dyn SpaceProvider>>;
    fn snapshot(&self, provider: &str) -> Result<Arc<dyn SnapshotProviderPort>>;
    fn template(&self, provider: &str) -> Result<Arc<dyn TemplateProviderPort>>;
}

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

    fn record(scope: &ResourceScope, id: &str, attempt: u32) -> EnvironmentIdempotencyRecord {
        EnvironmentIdempotencyRecord {
            id: id.into(),
            scope: scope.clone(),
            action: "test".into(),
            key_hash: format!("key-{id}"),
            request_hash: format!("request-{id}"),
            resource_id: None,
            state: EnvironmentIdempotencyState::Pending,
            claim_owner: "worker".into(),
            claim_expires_at_ms: 10,
            attempt,
            result_json: None,
            started_at_ms: 1,
            completed_at_ms: None,
        }
    }

    #[test]
    fn metadata_patch_contains_only_changed_deleted_and_new_aggregates() {
        let scope = ResourceScope {
            tenant_id: "tenant".into(),
            project_id: "project".into(),
        };
        let unchanged = record(&scope, "unchanged", 1);
        let changed = record(&scope, "changed", 1);
        let deleted = record(&scope, "deleted", 1);
        let before = EnvironmentMetadataSnapshot {
            version: 7,
            idempotency: vec![unchanged.clone(), changed, deleted],
            fencing_tokens: BTreeMap::from([
                ("unchanged-space".into(), 1),
                ("changed-space".into(), 1),
                ("deleted-space".into(), 1),
            ]),
            ..EnvironmentMetadataSnapshot::default()
        };
        let changed = record(&scope, "changed", 2);
        let added = record(&scope, "added", 1);
        let after = EnvironmentMetadataSnapshot {
            version: 8,
            idempotency: vec![unchanged, changed.clone(), added.clone()],
            fencing_tokens: BTreeMap::from([
                ("unchanged-space".into(), 1),
                ("changed-space".into(), 2),
                ("added-space".into(), 1),
            ]),
            ..EnvironmentMetadataSnapshot::default()
        };

        let patch = EnvironmentMetadataPatch::between(&before, &after);

        assert_eq!(patch.version, 8);
        assert_eq!(patch.idempotency.upserts, vec![added, changed]);
        assert_eq!(patch.idempotency.deletes, vec!["deleted"]);
        assert_eq!(
            patch.fencing_tokens.upserts,
            BTreeMap::from([("added-space".into(), 1), ("changed-space".into(), 2)])
        );
        assert_eq!(patch.fencing_tokens.deletes, vec!["deleted-space"]);
        assert_eq!(patch.changed_aggregate_count(), 6);
    }
}