beads_viewer_rust 0.2.1

Spec-first Rust port of beads_viewer (bv) — graph-aware triage for beads issue trackers (CLI binary: bvr)
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
//! AGENTS.md blurb management for AI coding agents.
//!
//! Detects, injects, updates, and removes standardised beads workflow
//! instructions in agent configuration files (AGENTS.md, CLAUDE.md, etc.).

use std::path::{Path, PathBuf};

use crate::{BvrError, Result};

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Current blurb format version. Increment on breaking changes.
///
/// COUPLING NOTE: When bumping this value, also update the `v<N>` marker
/// inside `AGENT_BLURB` below (the raw string literal cannot interpolate).
/// The `agent_blurb_version_matches_constant` test will catch any mismatch.
const BLURB_VERSION: u32 = 1;

#[cfg(test)]
const BLURB_START_MARKER: &str = "<!-- bv-agent-instructions-v1 -->";
const BLURB_END_MARKER: &str = "<!-- end-bv-agent-instructions -->";

/// Ordered preference for agent file names.
const SUPPORTED_FILES: &[&str] = &["AGENTS.md", "CLAUDE.md", "agents.md", "claude.md"];

/// Beads workflow instructions blurb.
///
/// The `<!-- bv-agent-instructions-vN -->` marker must match [`BLURB_VERSION`].
const AGENT_BLURB: &str = r#"<!-- bv-agent-instructions-v1 -->

---

## Beads Workflow Integration

