brainwires-agents 0.8.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
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
//! Resource locking system for build/test/git coordination
//!
//! Provides exclusive locks for build, test, and git operations to prevent
//! concurrent operations that could interfere with each other.
//!
//! Key features:
//! - Liveness-based validation (no fixed timeouts)
//! - Integration with OperationTracker for heartbeat monitoring
//! - Git-specific resource types for fine-grained control
//! - Wait queue integration for coordinated access

use anyhow::{Result, anyhow};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{RwLock, broadcast};

use crate::operation_tracker::{OperationHandle, OperationTracker};
use crate::wait_queue::WaitQueue;

/// Type of resource lock
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ResourceType {
    /// Build lock - prevents concurrent builds
    Build,
    /// Test lock - prevents concurrent test runs
    Test,
    /// Combined build+test lock (for commands that do both)
    BuildTest,
    /// Git index/staging area operations
    GitIndex,
    /// Git commit operations
    GitCommit,
    /// Git remote write operations (push)
    GitRemoteWrite,
    /// Git remote merge operations (pull)
    GitRemoteMerge,
    /// Git branch operations (create, switch, delete)
    GitBranch,
    /// Git destructive operations (discard, reset)
    GitDestructive,
}

impl std::fmt::Display for ResourceType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResourceType::Build => write!(f, "Build"),
            ResourceType::Test => write!(f, "Test"),
            ResourceType::BuildTest => write!(f, "BuildTest"),
            ResourceType::GitIndex => write!(f, "GitIndex"),
            ResourceType::GitCommit => write!(f, "GitCommit"),
            ResourceType::GitRemoteWrite => write!(f, "GitRemoteWrite"),
            ResourceType::GitRemoteMerge => write!(f, "GitRemoteMerge"),
            ResourceType::GitBranch => write!(f, "GitBranch"),
            ResourceType::GitDestructive => write!(f, "GitDestructive"),
        }
    }
}

impl ResourceType {
    /// Check if this resource type conflicts with another
    pub fn conflicts_with(&self, other: &ResourceType) -> bool {
        use ResourceType::*;
        match (self, other) {
            // Same type always conflicts
            (a, b) if a == b => true,

            // BuildTest conflicts with both Build and Test
            (BuildTest, Build) | (Build, BuildTest) => true,
            (BuildTest, Test) | (Test, BuildTest) => true,

            // Git operations that modify index conflict with each other
            (GitIndex, GitCommit) | (GitCommit, GitIndex) => true,
            (GitIndex, GitRemoteMerge) | (GitRemoteMerge, GitIndex) => true,
            (GitIndex, GitDestructive) | (GitDestructive, GitIndex) => true,

            // Commit conflicts with destructive operations
            (GitCommit, GitDestructive) | (GitDestructive, GitCommit) => true,

            // Build/Test conflicts with git operations that change code
            (Build, GitRemoteMerge) | (GitRemoteMerge, Build) => true,
            (Test, GitRemoteMerge) | (GitRemoteMerge, Test) => true,
            (Build, GitDestructive) | (GitDestructive, Build) => true,
            (Test, GitDestructive) | (GitDestructive, Test) => true,

            _ => false,
        }
    }

    /// Check if this is a git-related resource type
    pub fn is_git(&self) -> bool {
        matches!(
            self,
            ResourceType::GitIndex
                | ResourceType::GitCommit
                | ResourceType::GitRemoteWrite
                | ResourceType::GitRemoteMerge
                | ResourceType::GitBranch
                | ResourceType::GitDestructive
        )
    }

    /// Check if this is a build/test resource type
    pub fn is_build_test(&self) -> bool {
        matches!(
            self,
            ResourceType::Build | ResourceType::Test | ResourceType::BuildTest
        )
    }
}

/// Scope of a resource lock
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ResourceScope {
    /// Global lock across all projects
    Global,
    /// Project-specific lock (based on project root path)
    Project(PathBuf),
}

impl std::fmt::Display for ResourceScope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ResourceScope::Global => write!(f, "Global"),
            ResourceScope::Project(path) => write!(f, "Project({})", path.display()),
        }
    }
}

