brainwires-agents 0.7.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
//! Cross-resource conflict detection
//!
//! Provides bidirectional checking between file locks and resource locks:
//! - Builds should wait if source files are being edited
//! - File writes should wait if build/test is in progress
//!
//! This ensures consistency and prevents race conditions between
//! file editing and build/test operations.

use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

use crate::communication::{ConflictInfo, ConflictType};
use crate::file_locks::{FileLockManager, LockType};
use crate::operation_tracker::OperationTracker;
use crate::resource_locks::{ResourceLockManager, ResourceScope, ResourceType};

/// Result of checking for conflicts before an operation
#[derive(Debug, Clone)]
pub enum ConflictCheck {
    /// No conflicts, operation can proceed
    Clear,
    /// Operation is blocked by active conflicts - must wait
    Blocked(Vec<Conflict>),
    /// Conflicts exist but are warnings only - can proceed with caution
    Warning(Vec<Conflict>),
}

impl ConflictCheck {
    /// Returns true if the operation can proceed (Clear or Warning)
    pub fn can_proceed(&self) -> bool {
        matches!(self, ConflictCheck::Clear | ConflictCheck::Warning(_))
    }

    /// Returns true if the operation is blocked
    pub fn is_blocked(&self) -> bool {
        matches!(self, ConflictCheck::Blocked(_))
    }

    /// Get all conflicts (blocking or warning)
    pub fn conflicts(&self) -> &[Conflict] {
        match self {
            ConflictCheck::Clear => &[],
            ConflictCheck::Blocked(c) | ConflictCheck::Warning(c) => c,
        }
    }
}

/// Information about a detected conflict
#[derive(Debug, Clone)]
pub struct Conflict {
    /// Type of conflict
    pub conflict_type: ResourceConflictType,
    /// Agent holding the conflicting resource
    pub holder_agent: String,
    /// Resource identifier (path or scope description)
    pub resource: String,
    /// When the conflict started
    pub started_at: Instant,
    /// Current status of the blocking operation
    pub status: String,
    /// Description of what the holder is doing
    pub description: String,
}

impl Conflict {
    /// Convert to the communication ConflictInfo type for messaging
    pub fn to_conflict_info(&self) -> ConflictInfo {
        ConflictInfo {
            conflict_type: match &self.conflict_type {
                ResourceConflictType::FileWriteBlocksBuild { path } => {
                    ConflictType::FileWriteBlocksBuild { path: path.clone() }
                }
                ResourceConflictType::BuildBlocksFileWrite => ConflictType::BuildBlocksFileWrite,
                ResourceConflictType::TestBlocksFileWrite => ConflictType::TestBlocksFileWrite,
                ResourceConflictType::GitBlocksFileWrite => ConflictType::GitBlocksFileWrite,
                ResourceConflictType::FileWriteBlocksGit { path } => {
                    ConflictType::FileWriteBlocksGit { path: path.clone() }
                }
                ResourceConflictType::BuildBlocksGit => ConflictType::BuildBlocksGit,
            },
            holder_agent: self.holder_agent.clone(),
            resource: self.resource.clone(),
            duration_secs: self.started_at.elapsed().as_secs(),
            status: self.status.clone(),
        }
    }
}

/// Types of cross-resource conflicts
#[derive(Debug, Clone)]
pub enum ResourceConflictType {
    /// File write lock blocks a build operation
    FileWriteBlocksBuild {
        /// Path of the locked file.
        path: PathBuf,
    },
    /// Build in progress blocks file write
    BuildBlocksFileWrite,
    /// Test in progress blocks file write
    TestBlocksFileWrite,
    /// Git operation blocks file write
    GitBlocksFileWrite,
    /// File write lock blocks git operation
    FileWriteBlocksGit {
        /// Path of the locked file.
        path: PathBuf,
    },
    /// Build in progress blocks git operation
    BuildBlocksGit,
}

