brainwires-agents 0.9.0

Agent orchestration, coordination, and lifecycle management for the Brainwires 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
//! Saga-Style Compensating Transactions
//!
//! Based on SagaLLM (arXiv:2503.11951), this module implements the Saga pattern
//! for multi-step operations. When an operation fails mid-way, compensation
//! actions are executed in reverse order to undo completed sub-operations.
//!
//! # Key Concepts
//!
//! - **CompensableOperation**: A trait for operations that can be undone
//! - **SagaExecutor**: Manages execution and compensation of operation sequences
//! - **Checkpoint**: Captures state before operations for rollback
//! - **CompensationReport**: Summary of compensation actions taken
//!
//! # Example
//!
//! ```ignore
//! let mut saga = SagaExecutor::new("agent-1", "edit-and-build");
//!
//! // Execute operations in sequence
//! saga.execute_step(Arc::new(FileEditOp { path, content })).await?;
//! saga.execute_step(Arc::new(GitStageOp { files })).await?;
//! saga.execute_step(Arc::new(BuildOp { project })).await?;
//!
//! // If any step fails, compensate all completed operations
//! if failed {
//!     let report = saga.compensate_all().await?;
//!     // Files restored, staging undone
//! }
//! ```

use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;

use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use tokio::sync::RwLock;

/// A compensable operation that can be undone
#[async_trait]
pub trait CompensableOperation: Send + Sync {
    /// Execute the forward operation
    async fn execute(&self) -> Result<OperationResult>;

    /// Compensate (undo) the operation
    async fn compensate(&self, result: &OperationResult) -> Result<()>;

    /// Get operation description for logging
    fn description(&self) -> String;

    /// Get the operation type (for categorization)
    fn operation_type(&self) -> SagaOperationType {
        SagaOperationType::Generic
    }
}

/// Result of an operation, needed for compensation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OperationResult {
    /// Unique identifier for this operation.
    pub operation_id: String,
    /// Whether the operation succeeded.
    pub success: bool,
    /// State captured before operation (for rollback)
    #[serde(skip)]
    pub checkpoint: Option<Checkpoint>,
    /// Metadata needed for compensation
    pub compensation_data: serde_json::Value,
    /// Output from the operation
    pub output: Option<String>,
}

impl OperationResult {
    /// Create a successful operation result.
    pub fn success(operation_id: impl Into<String>) -> Self {
        Self {
            operation_id: operation_id.into(),
            success: true,
            checkpoint: None,
            compensation_data: serde_json::Value::Null,
            output: None,
        }
    }

    /// Create a successful operation result with compensation data.
    pub fn success_with_data(operation_id: impl Into<String>, data: serde_json::Value) -> Self {
        Self {
            operation_id: operation_id.into(),
            success: true,
            checkpoint: None,
            compensation_data: data,
            output: None,
        }
    }

    /// Create a failed operation result.
    pub fn failure(operation_id: impl Into<String>) -> Self {
        Self {
            operation_id: operation_id.into(),
            success: false,
            checkpoint: None,
            compensation_data: serde_json::Value::Null,
            output: None,
        }
    }

    /// Attach a checkpoint for rollback.
    pub fn with_checkpoint(mut self, checkpoint: Checkpoint) -> Self {
        self.checkpoint = Some(checkpoint);
        self
    }

    /// Attach output text to the result.
    pub fn with_output(mut self, output: impl Into<String>) -> Self {
        self.output = Some(output.into());
        self
    }
}

/// Checkpoint for state restoration
#[derive(Debug, Clone)]
pub struct Checkpoint {
    /// Checkpoint identifier.
    pub id: String,
    /// When the checkpoint was created.
    pub timestamp: Instant,
    /// File states before modification
    pub file_states: Vec<FileState>,
    /// Git state before modification
    pub git_state: Option<GitCheckpoint>,
}