/// Information about a held resource lock
#[derive(Debug, Clone)]
pub struct ResourceLockInfo {
    /// ID of the agent holding the lock
    pub agent_id: String,
    /// Type of resource locked
    pub resource_type: ResourceType,
    /// Scope of the lock
    pub scope: ResourceScope,
    /// When the lock was acquired
    pub acquired_at: Instant,
    /// Operation ID for liveness tracking (replaces timeout)
    pub operation_id: Option<String>,
    /// Description of the operation
    pub description: String,
    /// Current status message
    pub status: String,
}

impl ResourceLockInfo {
    /// Get elapsed time since lock was acquired
    pub fn elapsed(&self) -> Duration {
        self.acquired_at.elapsed()
    }
}

/// Key for resource lock storage
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ResourceKey {
    resource_type: ResourceType,
    scope: ResourceScope,
}

/// Guard that releases a resource lock when dropped
pub struct ResourceLockGuard {
    manager: Arc<ResourceLockManager>,
    agent_id: String,
    resource_type: ResourceType,
    scope: ResourceScope,
}

impl Drop for ResourceLockGuard {
    fn drop(&mut self) {
        let manager = self.manager.clone();
        let agent_id = self.agent_id.clone();
        let resource_type = self.resource_type;
        let scope = self.scope.clone();

        // Spawn a task to release the lock asynchronously
        tokio::spawn(async move {
            if let Err(e) = manager
                .release_resource_internal(&agent_id, resource_type, &scope)
                .await
            {
                eprintln!("Warning: Failed to release resource lock on drop: {}", e);
            }
        });
    }
}

/// Notification events for lock state changes
#[derive(Debug, Clone)]
pub enum LockNotification {
    /// Lock was acquired
    Acquired {
        /// Agent that acquired the lock.
        agent_id: String,
        /// Type of resource locked.
        resource_type: ResourceType,
        /// Scope of the lock.
        scope: ResourceScope,
    },
    /// Lock was released
    Released {
        /// Agent that released the lock.
        agent_id: String,
        /// Type of resource unlocked.
        resource_type: ResourceType,
        /// Scope of the lock.
        scope: ResourceScope,
    },
    /// Lock became stale (holder stopped sending heartbeats)
    Stale {
        /// Agent whose lock became stale.
        agent_id: String,
        /// Type of stale resource lock.
        resource_type: ResourceType,
        /// Scope of the stale lock.
        scope: ResourceScope,
    },
}

/// Manages resource locks (build/test/git) across multiple agents
///
/// Uses liveness-based validation instead of fixed timeouts:
/// - Integrates with OperationTracker for heartbeat monitoring
/// - Locks are valid as long as the holder is alive
/// - Supports wait queue for coordinated access
pub struct ResourceLockManager {
    /// Map of resource keys to their lock info
    locks: RwLock<HashMap<ResourceKey, ResourceLockInfo>>,
    /// Operation tracker for liveness checking
    operation_tracker: Option<Arc<OperationTracker>>,
    /// Wait queue for coordinated access
    wait_queue: Option<Arc<WaitQueue>>,
    /// Notification channel for lock events
    event_sender: broadcast::Sender<LockNotification>,
}

impl ResourceLockManager {
    /// Create a new resource lock manager
    pub fn new() -> Self {
        let (event_sender, _) = broadcast::channel(256);
        Self {
            locks: RwLock::new(HashMap::new()),
            operation_tracker: None,
            wait_queue: None,
            event_sender,
        }
    }

    /// Create a resource lock manager with operation tracker integration
    pub fn with_operation_tracker(operation_tracker: Arc<OperationTracker>) -> Self {
        let (event_sender, _) = broadcast::channel(256);
        Self {
            locks: RwLock::new(HashMap::new()),
            operation_tracker: Some(operation_tracker),
            wait_queue: None,
            event_sender,
        }
    }

    /// Create a fully integrated resource lock manager
    pub fn with_full_integration(
        operation_tracker: Arc<OperationTracker>,
        wait_queue: Arc<WaitQueue>,
    ) -> Self {
        let (event_sender, _) = broadcast::channel(256);
        Self {
            locks: RwLock::new(HashMap::new()),
            operation_tracker: Some(operation_tracker),
            wait_queue: Some(wait_queue),
            event_sender,
        }
    }

    /// Subscribe to lock notifications
    pub fn subscribe(&self) -> broadcast::Receiver<LockNotification> {
        self.event_sender.subscribe()
    }