/// Proposed operation to check for conflicts
#[derive(Debug, Clone)]
pub enum ProposedOperation {
    /// File write operation
    FileWrite {
        /// Path of the file to write.
        path: PathBuf,
        /// Agent performing the write.
        agent_id: String,
    },
    /// Build operation
    Build {
        /// Scope of the build.
        scope: ResourceScope,
        /// Agent performing the build.
        agent_id: String,
    },
    /// Test operation
    Test {
        /// Scope of the test.
        scope: ResourceScope,
        /// Agent performing the test.
        agent_id: String,
    },
    /// Git staging operation
    GitStaging {
        /// Scope of the staging operation.
        scope: ResourceScope,
        /// Agent performing the staging.
        agent_id: String,
    },
    /// Git commit operation
    GitCommit {
        /// Scope of the commit operation.
        scope: ResourceScope,
        /// Agent performing the commit.
        agent_id: String,
    },
    /// Git push operation
    GitPush {
        /// Scope of the push operation.
        scope: ResourceScope,
        /// Agent performing the push.
        agent_id: String,
    },
    /// Git pull operation
    GitPull {
        /// Scope of the pull operation.
        scope: ResourceScope,
        /// Agent performing the pull.
        agent_id: String,
    },
}

impl ProposedOperation {
    /// Get the agent ID for this proposed operation.
    pub fn agent_id(&self) -> &str {
        match self {
            ProposedOperation::FileWrite { agent_id, .. }
            | ProposedOperation::Build { agent_id, .. }
            | ProposedOperation::Test { agent_id, .. }
            | ProposedOperation::GitStaging { agent_id, .. }
            | ProposedOperation::GitCommit { agent_id, .. }
            | ProposedOperation::GitPush { agent_id, .. }
            | ProposedOperation::GitPull { agent_id, .. } => agent_id,
        }
    }
}

/// Cross-resource conflict checker
///
/// Checks for conflicts between:
/// - File locks and build/test operations
/// - Build/test operations and file writes
/// - Git operations and file/build operations
pub struct ResourceChecker {
    file_locks: Arc<FileLockManager>,
    resource_locks: Arc<ResourceLockManager>,
    _operation_tracker: Option<Arc<OperationTracker>>,
    /// File patterns to check for build conflicts (e.g., "src/**/*.rs")
    source_patterns: Vec<String>,
}

impl ResourceChecker {
    /// Create a new resource checker
    pub fn new(file_locks: Arc<FileLockManager>, resource_locks: Arc<ResourceLockManager>) -> Self {
        Self {
            file_locks,
            resource_locks,
            _operation_tracker: None,
            source_patterns: default_source_patterns(),
        }
    }

    /// Create a resource checker with operation tracker integration
    pub fn with_operation_tracker(
        file_locks: Arc<FileLockManager>,
        resource_locks: Arc<ResourceLockManager>,
        operation_tracker: Arc<OperationTracker>,
    ) -> Self {
        Self {
            file_locks,
            resource_locks,
            _operation_tracker: Some(operation_tracker),
            source_patterns: default_source_patterns(),
        }
    }

    /// Set custom source file patterns for build conflict detection
    pub fn with_source_patterns(mut self, patterns: Vec<String>) -> Self {
        self.source_patterns = patterns;
        self
    }

    /// Check if a build can start (no active file write locks in project)
    ///
    /// Returns `Clear` if no source files are being edited,
    /// or `Blocked` with details of which files are locked.
    pub async fn can_start_build(&self, scope: &ResourceScope, agent_id: &str) -> ConflictCheck {
        let file_locks = self.file_locks.list_locks().await;

        let mut conflicts = Vec::new();

        for (path, lock_info) in file_locks {
            // Skip if same agent
            if lock_info.agent_id == agent_id {
                continue;
            }

            // Only check write locks
            if lock_info.lock_type != LockType::Write {
                continue;
            }

            // Check if this file is within the scope and is a source file
            if self.is_in_scope(&path, scope) && self.is_source_file(&path) {
                conflicts.push(Conflict {
                    conflict_type: ResourceConflictType::FileWriteBlocksBuild {
                        path: path.clone(),
                    },
                    holder_agent: lock_info.agent_id.clone(),
                    resource: path.display().to_string(),
                    started_at: lock_info.acquired_at,
                    status: "File locked for editing".to_string(),
                    description: format!("Write lock on {}", path.display()),
                });
            }
        }

        if conflicts.is_empty() {
            ConflictCheck::Clear
        } else {
            ConflictCheck::Blocked(conflicts)
        }
    }

