beads_rust 0.3.2

Agent-first issue tracker (SQLite + JSONL)
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
//! Binary discovery and version pinning for conformance testing.
//!
//! Ensures conformance runs use the correct br/bd binaries and records version metadata.
//! Fails early with actionable errors if bd is missing or unsupported.

#![allow(dead_code)]

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

/// Minimum bd version required for conformance testing.
///
/// The suite is written against bd **v0.46.0** — the version named in the
/// `#[ignore]` ledger in `tests/conformance.rs` and the one
/// `.github/workflows/conformance.yml` pins. Older releases are missing flags
/// the tests drive (`bd defer --until`, for one), so they produce failures that
/// describe bd's history rather than a br defect.
///
/// This floor used to read `0.5.0`, which admitted the entire 0.4x line: the
/// comparison is numeric per component, so `0.40.0` compares *greater* than
/// `0.5.0` (40 > 5) and sailed through.
const MIN_BD_VERSION: &str = "0.46.0";

/// First bd version that abandoned the "classic" architecture br is frozen against.
///
/// br is a port of *classic* beads: SQLite as primary storage with a JSONL export
/// (see `README.md`). bd v0.50.0 switched its default backend to Dolt and made
/// `no-db` (JSONL-only, no SQLite) the default for `bd init`. A v0.50+ binary is
/// therefore not a valid conformance reference:
///
/// - `bd init` writes no `beads.db`, so the schema conformance suite has no
///   database to introspect.
/// - `config.yaml` changed shape entirely, so `conformance_init_config` compares
///   two unrelated documents.
/// - Every mutating command prints migration banners, test-data heuristics, and
///   `beads.role not configured` advisories that classic bd never emitted, so the
///   text conformance suite diffs advisory noise rather than issue rendering.
///
/// Comparing against such a binary produces dozens of failures that describe
/// upstream's evolution, not a br defect. The bound is exclusive: bd must satisfy
/// `MIN_BD_VERSION <= version < MAX_BD_VERSION_EXCLUSIVE`.
const MAX_BD_VERSION_EXCLUSIVE: &str = "0.50.0";

/// Binary version metadata captured from `--version --json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BinaryVersion {
    pub binary: String,
    pub path: PathBuf,
    pub version: String,
    pub commit: Option<String>,
    pub build_date: Option<String>,
    #[serde(default)]
    pub raw_output: String,
}

impl BinaryVersion {
    /// Serialize to JSON for inclusion in conformance logs.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "binary": self.binary,
            "path": self.path.display().to_string(),
            "version": self.version,
            "commit": self.commit,
            "build_date": self.build_date,
        })
    }
}

/// Result of binary discovery.
#[derive(Debug, Clone)]
pub struct DiscoveredBinaries {
    pub br: BinaryVersion,
    pub bd: Option<BinaryVersion>,
}

impl DiscoveredBinaries {
    /// Check if bd is available for conformance testing.
    pub const fn bd_available(&self) -> bool {
        self.bd.is_some()
    }

    /// Get bd or return an error message.
    pub fn require_bd(&self) -> Result<&BinaryVersion, String> {
        self.bd.as_ref().ok_or_else(|| {
            "bd (Go beads) binary not found. Conformance tests require bd to be installed.\n\
             Install from: https://github.com/steveyegge/beads\n\
             Or set BD_BINARY env var to the path."
                .to_string()
        })
    }

    /// Serialize for inclusion in conformance summary.
    pub fn to_json(&self) -> serde_json::Value {
        serde_json::json!({
            "br": self.br.to_json(),
            "bd": self.bd.as_ref().map(BinaryVersion::to_json),
            "conformance_ready": self.bd_available(),
        })
    }
}

/// Discover br binary (from cargo build).
fn discover_br() -> Result<BinaryVersion, String> {
    // First check if BR_BINARY env var is set
    if let Ok(br_path) = std::env::var("BR_BINARY") {
        let path = PathBuf::from(&br_path);
        if path.exists() {
            return probe_binary("br", &path);
        }
        return Err(format!("BR_BINARY={br_path} does not exist"));
    }

    // Try cargo-built binary
    let cargo_bin = assert_cmd::cargo::cargo_bin!("br");
    if cargo_bin.exists() {
        return probe_binary("br", cargo_bin);
    }

    // Try release binary
    let manifest_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
    let release_bin = manifest_dir.join("target/release/br");
    if release_bin.exists() {
        return probe_binary("br", &release_bin);
    }

    // Try PATH
    if let Some(path) = which("br") {
        return probe_binary("br", &path);
    }

    Err("br binary not found. Build with `cargo build` first.".to_string())
}