    /// Get the operation tracker if configured
    pub fn operation_tracker(&self) -> Option<&Arc<OperationTracker>> {
        self.operation_tracker.as_ref()
    }

    /// Get the wait queue if configured
    pub fn wait_queue(&self) -> Option<&Arc<WaitQueue>> {
        self.wait_queue.as_ref()
    }

    /// Acquire a resource lock
    ///
    /// Returns a ResourceLockGuard that automatically releases the lock when dropped.
    pub async fn acquire_resource(
        self: &Arc<Self>,
        agent_id: &str,
        resource_type: ResourceType,
        scope: ResourceScope,
        description: &str,
    ) -> Result<ResourceLockGuard> {
        let mut locks = self.locks.write().await;

        // Clean up stale locks first (based on liveness)
        self.cleanup_stale_internal(&mut locks).await;

        let key = ResourceKey {
            resource_type,
            scope: scope.clone(),
        };

        // Check for existing lock
        if let Some(existing) = locks.get(&key) {
            if existing.agent_id != agent_id {
                // Check if the existing lock is still valid
                if self.is_lock_alive_internal(existing).await {
                    return Err(anyhow!(
                        "Resource {} ({}) is locked by agent {} ({})",
                        resource_type,
                        scope,
                        existing.agent_id,
                        existing.description
                    ));
                }
                // Lock holder is dead, remove and continue
                locks.remove(&key);
            } else {
                // Same agent already has the lock, return success (idempotent)
                return Ok(ResourceLockGuard {
                    manager: Arc::clone(self),
                    agent_id: agent_id.to_string(),
                    resource_type,
                    scope,
                });
            }
        }

        // Check for conflicting locks using the new conflict detection
        self.check_conflicts_internal(&locks, agent_id, resource_type, &scope)
            .await?;

        // Acquire the lock
        locks.insert(
            key,
            ResourceLockInfo {
                agent_id: agent_id.to_string(),
                resource_type,
                scope: scope.clone(),
                acquired_at: Instant::now(),
                operation_id: None,
                description: description.to_string(),
                status: "Starting".to_string(),
            },
        );

        // Send notification
        let _ = self.event_sender.send(LockNotification::Acquired {
            agent_id: agent_id.to_string(),
            resource_type,
            scope: scope.clone(),
        });

        Ok(ResourceLockGuard {
            manager: Arc::clone(self),
            agent_id: agent_id.to_string(),
            resource_type,
            scope,
        })
    }

    /// Acquire a resource lock with operation tracking
    ///
    /// This method creates an OperationHandle that:
    /// - Automatically sends heartbeats
    /// - Can have a process attached for liveness monitoring
    /// - Signals completion when dropped
    pub async fn acquire_with_operation(
        self: &Arc<Self>,
        agent_id: &str,
        resource_type: ResourceType,
        scope: ResourceScope,
        description: &str,
    ) -> Result<(ResourceLockGuard, Option<OperationHandle>)> {
        // First acquire the lock
        let guard = self
            .acquire_resource(agent_id, resource_type, scope.clone(), description)
            .await?;

        // If we have an operation tracker, start tracking the operation
        let operation_handle = if let Some(tracker) = &self.operation_tracker {
            let handle = tracker
                .start_operation(agent_id, resource_type, scope.clone(), description)
                .await?;

            // Update the lock with the operation ID
            let mut locks = self.locks.write().await;
            let key = ResourceKey {
                resource_type,
                scope: scope.clone(),
            };
            if let Some(lock_info) = locks.get_mut(&key) {
                lock_info.operation_id = Some(handle.operation_id().to_string());
            }

            Some(handle)
        } else {
            None
        };

        Ok((guard, operation_handle))
    }