    /// Check if a file can be written (no active build/test in project)
    ///
    /// Returns `Clear` if no build/test is running,
    /// or `Blocked` with details of the blocking operation.
    pub async fn can_write_file(&self, path: &Path, agent_id: &str) -> ConflictCheck {
        let resource_locks = self.resource_locks.list_locks().await;

        let mut conflicts = Vec::new();

        // Determine the scope from the file path
        let file_scope = self.scope_for_path(path);

        for lock_info in resource_locks {
            // Skip if same agent
            if lock_info.agent_id == agent_id {
                continue;
            }

            // Check if the lock scope overlaps with the file's scope
            if !self.scopes_overlap(&lock_info.scope, &file_scope) {
                continue;
            }

            // Only source files are affected by builds/tests
            if !self.is_source_file(path) {
                continue;
            }

            // Check for build/test conflicts
            match lock_info.resource_type {
                ResourceType::Build | ResourceType::BuildTest => {
                    conflicts.push(Conflict {
                        conflict_type: ResourceConflictType::BuildBlocksFileWrite,
                        holder_agent: lock_info.agent_id.clone(),
                        resource: format!("{} ({})", lock_info.resource_type, lock_info.scope),
                        started_at: lock_info.acquired_at,
                        status: lock_info.status.clone(),
                        description: lock_info.description.clone(),
                    });
                }
                ResourceType::Test => {
                    conflicts.push(Conflict {
                        conflict_type: ResourceConflictType::TestBlocksFileWrite,
                        holder_agent: lock_info.agent_id.clone(),
                        resource: format!("{} ({})", lock_info.resource_type, lock_info.scope),
                        started_at: lock_info.acquired_at,
                        status: lock_info.status.clone(),
                        description: lock_info.description.clone(),
                    });
                }
                ResourceType::GitIndex
                | ResourceType::GitCommit
                | ResourceType::GitRemoteWrite
                | ResourceType::GitRemoteMerge
                | ResourceType::GitBranch
                | ResourceType::GitDestructive => {
                    // Git operations that modify the working tree block file writes
                    if lock_info.resource_type == ResourceType::GitRemoteMerge
                        || lock_info.resource_type == ResourceType::GitDestructive
                    {
                        conflicts.push(Conflict {
                            conflict_type: ResourceConflictType::GitBlocksFileWrite,
                            holder_agent: lock_info.agent_id.clone(),
                            resource: format!("{} ({})", lock_info.resource_type, lock_info.scope),
                            started_at: lock_info.acquired_at,
                            status: lock_info.status.clone(),
                            description: lock_info.description.clone(),
                        });
                    }
                }
            }
        }

        if conflicts.is_empty() {
            ConflictCheck::Clear
        } else {
            ConflictCheck::Blocked(conflicts)
        }
    }