impl Checkpoint {
    /// Create a new checkpoint with the given identifier.
    pub fn new(id: impl Into<String>) -> Self {
        Self {
            id: id.into(),
            timestamp: Instant::now(),
            file_states: Vec::new(),
            git_state: None,
        }
    }

    /// Add a file state to the checkpoint.
    pub fn with_file(mut self, path: PathBuf, content: String) -> Self {
        self.file_states.push(FileState {
            path,
            content_hash: Self::hash_content(&content),
            original_content: Some(content),
        });
        self
    }

    /// Set all file states at once.
    pub fn with_files(mut self, files: Vec<FileState>) -> Self {
        self.file_states = files;
        self
    }

    /// Attach a git checkpoint.
    pub fn with_git(mut self, git_state: GitCheckpoint) -> Self {
        self.git_state = Some(git_state);
        self
    }

    fn hash_content(content: &str) -> String {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        content.hash(&mut hasher);
        format!("{:x}", hasher.finish())
    }
}

/// Snapshot of a file's state for restoration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileState {
    /// File path.
    pub path: PathBuf,
    /// Hash of the file content.
    pub content_hash: String,
    /// Original content for small files (for direct restoration)
    pub original_content: Option<String>,
}

impl FileState {
    /// Create a file state with path and content hash.
    pub fn new(path: PathBuf, content_hash: String) -> Self {
        Self {
            path,
            content_hash,
            original_content: None,
        }
    }

    /// Create a file state with path and full content (auto-hashed).
    pub fn with_content(path: PathBuf, content: String) -> Self {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let mut hasher = DefaultHasher::new();
        content.hash(&mut hasher);

        Self {
            path,
            content_hash: format!("{:x}", hasher.finish()),
            original_content: Some(content),
        }
    }
}

/// Snapshot of git state for restoration.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GitCheckpoint {
    /// HEAD commit hash.
    pub head_commit: String,
    /// List of staged files.
    pub staged_files: Vec<String>,
    /// Current branch name.
    pub branch: String,
}

impl GitCheckpoint {
    /// Create a new git checkpoint.
    pub fn new(head_commit: impl Into<String>, branch: impl Into<String>) -> Self {
        Self {
            head_commit: head_commit.into(),
            staged_files: Vec::new(),
            branch: branch.into(),
        }
    }

    /// Set staged files for this checkpoint.
    pub fn with_staged(mut self, files: Vec<String>) -> Self {
        self.staged_files = files;
        self
    }
}

/// Types of saga operations for categorization
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum SagaOperationType {
    /// File write operation
    FileWrite,
    /// File edit operation
    FileEdit,
    /// File delete operation
    FileDelete,
    /// Git staging operation
    GitStage,
    /// Git unstaging operation
    GitUnstage,
    /// Git commit operation
    GitCommit,
    /// Git branch creation
    GitBranchCreate,
    /// Git branch deletion
    GitBranchDelete,
    /// Build operation
    Build,
    /// Test operation
    Test,
    /// Generic operation
    Generic,
}

impl SagaOperationType {
    /// Returns true if this operation type can be compensated
    pub fn is_compensable(&self) -> bool {
        match self {
            SagaOperationType::FileWrite
            | SagaOperationType::FileEdit
            | SagaOperationType::FileDelete
            | SagaOperationType::GitStage
            | SagaOperationType::GitUnstage
            | SagaOperationType::GitCommit
            | SagaOperationType::GitBranchCreate
            | SagaOperationType::GitBranchDelete => true,
            // Build and test are idempotent, no compensation needed
            SagaOperationType::Build | SagaOperationType::Test | SagaOperationType::Generic => {
                false
            }
        }
    }