    /// Check for conflicting locks
    async fn check_conflicts_internal(
        &self,
        locks: &HashMap<ResourceKey, ResourceLockInfo>,
        agent_id: &str,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Result<()> {
        // Check all existing locks for conflicts
        for (key, existing) in locks.iter() {
            if &key.scope != scope {
                continue; // Different scope, no conflict
            }
            if existing.agent_id == agent_id {
                continue; // Same agent, no conflict
            }
            if !self.is_lock_alive_internal(existing).await {
                continue; // Lock holder is dead, will be cleaned up
            }

            // Check if resource types conflict
            if resource_type.conflicts_with(&key.resource_type) {
                return Err(anyhow!(
                    "Cannot acquire {} lock: {} is locked by agent {} ({})",
                    resource_type,
                    key.resource_type,
                    existing.agent_id,
                    existing.description
                ));
            }
        }

        Ok(())
    }

    /// Check if a lock is still alive (holder is active)
    async fn is_lock_alive_internal(&self, lock_info: &ResourceLockInfo) -> bool {
        // If we have an operation tracker and the lock has an operation ID, check liveness
        if let (Some(tracker), Some(op_id)) = (&self.operation_tracker, &lock_info.operation_id) {
            return tracker.is_alive(op_id).await;
        }
        // Without operation tracking, assume lock is valid
        true
    }

    /// Clean up stale locks (holders that are no longer alive)
    async fn cleanup_stale_internal(
        &self,
        locks: &mut HashMap<ResourceKey, ResourceLockInfo>,
    ) -> usize {
        let mut stale_keys = Vec::new();

        for (key, info) in locks.iter() {
            if !self.is_lock_alive_internal(info).await {
                stale_keys.push(key.clone());
                let _ = self.event_sender.send(LockNotification::Stale {
                    agent_id: info.agent_id.clone(),
                    resource_type: info.resource_type,
                    scope: info.scope.clone(),
                });
            }
        }

        let count = stale_keys.len();
        for key in stale_keys {
            // Notify wait queue if configured
            if let Some(wait_queue) = &self.wait_queue {
                let resource_key = format!("{}:{}", key.resource_type, key.scope);
                let _ = wait_queue.notify_released(&resource_key).await;
            }
            locks.remove(&key);
        }

        count
    }

    /// Release a specific resource lock
    pub async fn release_resource(
        &self,
        agent_id: &str,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Result<()> {
        self.release_resource_internal(agent_id, resource_type, scope)
            .await
    }

    /// Internal release implementation
    async fn release_resource_internal(
        &self,
        agent_id: &str,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Result<()> {
        let mut locks = self.locks.write().await;

        let key = ResourceKey {
            resource_type,
            scope: scope.clone(),
        };

        if let Some(existing) = locks.get(&key) {
            if existing.agent_id == agent_id {
                locks.remove(&key);

                // Send notification
                let _ = self.event_sender.send(LockNotification::Released {
                    agent_id: agent_id.to_string(),
                    resource_type,
                    scope: scope.clone(),
                });

                // Notify wait queue if configured
                if let Some(wait_queue) = &self.wait_queue {
                    let resource_key = format!("{}:{}", resource_type, scope);
                    let _ = wait_queue.notify_released(&resource_key).await;
                }

                Ok(())
            } else {
                Err(anyhow!(
                    "Resource {} ({}) is locked by agent {}, not {}",
                    resource_type,
                    scope,
                    existing.agent_id,
                    agent_id
                ))
            }
        } else {
            Err(anyhow!(
                "No lock found for resource {} ({})",
                resource_type,
                scope
            ))
        }
    }

    /// Release all locks held by an agent
    pub async fn release_all_for_agent(&self, agent_id: &str) -> usize {
        let mut locks = self.locks.write().await;
        let original_len = locks.len();
        locks.retain(|_, info| info.agent_id != agent_id);
        original_len - locks.len()
    }

    /// Check if a resource can be acquired by an agent
    pub async fn can_acquire(
        &self,
        agent_id: &str,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> bool {
        let locks = self.locks.read().await;

        // Check all existing locks for conflicts
        for (key, existing) in locks.iter() {
            if &key.scope != scope {
                continue; // Different scope, no conflict
            }
            if existing.agent_id == agent_id {
                continue; // Same agent, no conflict
            }
            if !self.is_lock_alive_internal(existing).await {
                continue; // Lock holder is dead, will be cleaned up
            }

            // Check if resource types conflict
            if resource_type.conflicts_with(&key.resource_type) {
                return false;
            }
        }

        true
    }

    /// Get detailed information about what's blocking acquisition
    pub async fn get_blocking_locks(
        &self,
        agent_id: &str,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Vec<ResourceLockInfo> {
        let locks = self.locks.read().await;
        let mut blocking = Vec::new();

        for (key, existing) in locks.iter() {
            if &key.scope != scope {
                continue;
            }
            if existing.agent_id == agent_id {
                continue;
            }
            if !self.is_lock_alive_internal(existing).await {
                continue;
            }
            if resource_type.conflicts_with(&key.resource_type) {
                blocking.push(existing.clone());
            }
        }

        blocking
    }

    /// Query the detailed status of a lock
    pub async fn query_lock_status(
        &self,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Option<LockStatus> {
        let locks = self.locks.read().await;
        let key = ResourceKey {
            resource_type,
            scope: scope.clone(),
        };

        if let Some(info) = locks.get(&key) {
            let is_alive = self.is_lock_alive_internal(info).await;
            let operation_status = if let (Some(tracker), Some(op_id)) =
                (&self.operation_tracker, &info.operation_id)
            {
                tracker.get_status(op_id).await
            } else {
                None
            };

            Some(LockStatus {
                agent_id: info.agent_id.clone(),
                resource_type: info.resource_type,
                scope: info.scope.clone(),
                acquired_at_secs_ago: info.elapsed().as_secs(),
                is_alive,
                description: info.description.clone(),
                status: info.status.clone(),
                operation_id: info.operation_id.clone(),
                operation_status,
            })
        } else {
            None
        }
    }

    /// Check if a resource is currently locked
    pub async fn check_lock(
        &self,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Option<ResourceLockInfo> {
        let locks = self.locks.read().await;

        let key = ResourceKey {
            resource_type,
            scope: scope.clone(),
        };

        locks.get(&key).cloned()
    }

    /// Force release a lock (admin operation)
    pub async fn force_release(
        &self,
        resource_type: ResourceType,
        scope: &ResourceScope,
    ) -> Result<()> {
        let mut locks = self.locks.write().await;

        let key = ResourceKey {
            resource_type,
            scope: scope.clone(),
        };

        if locks.remove(&key).is_some() {
            Ok(())
        } else {
            Err(anyhow!(
                "No lock found for resource {} ({})",
                resource_type,
                scope
            ))
        }
    }

    /// Get all currently held locks
    pub async fn list_locks(&self) -> Vec<ResourceLockInfo> {
        let locks = self.locks.read().await;
        locks.values().cloned().collect()
    }

    /// Get locks held by a specific agent
    pub async fn locks_for_agent(&self, agent_id: &str) -> Vec<ResourceLockInfo> {
        let locks = self.locks.read().await;
        locks
            .values()
            .filter(|info| info.agent_id == agent_id)
            .cloned()
            .collect()
    }

    /// Clean up stale locks (public version)
    pub async fn cleanup_stale(&self) -> usize {
        let mut locks = self.locks.write().await;
        self.cleanup_stale_internal(&mut locks).await
    }

    /// Get statistics about current locks
    pub async fn stats(&self) -> ResourceLockStats {
        let locks = self.locks.read().await;

        let mut build_locks = 0;
        let mut test_locks = 0;
        let mut buildtest_locks = 0;
        let mut git_locks = 0;

        for info in locks.values() {
            match info.resource_type {
                ResourceType::Build => build_locks += 1,
                ResourceType::Test => test_locks += 1,
                ResourceType::BuildTest => buildtest_locks += 1,
                ResourceType::GitIndex
                | ResourceType::GitCommit
                | ResourceType::GitRemoteWrite
                | ResourceType::GitRemoteMerge
                | ResourceType::GitBranch
                | ResourceType::GitDestructive => git_locks += 1,
            }
        }

        ResourceLockStats {
            total_locks: locks.len(),
            build_locks,
            test_locks,
            buildtest_locks,
            git_locks,
        }
    }

    /// Update the status of a held lock
    pub async fn update_lock_status(
        &self,
        agent_id: &str,
        resource_type: ResourceType,
        scope: &ResourceScope,
        status: &str,
    ) -> Result<()> {
        let mut locks = self.locks.write().await;
        let key = ResourceKey {
            resource_type,
            scope: scope.clone(),
        };

        if let Some(info) = locks.get_mut(&key) {
            if info.agent_id == agent_id {
                info.status = status.to_string();
                Ok(())
            } else {
                Err(anyhow!(
                    "Lock is held by agent {}, not {}",
                    info.agent_id,
                    agent_id
                ))
            }
        } else {
            Err(anyhow!(
                "No lock found for resource {} ({})",
                resource_type,
                scope
            ))
        }
    }
}

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

/// Statistics about current resource locks
#[derive(Debug, Clone)]
pub struct ResourceLockStats {
    /// Total number of locks
    pub total_locks: usize,
    /// Number of build locks
    pub build_locks: usize,
    /// Number of test locks
    pub test_locks: usize,
    /// Number of build+test locks
    pub buildtest_locks: usize,
    /// Number of git-related locks
    pub git_locks: usize,
}

/// Detailed status of a lock (for querying)
#[derive(Debug, Clone)]
pub struct LockStatus {
    /// Agent holding the lock
    pub agent_id: String,
    /// Type of resource locked
    pub resource_type: ResourceType,
    /// Scope of the lock
    pub scope: ResourceScope,
    /// Seconds since lock was acquired
    pub acquired_at_secs_ago: u64,
    /// Whether the lock holder is still alive
    pub is_alive: bool,
    /// Description of the operation
    pub description: String,
    /// Current status message
    pub status: String,
    /// Operation ID if tracked
    pub operation_id: Option<String>,
    /// Detailed operation status if available
    pub operation_status: Option<super::operation_tracker::OperationStatus>,
}

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

    #[tokio::test]
    async fn test_acquire_build_lock() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let guard = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        assert!(
            manager
                .check_lock(ResourceType::Build, &scope)
                .await
                .is_some()
        );

        drop(guard);
        // Give the async drop task time to run
        tokio::time::sleep(Duration::from_millis(10)).await;

        assert!(
            manager
                .check_lock(ResourceType::Build, &scope)
                .await
                .is_none()
        );
    }

    #[tokio::test]
    async fn test_build_lock_blocks_other_agent() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        let result = manager
            .acquire_resource("agent-2", ResourceType::Build, scope.clone(), "cargo build")
            .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_same_agent_reacquire() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard1 = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        // Same agent can reacquire (idempotent)
        let _guard2 = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        assert!(
            manager
                .check_lock(ResourceType::Build, &scope)
                .await
                .is_some()
        );
    }

    #[tokio::test]
    async fn test_buildtest_blocks_build_and_test() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard = manager
            .acquire_resource(
                "agent-1",
                ResourceType::BuildTest,
                scope.clone(),
                "cargo build && cargo test",
            )
            .await
            .unwrap();

        // BuildTest should block Build
        let result = manager
            .acquire_resource("agent-2", ResourceType::Build, scope.clone(), "cargo build")
            .await;
        assert!(result.is_err());

        // BuildTest should block Test
        let result = manager
            .acquire_resource("agent-2", ResourceType::Test, scope.clone(), "cargo test")
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_build_blocks_buildtest() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        // Build should block BuildTest
        let result = manager
            .acquire_resource(
                "agent-2",
                ResourceType::BuildTest,
                scope.clone(),
                "cargo build && cargo test",
            )
            .await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_different_scopes_independent() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope1 = ResourceScope::Project(PathBuf::from("/test/project1"));
        let scope2 = ResourceScope::Project(PathBuf::from("/test/project2"));

        let _guard1 = manager
            .acquire_resource(
                "agent-1",
                ResourceType::Build,
                scope1.clone(),
                "cargo build",
            )
            .await
            .unwrap();

        // Different project should work
        let _guard2 = manager
            .acquire_resource(
                "agent-2",
                ResourceType::Build,
                scope2.clone(),
                "cargo build",
            )
            .await
            .unwrap();

        assert!(
            manager
                .check_lock(ResourceType::Build, &scope1)
                .await
                .is_some()
        );
        assert!(
            manager
                .check_lock(ResourceType::Build, &scope2)
                .await
                .is_some()
        );
    }

    #[tokio::test]
    async fn test_release_all_for_agent() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let guard1 = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();
        let guard2 = manager
            .acquire_resource("agent-1", ResourceType::Test, scope.clone(), "cargo test")
            .await
            .unwrap();

        // Forget guards to prevent auto-release
        std::mem::forget(guard1);
        std::mem::forget(guard2);

        let released = manager.release_all_for_agent("agent-1").await;
        assert_eq!(released, 2);

        assert!(
            manager
                .check_lock(ResourceType::Build, &scope)
                .await
                .is_none()
        );
        assert!(
            manager
                .check_lock(ResourceType::Test, &scope)
                .await
                .is_none()
        );
    }

    #[tokio::test]
    async fn test_can_acquire() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        // No locks - can acquire
        assert!(
            manager
                .can_acquire("agent-1", ResourceType::Build, &scope)
                .await
        );

        let _guard = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        // Same agent can acquire
        assert!(
            manager
                .can_acquire("agent-1", ResourceType::Build, &scope)
                .await
        );

        // Other agent cannot
        assert!(
            !manager
                .can_acquire("agent-2", ResourceType::Build, &scope)
                .await
        );
    }

    #[tokio::test]
    async fn test_stats() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard1 = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();
        let _guard2 = manager
            .acquire_resource(
                "agent-2",
                ResourceType::Test,
                ResourceScope::Global,
                "cargo test",
            )
            .await
            .unwrap();

        let stats = manager.stats().await;
        assert_eq!(stats.total_locks, 2);
        assert_eq!(stats.build_locks, 1);
        assert_eq!(stats.test_locks, 1);
        assert_eq!(stats.buildtest_locks, 0);
    }