    /// Check if a git operation can start
    ///
    /// Git operations are blocked by:
    /// - Active file write locks (for operations that read working tree)
    /// - Active builds (for commit/push operations)
    pub async fn can_start_git_operation(
        &self,
        git_op: ResourceType,
        scope: &ResourceScope,
        agent_id: &str,
    ) -> ConflictCheck {
        let mut conflicts = Vec::new();

        // Check file locks for git operations that read the working tree
        if matches!(
            git_op,
            ResourceType::GitIndex | ResourceType::GitCommit | ResourceType::GitRemoteWrite
        ) {
            let file_locks = self.file_locks.list_locks().await;

            for (path, lock_info) in file_locks {
                if lock_info.agent_id == agent_id {
                    continue;
                }
                if lock_info.lock_type != LockType::Write {
                    continue;
                }
                if self.is_in_scope(&path, scope) && self.is_source_file(&path) {
                    conflicts.push(Conflict {
                        conflict_type: ResourceConflictType::FileWriteBlocksGit {
                            path: path.clone(),
                        },
                        holder_agent: lock_info.agent_id.clone(),
                        resource: path.display().to_string(),
                        started_at: lock_info.acquired_at,
                        status: "File locked for editing".to_string(),
                        description: format!("Write lock on {}", path.display()),
                    });
                }
            }
        }

        // Check for build conflicts for commit/push operations
        if matches!(
            git_op,
            ResourceType::GitCommit | ResourceType::GitRemoteWrite
        ) {
            let resource_locks = self.resource_locks.list_locks().await;

            for lock_info in resource_locks {
                if lock_info.agent_id == agent_id {
                    continue;
                }
                if !self.scopes_overlap(&lock_info.scope, scope) {
                    continue;
                }

                if matches!(
                    lock_info.resource_type,
                    ResourceType::Build | ResourceType::Test | ResourceType::BuildTest
                ) {
                    conflicts.push(Conflict {
                        conflict_type: ResourceConflictType::BuildBlocksGit,
                        holder_agent: lock_info.agent_id.clone(),
                        resource: format!("{} ({})", lock_info.resource_type, lock_info.scope),
                        started_at: lock_info.acquired_at,
                        status: lock_info.status.clone(),
                        description: lock_info.description.clone(),
                    });
                }
            }
        }

        if conflicts.is_empty() {
            ConflictCheck::Clear
        } else {
            ConflictCheck::Blocked(conflicts)
        }
    }

    /// Check all conflicts for a proposed operation
    pub async fn check_conflicts(&self, operation: &ProposedOperation) -> ConflictCheck {
        match operation {
            ProposedOperation::FileWrite { path, agent_id } => {
                self.can_write_file(path, agent_id).await
            }
            ProposedOperation::Build { scope, agent_id } => {
                self.can_start_build(scope, agent_id).await
            }
            ProposedOperation::Test { scope, agent_id } => {
                // Same checks as build
                self.can_start_build(scope, agent_id).await
            }
            ProposedOperation::GitStaging { scope, agent_id } => {
                self.can_start_git_operation(ResourceType::GitIndex, scope, agent_id)
                    .await
            }
            ProposedOperation::GitCommit { scope, agent_id } => {
                self.can_start_git_operation(ResourceType::GitCommit, scope, agent_id)
                    .await
            }
            ProposedOperation::GitPush { scope, agent_id } => {
                self.can_start_git_operation(ResourceType::GitRemoteWrite, scope, agent_id)
                    .await
            }
            ProposedOperation::GitPull { scope, agent_id } => {
                self.can_start_git_operation(ResourceType::GitRemoteMerge, scope, agent_id)
                    .await
            }
        }
    }

    /// Get all current conflicts that would block a build
    pub async fn get_build_blockers(&self, scope: &ResourceScope, agent_id: &str) -> Vec<Conflict> {
        match self.can_start_build(scope, agent_id).await {
            ConflictCheck::Blocked(conflicts) => conflicts,
            _ => Vec::new(),
        }
    }

    /// Get all current conflicts that would block a file write
    pub async fn get_file_write_blockers(&self, path: &Path, agent_id: &str) -> Vec<Conflict> {
        match self.can_write_file(path, agent_id).await {
            ConflictCheck::Blocked(conflicts) => conflicts,
            _ => Vec::new(),
        }
    }

    // === Helper methods ===

    /// Check if a path is within a resource scope
    fn is_in_scope(&self, path: &Path, scope: &ResourceScope) -> bool {
        match scope {
            ResourceScope::Global => true,
            ResourceScope::Project(project_path) => path.starts_with(project_path),
        }
    }

    /// Determine the scope for a file path
    fn scope_for_path(&self, path: &Path) -> ResourceScope {
        // Try to find the project root by looking for common markers
        let mut current = path.parent();
        while let Some(dir) = current {
            if dir.join("Cargo.toml").exists()
                || dir.join("package.json").exists()
                || dir.join(".git").exists()
            {
                return ResourceScope::Project(dir.to_path_buf());
            }
            current = dir.parent();
        }
        ResourceScope::Global
    }