/// Discover bd binary (Go beads).
fn discover_bd() -> Option<BinaryVersion> {
    // First check if BD_BINARY env var is set
    if let Ok(bd_path) = std::env::var("BD_BINARY") {
        let path = PathBuf::from(&bd_path);
        if path.exists() {
            return probe_binary("bd", &path).ok();
        }
        eprintln!("Warning: BD_BINARY={bd_path} does not exist");
        return None;
    }

    // Get home directory
    let home = std::env::var("HOME")
        .ok()
        .map(PathBuf::from)
        .unwrap_or_default();

    // Try common locations
    let mut common_paths = vec![
        PathBuf::from("/usr/local/bin/bd"),
        PathBuf::from("/usr/bin/bd"),
    ];

    if !home.as_os_str().is_empty() {
        common_paths.push(home.join(".local/bin/bd"));
        common_paths.push(home.join("go/bin/bd"));
    }

    for path in common_paths {
        if path.exists()
            && let Ok(version) = probe_binary("bd", &path)
        {
            return Some(version);
        }
    }

    // Try PATH
    if let Some(path) = which("bd") {
        return probe_binary("bd", &path).ok();
    }

    None
}

/// Probe a binary to extract version information.
fn probe_binary(name: &str, path: &Path) -> Result<BinaryVersion, String> {
    if name == "bd"
        && let Some(output) = run_version_command(path, &["version"])
        && looks_like_br(&output)
    {
        return Err(format!(
            "bd binary at {} appears to be br; set BD_BINARY to real bd",
            path.display()
        ));
    }

    // Try `--version --json` first
    let json_output = run_version_command(path, &["version", "--json"]);
    if let Some(output) = json_output
        && let Ok(parsed) = parse_json_version(&output)
    {
        return Ok(BinaryVersion {
            binary: name.to_string(),
            path: path.to_path_buf(),
            version: parsed.version,
            commit: parsed.commit,
            build_date: parsed.build_date,
            raw_output: output,
        });
    }

    // Fallback to plain `--version`
    let plain_output = run_version_command(path, &["--version"]);
    if let Some(output) = plain_output {
        let version = parse_plain_version(&output);
        return Ok(BinaryVersion {
            binary: name.to_string(),
            path: path.to_path_buf(),
            version,
            commit: None,
            build_date: None,
            raw_output: output,
        });
    }

    // Last resort: just verify it runs
    let check_output = run_version_command(path, &["--help"]);
    if check_output.is_some() {
        return Ok(BinaryVersion {
            binary: name.to_string(),
            path: path.to_path_buf(),
            version: "unknown".to_string(),
            commit: None,
            build_date: None,
            raw_output: check_output.unwrap_or_default(),
        });
    }

    Err(format!(
        "Binary at {} does not respond to version commands",
        path.display()
    ))
}

fn looks_like_br(output: &str) -> bool {
    output.trim_start().starts_with("br ")
}

/// Run a version command and capture output.
fn run_version_command(binary: &Path, args: &[&str]) -> Option<String> {
    let output = Command::new(binary)
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .output()
        .ok()?;

    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).to_string())
    } else {
        None
    }
}

/// Parsed JSON version response.
#[derive(Debug, Deserialize)]
struct JsonVersion {
    version: String,
    commit: Option<String>,
    build_date: Option<String>,
}

/// Parse JSON version output.
fn parse_json_version(output: &str) -> Result<JsonVersion, serde_json::Error> {
    // Handle potential prefix text before JSON
    let json_start = output.find('{').unwrap_or(0);
    serde_json::from_str(&output[json_start..])
}