    #[tokio::test]
    async fn test_git_resource_types() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        // GitIndex lock
        let _guard = manager
            .acquire_resource(
                "agent-1",
                ResourceType::GitIndex,
                scope.clone(),
                "git stage",
            )
            .await
            .unwrap();

        // GitCommit should conflict with GitIndex
        let result = manager
            .acquire_resource(
                "agent-2",
                ResourceType::GitCommit,
                scope.clone(),
                "git commit",
            )
            .await;
        assert!(result.is_err());

        // GitRemoteWrite should NOT conflict with GitIndex
        let _guard2 = manager
            .acquire_resource(
                "agent-2",
                ResourceType::GitRemoteWrite,
                scope.clone(),
                "git push",
            )
            .await
            .unwrap();

        let stats = manager.stats().await;
        assert_eq!(stats.git_locks, 2);
    }

    #[tokio::test]
    async fn test_resource_type_conflicts() {
        // Test the conflicts_with method
        assert!(ResourceType::Build.conflicts_with(&ResourceType::Build));
        assert!(ResourceType::Build.conflicts_with(&ResourceType::BuildTest));
        assert!(ResourceType::BuildTest.conflicts_with(&ResourceType::Build));
        assert!(ResourceType::BuildTest.conflicts_with(&ResourceType::Test));

        // Git conflicts
        assert!(ResourceType::GitIndex.conflicts_with(&ResourceType::GitCommit));
        assert!(ResourceType::GitIndex.conflicts_with(&ResourceType::GitRemoteMerge));
        assert!(ResourceType::GitIndex.conflicts_with(&ResourceType::GitDestructive));

        // Non-conflicts
        assert!(!ResourceType::Build.conflicts_with(&ResourceType::Test));
        assert!(!ResourceType::GitRemoteWrite.conflicts_with(&ResourceType::GitBranch));
    }

    #[tokio::test]
    async fn test_get_blocking_locks() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        let blocking = manager
            .get_blocking_locks("agent-2", ResourceType::BuildTest, &scope)
            .await;

        assert_eq!(blocking.len(), 1);
        assert_eq!(blocking[0].agent_id, "agent-1");
        assert_eq!(blocking[0].resource_type, ResourceType::Build);
    }

    #[tokio::test]
    async fn test_update_lock_status() {
        let manager = Arc::new(ResourceLockManager::new());
        let scope = ResourceScope::Project(PathBuf::from("/test/project"));

        let _guard = manager
            .acquire_resource("agent-1", ResourceType::Build, scope.clone(), "cargo build")
            .await
            .unwrap();

        // Update status
        manager
            .update_lock_status("agent-1", ResourceType::Build, &scope, "Compiling crate...")
            .await
            .unwrap();

        let lock = manager
            .check_lock(ResourceType::Build, &scope)
            .await
            .unwrap();
        assert_eq!(lock.status, "Compiling crate...");

        // Other agent cannot update
        let result = manager
            .update_lock_status("agent-2", ResourceType::Build, &scope, "Hacking...")
            .await;
        assert!(result.is_err());
    }
}