    /// Get the compensation description for this operation type
    pub fn compensation_description(&self) -> &'static str {
        match self {
            SagaOperationType::FileWrite => "Delete written file or restore from backup",
            SagaOperationType::FileEdit => "Restore original file content",
            SagaOperationType::FileDelete => "Restore deleted file",
            SagaOperationType::GitStage => "git reset HEAD <files>",
            SagaOperationType::GitUnstage => "git add <files>",
            SagaOperationType::GitCommit => "git reset --soft HEAD~1",
            SagaOperationType::GitBranchCreate => "git branch -d <branch>",
            SagaOperationType::GitBranchDelete => "Restore branch from reflog",
            SagaOperationType::Build => "No compensation (idempotent)",
            SagaOperationType::Test => "No compensation (idempotent)",
            SagaOperationType::Generic => "Custom compensation",
        }
    }
}

/// Saga executor that manages compensating transactions
pub struct SagaExecutor {
    /// Unique saga identifier
    pub saga_id: String,
    /// Agent executing this saga
    pub agent_id: String,
    /// Description of the saga's purpose
    pub description: String,
    /// When the saga started
    pub started_at: Instant,
    /// Completed operations in execution order
    completed_ops: RwLock<Vec<(Arc<dyn CompensableOperation>, OperationResult)>>,
    /// Compensation callbacks
    #[allow(clippy::type_complexity)]
    compensation_hooks: RwLock<Vec<Box<dyn Fn(&str, bool) + Send + Sync>>>,
    /// Current status
    status: RwLock<SagaStatus>,
}

/// Current status of a saga execution.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SagaStatus {
    /// Saga is in progress
    Running,
    /// Saga completed successfully
    Completed,
    /// Saga failed and compensation is needed
    Failed,
    /// Compensation is in progress
    Compensating,
    /// Compensation completed
    Compensated,
}

impl SagaExecutor {
    /// Create a new saga executor for the given agent and description.
    pub fn new(agent_id: impl Into<String>, description: impl Into<String>) -> Self {
        let agent_id = agent_id.into();
        let description = description.into();
        let saga_id = format!(
            "saga-{}-{}",
            agent_id,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system clock before UNIX epoch")
                .as_millis()
        );

        Self {
            saga_id,
            agent_id,
            description,
            started_at: Instant::now(),
            completed_ops: RwLock::new(Vec::new()),
            compensation_hooks: RwLock::new(Vec::new()),
            status: RwLock::new(SagaStatus::Running),
        }
    }

    /// Get current status
    pub async fn status(&self) -> SagaStatus {
        *self.status.read().await
    }

    /// Get number of completed operations
    pub async fn operation_count(&self) -> usize {
        self.completed_ops.read().await.len()
    }

    /// Execute an operation within the saga
    pub async fn execute_step(&self, op: Arc<dyn CompensableOperation>) -> Result<OperationResult> {
        // Check if saga is still running
        if *self.status.read().await != SagaStatus::Running {
            anyhow::bail!("Cannot execute step: saga is not running");
        }

        tracing::debug!(
            saga_id = %self.saga_id,
            operation = %op.description(),
            "Executing saga step"
        );

        let result = op.execute().await?;

        if result.success {
            self.completed_ops.write().await.push((op, result.clone()));
            tracing::debug!(
                saga_id = %self.saga_id,
                "Saga step completed successfully"
            );
        } else {
            *self.status.write().await = SagaStatus::Failed;
            tracing::warn!(
                saga_id = %self.saga_id,
                "Saga step failed"
            );
        }

        Ok(result)
    }

    /// Mark the saga as successfully completed
    pub async fn complete(&self) {
        *self.status.write().await = SagaStatus::Completed;
        tracing::info!(
            saga_id = %self.saga_id,
            operations = self.completed_ops.read().await.len(),
            "Saga completed successfully"
        );
    }

    /// Mark the saga as failed (triggers compensation need)
    pub async fn fail(&self) {
        *self.status.write().await = SagaStatus::Failed;
        tracing::warn!(
            saga_id = %self.saga_id,
            operations = self.completed_ops.read().await.len(),
            "Saga marked as failed"
        );
    }