This project uses [beads_rust](https://github.com/Dicklesworthstone/beads_rust) (`br`) for issue tracking. Issues are stored in `.beads/` and tracked in git.

**Important:** `br` is non-invasive—it NEVER runs git commands automatically. After `br sync --flush-only`, you must manually commit changes.

### Essential Commands

```bash
# View issues (launches TUI - avoid in automated sessions)
bvr

# CLI commands for agents (use these instead)
br ready              # Show issues ready to work (no blockers)
br list --status=open # All open issues
br show <id>          # Full issue details with dependencies
br create --title="..." --type=task --priority=2
br update <id> --status=in_progress
br close <id> --reason "Completed"
br close <id1> <id2>  # Close multiple issues at once
br sync --flush-only  # Export to JSONL (NO git operations)
```

### Workflow Pattern

1. **Start**: Run `br ready` to find actionable work
2. **Claim**: Use `br update <id> --status=in_progress`
3. **Work**: Implement the task
4. **Complete**: Use `br close <id>`
5. **Sync**: Run `br sync --flush-only` then manually commit

### Key Concepts

- **Dependencies**: Issues can block other issues. `br ready` shows only unblocked work.
- **Priority**: P0=critical, P1=high, P2=medium, P3=low, P4=backlog (use numbers, not words)
- **Types**: task, bug, feature, epic, question, docs
- **Blocking**: `br dep add <issue> <depends-on>` to add dependencies

### Session Protocol

**Before ending any session, run this checklist:**

```bash
git status              # Check what changed
git add <files>         # Stage code changes
br sync --flush-only    # Export beads to JSONL
git add .beads/         # Stage beads changes
git commit -m "..."     # Commit everything together
git push                # Push to remote
```

### Best Practices

- Check `br ready` at session start to find available work
- Update status as you work (in_progress -> closed)
- Create new issues with `br create` when you discover tasks
- Use descriptive titles and set appropriate priority/type
- Always `br sync --flush-only && git add .beads/` before ending session

<!-- end-bv-agent-instructions -->"#;

// ---------------------------------------------------------------------------
// Detection
// ---------------------------------------------------------------------------

/// Result of detecting an agent config file.
#[derive(Debug, Clone, Default)]
pub struct AgentFileDetection {
    pub file_path: Option<PathBuf>,
    pub file_type: String,
    pub has_blurb: bool,
    pub has_legacy_blurb: bool,
    pub blurb_version: u32,
    pub content: String,
    /// True when the file exists but could not be read (permissions, encoding).
    pub read_error: bool,
}

impl AgentFileDetection {
    pub fn found(&self) -> bool {
        self.file_path.is_some()
    }

    pub fn needs_blurb(&self) -> bool {
        self.found() && !self.has_blurb
    }

    pub fn needs_upgrade(&self) -> bool {
        if self.has_legacy_blurb {
            return true;
        }
        self.has_blurb && self.blurb_version < BLURB_VERSION
    }
}

/// Check if content contains the current blurb format.
fn contains_blurb(content: &str) -> bool {
    content.contains("<!-- bv-agent-instructions-v")
}

/// Check if content contains the legacy blurb (pre-v1, no HTML markers).
fn contains_legacy_blurb(content: &str) -> bool {
    let patterns = [
        "### Using bv as an AI sidecar",
        "--robot-insights",
        "--robot-plan",
        "bv already computes the hard parts",
    ];

    // Must have the section header
    if !content.contains("Using bv as an AI sidecar") {
        return false;
    }

    // Require all patterns
    patterns.iter().all(|p| content.contains(p))
}

/// Extract blurb version from content.
fn get_blurb_version(content: &str) -> u32 {
    // Look for <!-- bv-agent-instructions-v<N> -->
    let marker = "<!-- bv-agent-instructions-v";
    if let Some(pos) = content.find(marker) {
        let after = &content[pos + marker.len()..];
        if let Some(end) = after.find(" -->") {
            if let Ok(v) = after[..end].parse::<u32>() {
                return v;
            }
        }
    }
    0
}

/// Detect an agent file in a single directory.
fn detect_agent_file(work_dir: &Path) -> AgentFileDetection {
    // Try uppercase variants first
    for &filename in SUPPORTED_FILES
        .iter()
        .filter(|f| f.starts_with(|c: char| c.is_uppercase()))
    {
        let path = work_dir.join(filename);
        if let Some(det) = check_agent_file(&path, filename) {
            return det;
        }
    }

    // Try lowercase variants
    for &filename in SUPPORTED_FILES
        .iter()
        .filter(|f| f.starts_with(|c: char| c.is_lowercase()))
    {
        let path = work_dir.join(filename);
        if let Some(det) = check_agent_file(&path, filename) {
            return det;
        }
    }

    AgentFileDetection::default()
}

fn check_agent_file(path: &Path, file_type: &str) -> Option<AgentFileDetection> {
    if !path.is_file() {
        return None;
    }

    let content = match std::fs::read_to_string(path) {
        Ok(text) => text,
        Err(error) => {
            tracing::warn!(
                "cannot read {}: {error} — treating as unreadable",
                path.display()
            );
            return Some(AgentFileDetection {
                file_path: Some(path.to_path_buf()),
                file_type: file_type.to_string(),
                read_error: true,
                ..Default::default()
            });
        }
    };

    let has_legacy = contains_legacy_blurb(&content);
    let has_blurb = contains_blurb(&content) || has_legacy;

    Some(AgentFileDetection {
        file_path: Some(path.to_path_buf()),
        file_type: file_type.to_string(),
        has_blurb,
        has_legacy_blurb: has_legacy,
        blurb_version: get_blurb_version(&content),
        content,
        read_error: false,
    })
}

/// Search for agent files starting from `work_dir` and walking up.
pub fn detect_agent_file_in_parents(work_dir: &Path, max_levels: usize) -> AgentFileDetection {
    let mut current = work_dir.to_path_buf();
    for _ in 0..=max_levels {
        let det = detect_agent_file(&current);
        if det.found() {
            return det;
        }
        match current.parent() {
            Some(parent) if parent != current => current = parent.to_path_buf(),
            _ => break,
        }
    }
    AgentFileDetection::default()
}

// ---------------------------------------------------------------------------
// Blurb manipulation
// ---------------------------------------------------------------------------

/// Append the blurb to content.
fn append_blurb(content: &str) -> String {
    let mut out = content.to_string();
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out.push('\n');
    out.push_str(AGENT_BLURB);
    out.push('\n');
    out
}

/// Remove the current-format blurb from content.
fn remove_blurb(content: &str) -> String {
    let Some(start_byte) = content.find("<!-- bv-agent-instructions-v") else {
        return content.to_string();
    };
    let Some(end_byte) = content.find(BLURB_END_MARKER) else {
        return content.to_string();
    };

    let mut end = end_byte + BLURB_END_MARKER.len();
    // Consume trailing newlines
    while end < content.len() && matches!(content.as_bytes()[end], b'\n' | b'\r') {
        end += 1;
    }
    // Consume leading newlines
    let mut start = start_byte;
    while start > 0 && matches!(content.as_bytes()[start - 1], b'\n' | b'\r') {
        start -= 1;
    }

    let mut result = content[..start].to_string();
    result.push_str(&content[end..]);
    result
}

/// Remove the legacy blurb (pre-v1) from content.
fn remove_legacy_blurb(content: &str) -> String {
    if !contains_legacy_blurb(content) {
        return content.to_string();
    }

    // Find start: "## Using bv as an AI sidecar" or "### Using bv as an AI sidecar"
    let Some(start_byte) = content.find("Using bv as an AI sidecar") else {
        return content.to_string();
    };
    // Back up to the heading marker
    let start = content[..start_byte].rfind('#').unwrap_or(start_byte);

    // Find end: "bv already computes the hard parts"
    let end = content[start..]
        .find("bv already computes the hard parts")
        .map_or(content.len(), |pos| {
            let mut e = start + pos;
            // Skip to end of line
            if let Some(nl) = content[e..].find('\n') {
                e += nl + 1;
            } else {
                e = content.len();
            }
            // Skip trailing code fence if present
            let remaining = &content[e..];
            if remaining.starts_with("```") {
                if let Some(nl) = remaining.find('\n') {
                    e += nl + 1;
                }
            }
            // Consume trailing newlines
            while e < content.len() && matches!(content.as_bytes()[e], b'\n' | b'\r') {
                e += 1;
            }
            e
        });

    // Consume leading newlines before start
    let mut adj_start = start;
    while adj_start > 0 && matches!(content.as_bytes()[adj_start - 1], b'\n' | b'\r') {
        adj_start -= 1;
    }
    if adj_start > 0 {
        adj_start += 1; // Keep one newline separator
    }

    let mut result = content[..adj_start].to_string();
    result.push_str(&content[end..]);
    result
}

/// Replace existing blurb (current or legacy) with the current version.
fn update_blurb(content: &str) -> String {
    let content = remove_legacy_blurb(content);
    let content = remove_blurb(&content);
    append_blurb(&content)
}

// ---------------------------------------------------------------------------
// File operations
// ---------------------------------------------------------------------------

/// Write file contents, using temp-file + rename when possible for atomicity.
fn atomic_write(path: &Path, content: &[u8]) -> Result<()> {
    use std::io::Write;

    let dir = path.parent().unwrap_or_else(|| Path::new("."));

    // Try atomic temp-file + rename first
    match tempfile::NamedTempFile::new_in(dir) {
        Ok(mut tmp) => {
            tmp.write_all(content).map_err(BvrError::Io)?;
            tmp.as_file().sync_all().map_err(BvrError::Io)?;
            tmp.persist(path).map_err(|e| BvrError::Io(e.error))?;
        }
        Err(_) => {
            // Fall back to direct write (e.g. when dir is not writable for temp files)
            std::fs::write(path, content).map_err(BvrError::Io)?;
        }
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Public CLI actions
// ---------------------------------------------------------------------------

/// Result returned to the CLI dispatcher with a user-facing message.
pub struct AgentsResult {
    pub message: String,
    pub changed: bool,
}

fn agents_check_from_detection(work_dir: &Path, det: &AgentFileDetection) -> AgentsResult {
    if !det.found() {
        return AgentsResult {
            message: format!(
                "No agent file found (searched up to 3 parent directories from {}).\n\
                 Run 'bvr --agents-add' to create AGENTS.md with beads workflow instructions.",
                work_dir.display()
            ),
            changed: false,
        };
    }

    let Some(path_buf) = det.file_path.as_ref() else {
        return AgentsResult {
            message: format!(
                "Found {} but could not resolve its path; run 'bvr --agents-check' again.",
                det.file_type
            ),
            changed: false,
        };
    };
    let path = path_buf.display();

    if det.read_error {
        return AgentsResult {
            message: format!(
                "Found {file_type} at {path}, but it could not be read.\n\
                 Check file permissions before running any agents command.",
                file_type = det.file_type,
            ),
            changed: false,
        };
    }

    if det.needs_upgrade() {
        let current_ver = if det.has_legacy_blurb {
            "legacy".to_string()
        } else {
            format!("v{}", det.blurb_version)
        };
        return AgentsResult {
            message: format!(
                "Found {file_type} at {path} (blurb {current_ver}, current v{BLURB_VERSION} — needs update)\n\
                 Run 'bvr --agents-update' to update to the latest version.",
                file_type = det.file_type,
            ),
            changed: false,
        };
    }

    if det.needs_blurb() {
        return AgentsResult {
            message: format!(
                "Found {file_type} at {path} (no blurb)\n\
                 Run 'bvr --agents-add' to add beads workflow instructions.",
                file_type = det.file_type,
            ),
            changed: false,
        };
    }

    AgentsResult {
        message: format!(
            "Found {file_type} at {path} (blurb v{BLURB_VERSION} — up to date)",
            file_type = det.file_type,
        ),
        changed: false,
    }
}

/// `--agents-check`: report blurb status.
pub fn agents_check(work_dir: &Path) -> AgentsResult {
    let det = detect_agent_file_in_parents(work_dir, 3);
    agents_check_from_detection(work_dir, &det)
}

/// `--agents-add`: add blurb to agent file (create if needed).
pub fn agents_add(work_dir: &Path, dry_run: bool) -> Result<AgentsResult> {
    let det = detect_agent_file_in_parents(work_dir, 3);

    if det.found() {
        let Some(path) = det.file_path.as_ref() else {
            return Err(BvrError::InvalidArgument(
                "Agent file detected but no file path was recorded.".to_string(),
            ));
        };

        if det.read_error {
            return Err(BvrError::InvalidArgument(format!(
                "Cannot read {} — check file permissions.",
                path.display()
            )));
        }

        if det.has_blurb && !det.needs_upgrade() {
            return Ok(AgentsResult {
                message: format!(
                    "{} already has blurb v{BLURB_VERSION} — nothing to do.",
                    det.file_type
                ),
                changed: false,
            });
        }

        if det.needs_upgrade() {
            return Err(BvrError::InvalidArgument(format!(
                "{} has outdated blurb. Run 'bvr --agents-update' instead.",
                det.file_type
            )));
        }

        // File exists but no blurb — append
        if dry_run {
            return Ok(AgentsResult {
                message: format!("[dry-run] Would append blurb to {}.", path.display()),
                changed: false,
            });
        }

        let new_content = append_blurb(&det.content);
        atomic_write(path, new_content.as_bytes())?;

        return Ok(AgentsResult {
            message: format!("Added blurb to {}.", path.display()),
            changed: true,
        });
    }

    // No agent file — create AGENTS.md
    let path = work_dir.join("AGENTS.md");
    if dry_run {
        return Ok(AgentsResult {
            message: format!("[dry-run] Would create {}.", path.display()),
            changed: false,
        });
    }

    let content = format!("# AI Agent Instructions\n\n{AGENT_BLURB}\n");
    atomic_write(&path, content.as_bytes())?;

    Ok(AgentsResult {
        message: format!(
            "Created {} with beads workflow instructions.",
            path.display()
        ),
        changed: true,
    })
}

/// `--agents-update`: upgrade blurb to current version.
pub fn agents_update(work_dir: &Path, dry_run: bool) -> Result<AgentsResult> {
    let det = detect_agent_file_in_parents(work_dir, 3);

    if !det.found() {
        return Err(BvrError::InvalidArgument(
            "No agent file found. Run 'bvr --agents-add' first.".to_string(),
        ));
    }

    let Some(path) = det.file_path.as_ref() else {
        return Err(BvrError::InvalidArgument(
            "Agent file detected but no file path was recorded.".to_string(),
        ));
    };

    if det.read_error {
        return Err(BvrError::InvalidArgument(format!(
            "Cannot read {} — check file permissions.",
            path.display()
        )));
    }

    if !det.has_blurb {
        return Err(BvrError::InvalidArgument(format!(
            "{} has no blurb to update. Run 'bvr --agents-add' instead.",
            det.file_type,
        )));
    }

    if !det.needs_upgrade() {
        return Ok(AgentsResult {
            message: format!(
                "{} blurb is already v{BLURB_VERSION} — nothing to do.",
                det.file_type,
            ),
            changed: false,
        });
    }

    let label = if det.has_legacy_blurb {
        "legacy blurb"
    } else {
        "outdated blurb"
    };

    if dry_run {
        return Ok(AgentsResult {
            message: format!(
                "[dry-run] Would upgrade {label} to v{BLURB_VERSION} in {}.",
                path.display()
            ),
            changed: false,
        });
    }

    let new_content = update_blurb(&det.content);
    atomic_write(path, new_content.as_bytes())?;

    Ok(AgentsResult {
        message: format!("Updated blurb to v{BLURB_VERSION} in {}.", path.display()),
        changed: true,
    })
}

/// `--agents-remove`: remove blurb from agent file.
pub fn agents_remove(work_dir: &Path, dry_run: bool) -> Result<AgentsResult> {
    let det = detect_agent_file_in_parents(work_dir, 3);

    if !det.found() {
        return Ok(AgentsResult {
            message: "No agent file found — nothing to remove.".to_string(),
            changed: false,
        });
    }

    let Some(path) = det.file_path.as_ref() else {
        return Err(BvrError::InvalidArgument(
            "Agent file detected but no file path was recorded.".to_string(),
        ));
    };

    if det.read_error {
        return Err(BvrError::InvalidArgument(format!(
            "Cannot read {} — check file permissions.",
            path.display()
        )));
    }

    if !det.has_blurb {
        return Ok(AgentsResult {
            message: format!("{} has no blurb — nothing to remove.", det.file_type),
            changed: false,
        });
    }

    if dry_run {
        return Ok(AgentsResult {
            message: format!("[dry-run] Would remove blurb from {}.", path.display()),
            changed: false,
        });
    }

    let new_content = if det.has_legacy_blurb {
        remove_legacy_blurb(&det.content)
    } else {
        remove_blurb(&det.content)
    };
    atomic_write(path, new_content.as_bytes())?;

    Ok(AgentsResult {
        message: format!("Removed blurb from {}.", path.display()),
        changed: true,
    })
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    #[test]
    fn contains_blurb_detects_current_marker() {
        assert!(contains_blurb(
            "before\n<!-- bv-agent-instructions-v1 -->\nstuff\n<!-- end-bv-agent-instructions -->\nafter"
        ));
        assert!(!contains_blurb("no marker here"));
    }

    #[test]
    fn get_blurb_version_extracts_version() {
        assert_eq!(get_blurb_version("<!-- bv-agent-instructions-v1 -->"), 1);
        assert_eq!(get_blurb_version("<!-- bv-agent-instructions-v42 -->"), 42);
        assert_eq!(get_blurb_version("no marker"), 0);
    }

    #[test]
    fn agent_blurb_version_matches_constant() {
        // Guard against BLURB_VERSION being bumped without updating the
        // version marker inside AGENT_BLURB. If this fails, update the
        // `<!-- bv-agent-instructions-vN -->` marker in AGENT_BLURB to
        // match BLURB_VERSION.
        assert_eq!(
            get_blurb_version(AGENT_BLURB),
            BLURB_VERSION,
            "AGENT_BLURB marker version must match BLURB_VERSION (currently {BLURB_VERSION})"
        );
    }

    #[test]
    fn append_blurb_adds_to_content() {
        let result = append_blurb("# Existing\n");
        assert!(result.starts_with("# Existing\n"));
        assert!(result.contains(BLURB_START_MARKER));
        assert!(result.contains(BLURB_END_MARKER));
    }

    #[test]
    fn agent_blurb_uses_bvr_command_name() {
        assert!(AGENT_BLURB.contains("\nbvr\n"));
        assert!(!AGENT_BLURB.contains("\nbv\n"));
    }

    #[test]
    fn remove_blurb_strips_current() {
        let content = format!("before\n\n{AGENT_BLURB}\n\nafter");
        let result = remove_blurb(&content);
        assert!(result.contains("before"));
        assert!(result.contains("after"));
        assert!(!result.contains(BLURB_START_MARKER));
    }

    #[test]
    fn update_blurb_replaces_existing() {
        let old = "# File\n\n<!-- bv-agent-instructions-v0 -->\nold stuff\n<!-- end-bv-agent-instructions -->\n";
        let result = update_blurb(old);
        assert!(result.contains(BLURB_START_MARKER));
        assert!(!result.contains("old stuff"));
        assert!(result.contains("br ready"));
    }

    #[test]
    fn detection_defaults() {
        let det = AgentFileDetection::default();
        assert!(!det.found());
        assert!(!det.needs_blurb());
        assert!(!det.needs_upgrade());
    }

    #[test]
    fn detection_needs_upgrade_for_legacy() {
        let det = AgentFileDetection {
            file_path: Some(PathBuf::from("/test/AGENTS.md")),
            has_blurb: true,
            has_legacy_blurb: true,
            ..Default::default()
        };
        assert!(det.needs_upgrade());
    }

    #[test]
    fn detection_up_to_date() {
        let det = AgentFileDetection {
            file_path: Some(PathBuf::from("/test/AGENTS.md")),
            has_blurb: true,
            blurb_version: BLURB_VERSION,
            ..Default::default()
        };
        assert!(!det.needs_upgrade());
        assert!(!det.needs_blurb());
    }

    #[test]
    fn agents_check_no_file() {
        let tmp = tempfile::tempdir().unwrap();
        // Nest 4 levels deep so the 3-level parent walk stays inside the temp dir
        let nested = tmp.path().join("a/b/c/d");
        std::fs::create_dir_all(&nested).unwrap();
        let result = agents_check(&nested);
        assert!(
            result.message.contains("No agent file found"),
            "unexpected message: {}",
            result.message
        );
        assert!(!result.changed);
    }

    #[test]
    fn agents_check_reports_unreadable_agent_file() {
        let work_dir = Path::new("/tmp/project");
        let detection = AgentFileDetection {
            file_path: Some(PathBuf::from("/tmp/project/AGENTS.md")),
            file_type: "AGENTS.md".to_string(),
            read_error: true,
            ..Default::default()
        };

        let result = agents_check_from_detection(work_dir, &detection);
        assert!(result.message.contains("could not be read"));
        assert!(result.message.contains("Check file permissions"));
        assert!(!result.changed);
    }

    #[test]
    fn agents_add_creates_file() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a/b/c/d");
        std::fs::create_dir_all(&nested).unwrap();
        let result = agents_add(&nested, false).unwrap();
        assert!(result.changed);
        assert!(result.message.contains("Created"));

        let content = std::fs::read_to_string(nested.join("AGENTS.md")).unwrap();
        assert!(content.contains(BLURB_START_MARKER));
    }

    #[test]
    fn agents_add_dry_run_no_write() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a/b/c/d");
        std::fs::create_dir_all(&nested).unwrap();
        let result = agents_add(&nested, true).unwrap();
        assert!(!result.changed);
        assert!(result.message.contains("[dry-run]"));
        assert!(!nested.join("AGENTS.md").exists());
    }

    #[test]
    fn agents_remove_strips_blurb() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a/b/c/d");
        std::fs::create_dir_all(&nested).unwrap();
        let path = nested.join("AGENTS.md");
        let content = format!("# Header\n\n{AGENT_BLURB}\n\n## Other\n");
        std::fs::write(&path, &content).unwrap();

        let result = agents_remove(&nested, false).unwrap();
        assert!(result.changed);

        let updated = std::fs::read_to_string(&path).unwrap();
        assert!(!updated.contains(BLURB_START_MARKER));
        assert!(updated.contains("# Header"));
        assert!(updated.contains("## Other"));
    }

    #[test]
    fn agents_update_upgrades_old_version() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a/b/c/d");
        std::fs::create_dir_all(&nested).unwrap();
        let path = nested.join("AGENTS.md");
        let content = "# Header\n\n<!-- bv-agent-instructions-v0 -->\nold\n<!-- end-bv-agent-instructions -->\n";
        std::fs::write(&path, content).unwrap();

        let result = agents_update(&nested, false).unwrap();
        assert!(result.changed);

        let updated = std::fs::read_to_string(&path).unwrap();
        assert!(updated.contains("bv-agent-instructions-v1"));
        assert!(updated.contains("br ready"));
    }

    #[test]
    fn roundtrip_add_check_remove() {
        let tmp = tempfile::tempdir().unwrap();
        let nested = tmp.path().join("a/b/c/d");
        std::fs::create_dir_all(&nested).unwrap();

        // Add
        let r = agents_add(&nested, false).unwrap();
        assert!(r.changed);

        // Check
        let r = agents_check(&nested);
        assert!(r.message.contains("up to date"));

        // Remove
        let r = agents_remove(&nested, false).unwrap();
        assert!(r.changed);

        // Check again
        let r = agents_check(&nested);
        assert!(r.message.contains("no blurb"));
    }
}