/// Parse plain text version output (e.g., "br 0.1.0").
fn parse_plain_version(output: &str) -> String {
    let output = output.trim();

    // Try to extract version number
    for word in output.split_whitespace() {
        if word.chars().next().is_some_and(|c| c.is_ascii_digit()) {
            // Include digits, dots, hyphens, and alphanumeric suffixes (e.g., "0.1.0-dev")
            let version: String = word
                .chars()
                .take_while(|c| c.is_ascii_alphanumeric() || *c == '.' || *c == '-')
                .collect();
            if !version.is_empty() {
                return version;
            }
        }
    }

    "unknown".to_string()
}

/// Find binary in PATH.
fn which(name: &str) -> Option<PathBuf> {
    std::env::var_os("PATH").and_then(|paths| {
        std::env::split_paths(&paths).find_map(|dir| {
            let path = dir.join(name);
            if path.exists() && path.is_file() {
                Some(path)
            } else {
                None
            }
        })
    })
}

/// Discover both br and bd binaries.
///
/// Returns error only if br is not found (bd is optional for non-conformance tests).
pub fn discover_binaries() -> Result<DiscoveredBinaries, String> {
    let br = discover_br()?;
    let bd = discover_bd();

    Ok(DiscoveredBinaries { br, bd })
}

/// Check if bd version meets minimum requirements for conformance.
pub fn check_bd_version(version: &BinaryVersion) -> Result<(), String> {
    let current = &version.version;

    // Skip check for development/unknown versions
    if current == "unknown" || current.contains("dev") {
        return Ok(());
    }

    // Simple version comparison (works for semver)
    if compare_versions(current, MIN_BD_VERSION).is_lt() {
        return Err(format!(
            "bd version {current} is below minimum required version {MIN_BD_VERSION}. Please upgrade bd."
        ));
    }

    Ok(())
}

/// Name or path of the reference bd binary (`BD_BINARY`, else PATH lookup).
pub fn bd_binary_name() -> String {
    std::env::var("BD_BINARY").unwrap_or_else(|_| "bd".to_string())
}

/// Why the conformance suite cannot use the discovered `bd`, if it cannot.
///
/// This is the single gate every conformance and benchmark suite consults, so a
/// misconfigured reference binary produces one actionable skip message instead of
/// dozens of diffs against a binary that was never comparable.
///
/// Returns `None` when `bd` is a usable classic reference.
pub fn bd_skip_reason() -> Option<String> {
    let bd_bin = bd_binary_name();

    let Some(stdout) = run_version_command(Path::new(&bd_bin), &["version"]) else {
        return Some(format!(
            "'{bd_bin}' did not respond to `bd version`. {REMEDY}"
        ));
    };

    // `bd` aliased or symlinked to `br` would compare br against itself.
    if looks_like_br(&stdout) {
        return Some(format!(
            "'{bd_bin}' is br, not Go bd — conformance would compare br against itself. {REMEDY}"
        ));
    }

    let first_token = stdout
        .split_whitespace()
        .next()
        .map(str::to_ascii_lowercase)
        .unwrap_or_default();
    if !matches!(first_token.as_str(), "bd" | "beads") {
        return Some(format!(
            "'{bd_bin}' does not identify itself as bd (`bd version` printed {stdout:?}). {REMEDY}"
        ));
    }

    let version = parse_plain_version(&stdout);
    if version == "unknown" {
        // Locally built bd without version stamping: trust the operator's choice.
        return None;
    }

    if compare_versions(&version, MIN_BD_VERSION).is_lt() {
        return Some(format!(
            "bd {version} at '{bd_bin}' predates the conformance baseline \
             (minimum {MIN_BD_VERSION}). {REMEDY}"
        ));
    }

    if compare_versions(&version, MAX_BD_VERSION_EXCLUSIVE).is_ge() {
        return Some(format!(
            "bd {version} at '{bd_bin}' is past the classic architecture br is frozen against \
             (requires < {MAX_BD_VERSION_EXCLUSIVE}). bd v0.50+ defaults to Dolt and to \
             JSONL-only `no-db` mode, so it exposes no SQLite schema, writes a different \
             config.yaml, and prints migration banners on every command. {REMEDY}"
        ));
    }

    None
}