    /// Compensate all completed operations in reverse order
    pub async fn compensate_all(&self) -> Result<CompensationReport> {
        *self.status.write().await = SagaStatus::Compensating;

        let mut report = CompensationReport::new(self.saga_id.clone());

        tracing::info!(
            saga_id = %self.saga_id,
            "Starting saga compensation"
        );

        // Pop operations in reverse order
        while let Some((op, result)) = self.completed_ops.write().await.pop() {
            let description = op.description();

            // Skip non-compensable operations
            if !op.operation_type().is_compensable() {
                tracing::debug!(
                    operation = %description,
                    "Skipping non-compensable operation"
                );
                report.add_skipped(&description, "Non-compensable operation type");
                continue;
            }

            tracing::debug!(
                operation = %description,
                "Compensating operation"
            );

            match op.compensate(&result).await {
                Ok(()) => {
                    report.add_success(&description);
                    tracing::debug!(
                        operation = %description,
                        "Compensation successful"
                    );
                }
                Err(e) => {
                    let error_msg = e.to_string();
                    report.add_failure(&description, error_msg.clone());
                    tracing::error!(
                        operation = %description,
                        error = %error_msg,
                        "Compensation failed"
                    );
                    // Continue compensating other operations even if one fails
                }
            }
        }

        *self.status.write().await = SagaStatus::Compensated;

        // Call compensation hooks
        let hooks = self.compensation_hooks.read().await;
        let summary = report.summary();
        let all_successful = report.all_successful();
        for hook in hooks.iter() {
            hook(&summary, all_successful);
        }

        tracing::info!(
            saga_id = %self.saga_id,
            summary = %summary,
            "Saga compensation completed"
        );

        Ok(report)
    }

    /// Add a hook called after compensation
    pub async fn on_compensation<F>(&self, hook: F)
    where
        F: Fn(&str, bool) + Send + Sync + 'static,
    {
        self.compensation_hooks.write().await.push(Box::new(hook));
    }

    /// Get descriptions of all completed operations
    pub async fn get_operation_descriptions(&self) -> Vec<String> {
        self.completed_ops
            .read()
            .await
            .iter()
            .map(|(op, _)| op.description())
            .collect()
    }
}

/// Report of compensation actions
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompensationReport {
    /// Saga this report belongs to.
    pub saga_id: String,
    /// Status of each compensation action.
    pub operations: Vec<CompensationStatus>,
    /// When compensation started (epoch millis).
    pub started_at: u64,
    /// When compensation finished (epoch millis).
    pub completed_at: Option<u64>,
}

impl CompensationReport {
    /// Create a new empty compensation report.
    pub fn new(saga_id: String) -> Self {
        Self {
            saga_id,
            operations: Vec::new(),
            started_at: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system clock before UNIX epoch")
                .as_millis() as u64,
            completed_at: None,
        }
    }

    /// Record a successful compensation action.
    pub fn add_success(&mut self, description: &str) {
        self.operations.push(CompensationStatus {
            description: description.to_string(),
            status: CompensationOutcome::Success,
            error: None,
        });
    }

    /// Record a failed compensation action.
    pub fn add_failure(&mut self, description: &str, error: String) {
        self.operations.push(CompensationStatus {
            description: description.to_string(),
            status: CompensationOutcome::Failed,
            error: Some(error),
        });
    }

    /// Record a skipped compensation action.
    pub fn add_skipped(&mut self, description: &str, reason: &str) {
        self.operations.push(CompensationStatus {
            description: description.to_string(),
            status: CompensationOutcome::Skipped,
            error: Some(reason.to_string()),
        });
    }

    /// Returns true if all compensations succeeded or were skipped.
    pub fn all_successful(&self) -> bool {
        self.operations.iter().all(|s| {
            matches!(
                s.status,
                CompensationOutcome::Success | CompensationOutcome::Skipped
            )
        })
    }