    /// Check if two scopes overlap
    fn scopes_overlap(&self, scope1: &ResourceScope, scope2: &ResourceScope) -> bool {
        match (scope1, scope2) {
            (ResourceScope::Global, _) | (_, ResourceScope::Global) => true,
            (ResourceScope::Project(p1), ResourceScope::Project(p2)) => {
                p1.starts_with(p2) || p2.starts_with(p1)
            }
        }
    }

    /// Check if a file is a source file that should block builds
    fn is_source_file(&self, path: &Path) -> bool {
        let path_str = path.to_string_lossy();

        // Check against source patterns
        for pattern in &self.source_patterns {
            if matches_pattern(&path_str, pattern) {
                return true;
            }
        }

        // Default: check common source extensions
        if let Some(ext) = path.extension() {
            let ext = ext.to_string_lossy().to_lowercase();
            matches!(
                ext.as_str(),
                "rs" | "ts"
                    | "tsx"
                    | "js"
                    | "jsx"
                    | "py"
                    | "go"
                    | "java"
                    | "c"
                    | "cpp"
                    | "h"
                    | "hpp"
                    | "cs"
                    | "swift"
                    | "kt"
                    | "scala"
                    | "rb"
                    | "php"
            )
        } else {
            false
        }
    }
}

/// Default source file patterns for build conflict detection
fn default_source_patterns() -> Vec<String> {
    vec![
        "src/**/*".to_string(),
        "lib/**/*".to_string(),
        "crates/**/*".to_string(),
        "packages/**/*".to_string(),
        "app/**/*".to_string(),
    ]
}