/// Operator remedy appended to every conformance skip message.
const REMEDY: &str = "Point BD_BINARY at a classic Go bd, e.g. \
     `git clone --depth 1 --branch v0.46.0 https://github.com/steveyegge/beads.git \
     && cd beads && go build -o bd ./cmd/bd`.";

/// Whether `bd` is usable as a conformance reference.
pub fn bd_available() -> bool {
    bd_skip_reason().is_none()
}

/// Simple semver-style version comparison.
fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering {
    let parse = |s: &str| -> Vec<u32> {
        s.split(|c: char| !c.is_ascii_digit())
            .filter_map(|p| p.parse().ok())
            .collect()
    };

    let av = parse(a);
    let bv = parse(b);

    av.cmp(&bv)
}

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

    #[test]
    fn test_discover_br() {
        let result = discover_br();
        assert!(result.is_ok(), "br should be discoverable: {result:?}");

        let version = result.unwrap();
        assert_eq!(version.binary, "br");
        assert!(version.path.exists());
    }

    #[test]
    fn test_discover_binaries() {
        let result = discover_binaries();
        assert!(result.is_ok(), "Binary discovery failed: {result:?}");

        let binaries = result.unwrap();
        assert_eq!(binaries.br.binary, "br");

        // bd may or may not be available
        if binaries.bd_available() {
            let bd = binaries.bd.as_ref().unwrap();
            assert_eq!(bd.binary, "bd");
        }
    }

    #[test]
    fn test_parse_plain_version() {
        assert_eq!(parse_plain_version("br 0.1.0"), "0.1.0");
        assert_eq!(parse_plain_version("beads 0.5.2"), "0.5.2");
        assert_eq!(parse_plain_version("0.1.0-dev"), "0.1.0-dev");
        assert_eq!(parse_plain_version("no version"), "unknown");
    }

    #[test]
    fn test_compare_versions() {
        use std::cmp::Ordering;
        assert_eq!(compare_versions("0.1.0", "0.1.0"), Ordering::Equal);
        assert_eq!(compare_versions("0.2.0", "0.1.0"), Ordering::Greater);
        assert_eq!(compare_versions("0.1.0", "0.2.0"), Ordering::Less);
        assert_eq!(compare_versions("1.0.0", "0.5.0"), Ordering::Greater);
    }

    /// The classic-architecture window must accept the bd releases br was ported
    /// against and reject the Dolt-default line, including the double-digit minor
    /// versions that a naive lexicographic comparison would order wrongly.
    #[test]
    fn test_classic_bd_version_window() {
        let in_window = |v: &str| {
            compare_versions(v, MIN_BD_VERSION).is_ge()
                && compare_versions(v, MAX_BD_VERSION_EXCLUSIVE).is_lt()
        };

        // Classic line: SQLite primary storage, JSONL export.
        assert!(in_window("0.46.0"), "minimum is inclusive");
        assert!(in_window("0.47.2"));
        assert!(in_window("0.49.6"), "last classic release");

        // Pre-0.46 releases compare numerically per component, so a naive floor
        // of "0.5.0" would admit the whole 0.4x line (40 > 5). They lack flags
        // the suite drives, e.g. `bd defer --until`.
        assert!(!in_window("0.40.0"), "0.4x must not slip past the floor");
        assert!(!in_window("0.45.0"));

        // Dolt-default line.
        assert!(!in_window("0.50.0"), "maximum is exclusive");
        assert!(!in_window("0.50.3"), "upstream default install");
        assert!(!in_window("0.59.0"));
        assert!(!in_window("1.0.0"));

        // Below the baseline.
        assert!(!in_window("0.4.9"));
    }

    #[test]
    fn test_bd_skip_reason_messages_are_actionable() {
        // A reason, when present, must always name the remedy so an operator can
        // act without reading this file.
        if let Some(reason) = bd_skip_reason() {
            assert!(
                reason.contains("BD_BINARY"),
                "skip reason must name BD_BINARY: {reason}"
            );
        }
    }

    #[test]
    fn test_discovered_binaries_json() {
        let binaries = discover_binaries().expect("discovery failed");
        let json = binaries.to_json();

        assert!(json.get("br").is_some());
        assert!(json.get("conformance_ready").is_some());
    }
}