    /// Generate a human-readable summary of compensation outcomes.
    pub fn summary(&self) -> String {
        let successful = self
            .operations
            .iter()
            .filter(|s| s.status == CompensationOutcome::Success)
            .count();
        let failed = self
            .operations
            .iter()
            .filter(|s| s.status == CompensationOutcome::Failed)
            .count();
        let skipped = self
            .operations
            .iter()
            .filter(|s| s.status == CompensationOutcome::Skipped)
            .count();

        format!(
            "{} successful, {} failed, {} skipped (total: {})",
            successful,
            failed,
            skipped,
            self.operations.len()
        )
    }

    /// Mark the compensation report as completed with a timestamp.
    pub fn mark_completed(&mut self) {
        self.completed_at = Some(
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("system clock before UNIX epoch")
                .as_millis() as u64,
        );
    }
}

/// Status of a single compensation action.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompensationStatus {
    /// Description of the compensated operation.
    pub description: String,
    /// Outcome of the compensation attempt.
    pub status: CompensationOutcome,
    /// Error message if compensation failed.
    pub error: Option<String>,
}

/// Outcome of a compensation attempt.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompensationOutcome {
    /// Compensation succeeded.
    Success,
    /// Compensation failed.
    Failed,
    /// Compensation was skipped.
    Skipped,
}

// =============================================================================
// Common Compensable Operations
// =============================================================================

/// File write operation with compensation
pub struct FileWriteOp {
    /// Path to the file being written.
    pub path: PathBuf,
    /// Content to write.
    pub content: String,
    /// Whether this creates a new file or overwrites an existing one.
    pub is_new_file: bool,
}

#[async_trait]
impl CompensableOperation for FileWriteOp {
    async fn execute(&self) -> Result<OperationResult> {
        // Capture existing content if file exists
        let checkpoint = if self.path.exists() {
            let original_content = tokio::fs::read_to_string(&self.path).await?;
            Some(
                Checkpoint::new(format!("file-write-{}", self.path.display()))
                    .with_file(self.path.clone(), original_content),
            )
        } else {
            None
        };

        // Write new content
        tokio::fs::write(&self.path, &self.content).await?;

        let mut result = OperationResult::success_with_data(
            format!("file-write-{}", self.path.display()),
            serde_json::json!({
                "path": self.path.display().to_string(),
                "is_new_file": self.is_new_file,
            }),
        );

        if let Some(cp) = checkpoint {
            result = result.with_checkpoint(cp);
        }

        Ok(result)
    }

    async fn compensate(&self, result: &OperationResult) -> Result<()> {
        if self.is_new_file {
            // Delete the new file
            if self.path.exists() {
                tokio::fs::remove_file(&self.path).await?;
            }
        } else if let Some(checkpoint) = &result.checkpoint {
            // Restore original content
            if let Some(file_state) = checkpoint.file_states.first()
                && let Some(original_content) = &file_state.original_content
            {
                tokio::fs::write(&self.path, original_content).await?;
            }
        }
        Ok(())
    }

    fn description(&self) -> String {
        format!(
            "Write file: {} ({})",
            self.path.display(),
            if self.is_new_file { "new" } else { "existing" }
        )
    }

    fn operation_type(&self) -> SagaOperationType {
        SagaOperationType::FileWrite
    }
}

/// File edit operation with compensation
pub struct FileEditOp {
    /// Path to the file being edited.
    pub path: PathBuf,
    /// Original file content before edit.
    pub old_content: String,
    /// New file content after edit.
    pub new_content: String,
}

#[async_trait]
impl CompensableOperation for FileEditOp {
    async fn execute(&self) -> Result<OperationResult> {
        let checkpoint = Checkpoint::new(format!("file-edit-{}", self.path.display()))
            .with_file(self.path.clone(), self.old_content.clone());

        // Write new content
        tokio::fs::write(&self.path, &self.new_content).await?;

        Ok(
            OperationResult::success(format!("file-edit-{}", self.path.display()))
                .with_checkpoint(checkpoint),
        )
    }