/// Simple glob-style pattern matching
fn matches_pattern(path: &str, pattern: &str) -> bool {
    if pattern.contains("**") {
        // Handle ** (match any depth)
        let parts: Vec<&str> = pattern.split("**").collect();
        if parts.len() == 2 {
            let prefix = parts[0].trim_end_matches('/');
            let suffix = parts[1].trim_start_matches('/');

            let has_prefix = prefix.is_empty() || path.starts_with(prefix);
            let has_suffix = suffix.is_empty()
                || suffix == "*"
                || path.ends_with(suffix.trim_start_matches('*'));

            return has_prefix && has_suffix;
        }
    }

    if pattern.contains('*') {
        // Handle single * (match within directory)
        let parts: Vec<&str> = pattern.split('*').collect();
        if parts.len() == 2 {
            return path.starts_with(parts[0]) && path.ends_with(parts[1]);
        }
    }

    // Exact match
    path == pattern
}

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

    #[test]
    fn test_matches_pattern() {
        assert!(matches_pattern("src/main.rs", "src/**/*"));
        assert!(matches_pattern("src/lib/utils.rs", "src/**/*"));
        assert!(matches_pattern("crates/foo/src/lib.rs", "crates/**/*"));
        assert!(!matches_pattern("target/debug/main", "src/**/*"));
    }

    #[test]
    fn test_is_source_file() {
        let checker = ResourceChecker::new(
            Arc::new(FileLockManager::new()),
            Arc::new(ResourceLockManager::new()),
        );

        assert!(checker.is_source_file(Path::new("src/main.rs")));
        assert!(checker.is_source_file(Path::new("lib/index.ts")));
        assert!(checker.is_source_file(Path::new("app.py")));
        assert!(!checker.is_source_file(Path::new("README.md")));
        assert!(!checker.is_source_file(Path::new("Cargo.toml")));
    }

    #[test]
    fn test_scopes_overlap() {
        let checker = ResourceChecker::new(
            Arc::new(FileLockManager::new()),
            Arc::new(ResourceLockManager::new()),
        );

        // Global overlaps with everything
        assert!(checker.scopes_overlap(&ResourceScope::Global, &ResourceScope::Global));
        assert!(checker.scopes_overlap(
            &ResourceScope::Global,
            &ResourceScope::Project(PathBuf::from("/foo"))
        ));

        // Project scopes
        assert!(checker.scopes_overlap(
            &ResourceScope::Project(PathBuf::from("/foo")),
            &ResourceScope::Project(PathBuf::from("/foo"))
        ));
        assert!(checker.scopes_overlap(
            &ResourceScope::Project(PathBuf::from("/foo")),
            &ResourceScope::Project(PathBuf::from("/foo/bar"))
        ));
        assert!(!checker.scopes_overlap(
            &ResourceScope::Project(PathBuf::from("/foo")),
            &ResourceScope::Project(PathBuf::from("/baz"))
        ));
    }

    #[tokio::test]
    async fn test_can_start_build_no_conflicts() {
        let file_locks = Arc::new(FileLockManager::new());
        let resource_locks = Arc::new(ResourceLockManager::new());
        let checker = ResourceChecker::new(file_locks, resource_locks);

        let scope = ResourceScope::Project(PathBuf::from("/test/project"));
        let result = checker.can_start_build(&scope, "agent-1").await;

        assert!(matches!(result, ConflictCheck::Clear));
    }

    #[tokio::test]
    async fn test_can_write_file_no_conflicts() {
        let file_locks = Arc::new(FileLockManager::new());
        let resource_locks = Arc::new(ResourceLockManager::new());
        let checker = ResourceChecker::new(file_locks, resource_locks);

        let result = checker
            .can_write_file(Path::new("/test/project/src/main.rs"), "agent-1")
            .await;

        assert!(matches!(result, ConflictCheck::Clear));
    }

    #[tokio::test]
    async fn test_build_blocked_by_file_write() {
        let file_locks = Arc::new(FileLockManager::new());
        let resource_locks = Arc::new(ResourceLockManager::new());

        // Agent 2 acquires a write lock on a source file
        file_locks
            .acquire_lock("agent-2", "/test/project/src/main.rs", LockType::Write)
            .await
            .unwrap();

        let checker = ResourceChecker::new(file_locks, resource_locks);

        let scope = ResourceScope::Project(PathBuf::from("/test/project"));
        let result = checker.can_start_build(&scope, "agent-1").await;

        assert!(result.is_blocked());
        let conflicts = result.conflicts();
        assert_eq!(conflicts.len(), 1);
        assert!(matches!(
            conflicts[0].conflict_type,
            ResourceConflictType::FileWriteBlocksBuild { .. }
        ));
    }

    #[tokio::test]
    async fn test_file_write_blocked_by_build() {
        let file_locks = Arc::new(FileLockManager::new());
        let resource_locks = Arc::new(ResourceLockManager::new());

        // Agent 2 acquires a build lock
        resource_locks
            .acquire_resource(
                "agent-2",
                ResourceType::Build,
                ResourceScope::Project(PathBuf::from("/test/project")),
                "cargo build",
            )
            .await
            .unwrap();

        let checker = ResourceChecker::new(file_locks, resource_locks);

        let result = checker
            .can_write_file(Path::new("/test/project/src/main.rs"), "agent-1")
            .await;

        assert!(result.is_blocked());
        let conflicts = result.conflicts();
        assert_eq!(conflicts.len(), 1);
        assert!(matches!(
            conflicts[0].conflict_type,
            ResourceConflictType::BuildBlocksFileWrite
        ));
    }

    #[tokio::test]
    async fn test_same_agent_no_conflict() {
        let file_locks = Arc::new(FileLockManager::new());
        let resource_locks = Arc::new(ResourceLockManager::new());

        // Same agent has file lock and wants to build
        file_locks
            .acquire_lock("agent-1", "/test/project/src/main.rs", LockType::Write)
            .await
            .unwrap();

        let checker = ResourceChecker::new(file_locks, resource_locks);

        let scope = ResourceScope::Project(PathBuf::from("/test/project"));
        let result = checker.can_start_build(&scope, "agent-1").await;

        // Same agent should not conflict with itself
        assert!(matches!(result, ConflictCheck::Clear));
    }
}