    async fn compensate(&self, result: &OperationResult) -> Result<()> {
        if let Some(checkpoint) = &result.checkpoint
            && let Some(file_state) = checkpoint.file_states.first()
            && let Some(original_content) = &file_state.original_content
        {
            tokio::fs::write(&self.path, original_content).await?;
        }
        Ok(())
    }

    fn description(&self) -> String {
        format!("Edit file: {}", self.path.display())
    }

    fn operation_type(&self) -> SagaOperationType {
        SagaOperationType::FileEdit
    }
}

/// Git stage operation with compensation
pub struct GitStageOp {
    /// Files to stage.
    pub files: Vec<PathBuf>,
    /// Working directory for the git command.
    pub working_dir: PathBuf,
}

#[async_trait]
impl CompensableOperation for GitStageOp {
    async fn execute(&self) -> Result<OperationResult> {
        use tokio::process::Command;

        for file in &self.files {
            Command::new("git")
                .args(["add", &file.display().to_string()])
                .current_dir(&self.working_dir)
                .output()
                .await?;
        }

        Ok(OperationResult::success_with_data(
            "git-stage",
            serde_json::json!({
                "files": self.files.iter().map(|f| f.display().to_string()).collect::<Vec<_>>(),
            }),
        ))
    }

    async fn compensate(&self, _result: &OperationResult) -> Result<()> {
        use tokio::process::Command;

        for file in &self.files {
            Command::new("git")
                .args(["reset", "HEAD", &file.display().to_string()])
                .current_dir(&self.working_dir)
                .output()
                .await?;
        }
        Ok(())
    }

    fn description(&self) -> String {
        format!("Git stage: {} files", self.files.len())
    }

    fn operation_type(&self) -> SagaOperationType {
        SagaOperationType::GitStage
    }
}

/// Git commit operation with compensation
pub struct GitCommitOp {
    /// Commit message.
    pub message: String,
    /// Working directory for the git command.
    pub working_dir: PathBuf,
}

#[async_trait]
impl CompensableOperation for GitCommitOp {
    async fn execute(&self) -> Result<OperationResult> {
        use tokio::process::Command;

        // Get current HEAD before commit
        let head_output = Command::new("git")
            .args(["rev-parse", "HEAD"])
            .current_dir(&self.working_dir)
            .output()
            .await?;
        let previous_head = String::from_utf8_lossy(&head_output.stdout)
            .trim()
            .to_string();

        // Perform commit
        let output = Command::new("git")
            .args(["commit", "-m", &self.message])
            .current_dir(&self.working_dir)
            .output()
            .await?;

        if output.status.success() {
            Ok(OperationResult::success_with_data(
                "git-commit",
                serde_json::json!({
                    "previous_head": previous_head,
                    "message": self.message,
                }),
            ))
        } else {
            anyhow::bail!(
                "Git commit failed: {}",
                String::from_utf8_lossy(&output.stderr)
            )
        }
    }

    async fn compensate(&self, _result: &OperationResult) -> Result<()> {
        use tokio::process::Command;

        // Soft reset to undo the commit but keep changes staged
        Command::new("git")
            .args(["reset", "--soft", "HEAD~1"])
            .current_dir(&self.working_dir)
            .output()
            .await?;
        Ok(())
    }

    fn description(&self) -> String {
        format!("Git commit: {}", self.message)
    }

    fn operation_type(&self) -> SagaOperationType {
        SagaOperationType::GitCommit
    }
}

/// No-op compensable operation (for operations that don't need compensation)
pub struct NoOpCompensation {
    /// Description of the operation.
    pub description: String,
    /// Type of the operation.
    pub op_type: SagaOperationType,
}

#[async_trait]
impl CompensableOperation for NoOpCompensation {
    async fn execute(&self) -> Result<OperationResult> {
        Ok(OperationResult::success(&self.description))
    }

    async fn compensate(&self, _result: &OperationResult) -> Result<()> {
        // No compensation needed
        Ok(())
    }

    fn description(&self) -> String {
        self.description.clone()
    }

    fn operation_type(&self) -> SagaOperationType {
        self.op_type
    }
}

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

    #[tokio::test]
    async fn test_saga_executor_basic() {
        let saga = SagaExecutor::new("test-agent", "test saga");

        assert_eq!(saga.status().await, SagaStatus::Running);
        assert_eq!(saga.operation_count().await, 0);
    }

    #[tokio::test]
    async fn test_saga_execute_and_complete() {
        let saga = SagaExecutor::new("test-agent", "test saga");

        let op = Arc::new(NoOpCompensation {
            description: "test op".to_string(),
            op_type: SagaOperationType::Generic,
        });

        let result = saga.execute_step(op).await.unwrap();
        assert!(result.success);

        saga.complete().await;
        assert_eq!(saga.status().await, SagaStatus::Completed);
    }

    #[tokio::test]
    async fn test_saga_compensation() {
        let saga = SagaExecutor::new("test-agent", "test saga");

        // Execute a compensable operation
        let op = Arc::new(NoOpCompensation {
            description: "compensable op".to_string(),
            op_type: SagaOperationType::FileWrite,
        });

        saga.execute_step(op).await.unwrap();

        // Trigger compensation
        saga.fail().await;
        let report = saga.compensate_all().await.unwrap();

        assert_eq!(saga.status().await, SagaStatus::Compensated);
        assert_eq!(report.operations.len(), 1);
    }

    #[tokio::test]
    async fn test_file_write_op_compensation() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("test.txt");

        // Create initial file
        std::fs::write(&file_path, "original content").unwrap();

        // Create file write operation
        let op = FileWriteOp {
            path: file_path.clone(),
            content: "new content".to_string(),
            is_new_file: false,
        };

        // Execute
        let result = op.execute().await.unwrap();
        assert!(result.success);

        // Verify new content
        let content = std::fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "new content");

        // Compensate
        op.compensate(&result).await.unwrap();

        // Verify original content restored
        let content = std::fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "original content");
    }

    #[tokio::test]
    async fn test_file_write_new_file_compensation() {
        let dir = tempdir().unwrap();
        let file_path = dir.path().join("new_file.txt");

        // Create file write operation for new file
        let op = FileWriteOp {
            path: file_path.clone(),
            content: "new content".to_string(),
            is_new_file: true,
        };

        // Execute
        let result = op.execute().await.unwrap();
        assert!(result.success);
        assert!(file_path.exists());

        // Compensate (should delete the file)
        op.compensate(&result).await.unwrap();
        assert!(!file_path.exists());
    }

    #[tokio::test]
    async fn test_compensation_report() {
        let mut report = CompensationReport::new("test-saga".to_string());

        report.add_success("op1");
        report.add_failure("op2", "error".to_string());
        report.add_skipped("op3", "non-compensable");

        assert!(!report.all_successful());
        assert!(report.summary().contains("1 successful"));
        assert!(report.summary().contains("1 failed"));
        assert!(report.summary().contains("1 skipped"));
    }

    #[tokio::test]
    async fn test_operation_type_compensable() {
        assert!(SagaOperationType::FileWrite.is_compensable());
        assert!(SagaOperationType::FileEdit.is_compensable());
        assert!(SagaOperationType::GitStage.is_compensable());
        assert!(SagaOperationType::GitCommit.is_compensable());

        assert!(!SagaOperationType::Build.is_compensable());
        assert!(!SagaOperationType::Test.is_compensable());
        assert!(!SagaOperationType::Generic.is_compensable());
    }

    #[tokio::test]
    async fn test_checkpoint_creation() {
        let checkpoint = Checkpoint::new("test-cp")
            .with_file(PathBuf::from("/test/file.txt"), "content".to_string());

        assert_eq!(checkpoint.id, "test-cp");
        assert_eq!(checkpoint.file_states.len(), 1);
        assert_eq!(
            checkpoint.file_states[0].path,
            PathBuf::from("/test/file.txt")
        );
        assert!(checkpoint.file_states[0].original_content.is_some());
    }
}