beady-eye 0.8.0

A tree of work in flight: bead graphs annotated with the live agents working them
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
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
//! bd's command line as the way to a project's tracker.
//!
//! The one module that spells `bd -C <path> --readonly …`. Each question the
//! seam asks is one bd invocation or two, answered in bd's own JSON and parsed
//! here and nowhere else. The roots to draw the rows under are read off the
//! rows themselves, in `app::tracker`.

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Mutex;

use anyhow::Context;
use serde::Deserialize;

use chrono::{DateTime, Utc};
use serde::Deserializer;

use crate::collect::environment;
use crate::collect::run::{Env, FailureKind, RunFailure, Runner};
use crate::collect::tracker::{OpenFailure, Tracker, Trackers};
use crate::config::Project;
use crate::model::types::{Bead, Dependency, Edge, Status};

/// Parse a flat array of bd rows, however the answer that carried them was
/// asked for. `bd list`, `bd ready` and `bd query` all write the same row.
pub fn parse_beads(s: &str) -> anyhow::Result<Vec<Bead>> {
    let rows: Vec<Row> =
        serde_json::from_str(s).context("bd --json returned a shape we do not understand")?;
    // Read for its own fields after it has parsed, so what a reader is told
    // about an answer that would not parse still carries where in the answer
    // it broke. Anything the typed read accepted is an array of objects here.
    let written: Vec<serde_json::Map<String, serde_json::Value>> =
        serde_json::from_str(s).context("bd --json returned a shape we do not understand")?;
    Ok(rows
        .into_iter()
        .zip(written)
        .map(|(row, written)| row.into_bead(values_of(&written)))
        .collect())
}

/// Every value this row holds, under the key that names it: a field by its own
/// name, and a member of a field's object by the two joined with a dot.
///
/// A badge reads here, so what a row holds is what a badge can draw. A field bd
/// grows is drawable the day bd writes it, and an object-valued one is drawable
/// a member at a time, without `bdi` learning a thing about either.
///
/// `text_of` decides what is one value, and it decides it the same way for a
/// field and for a member. The rule is about kinds of value rather than names
/// of fields, so nothing here moves when bd's schema does.
fn values_of(row: &serde_json::Map<String, serde_json::Value>) -> BTreeMap<String, String> {
    let mut values = BTreeMap::new();
    for (field, value) in row {
        match object_written_either_way(value) {
            Some(members) => values.extend(
                members
                    .iter()
                    .filter_map(|(key, member)| Some((format!("{field}.{key}"), text_of(member)?))),
            ),
            None => {
                if let Some(text) = text_of(value) {
                    values.insert(field.clone(), text);
                }
            }
        }
    }
    values
}

/// One value as the text it prints as, or nothing where it is not one value.
///
/// A string, a number and a boolean are each one value. A null and an empty
/// string are both how bd spells something nothing was written to — it writes
/// the top of a chain as an empty parent — and an array is not one value at
/// all. Those are no key, which is where a name no row carries already lands.
/// So is an object, which is what keeps a key naming a whole one from drawing
/// the blob onto a row.
fn text_of(value: &serde_json::Value) -> Option<String> {
    match value {
        serde_json::Value::String(text) if !text.is_empty() => Some(text.clone()),
        serde_json::Value::Number(_) | serde_json::Value::Bool(_) => Some(value.to_string()),
        _ => None,
    }
}

/// One row of a bd listing, in the shape bd writes it, holding only the
/// fields `bdi` reads.
///
/// Unknown fields are ignored, and a field written as null reads as the one
/// bd left out; a field of any other wrong type is still an error.
///
/// `depth` is deliberately absent: bd flattens it under `--max-depth`, so the
/// tree recomputes nesting from the dependency edges instead.
#[derive(Deserialize)]
struct Row {
    id: String,
    #[serde(deserialize_with = "null_is_default")]
    title: String,
    #[serde(deserialize_with = "null_is_unrecognised")]
    status: Status,
    #[serde(default, deserialize_with = "null_is_default")]
    priority: u8,
    #[serde(default, deserialize_with = "null_is_default")]
    issue_type: String,
    /// bd writes the top of a chain as an empty parent, or leaves the field
    /// out; either reads as none.
    #[serde(default, deserialize_with = "empty_is_none")]
    parent: Option<String>,
    #[serde(default, deserialize_with = "none_is_empty")]
    dependencies: Vec<RowDependency>,
    #[serde(default, deserialize_with = "text_of_each_value")]
    metadata: BTreeMap<String, String>,
    #[serde(default)]
    owner: Option<String>,
    #[serde(default)]
    assignee: Option<String>,
    /// As `bd show` prints it. bd leaves the field out of a row that has
    /// none.
    #[serde(default)]
    description: Option<String>,
    /// Everything `bd note` has added, as one text. Left out the same way.
    #[serde(default)]
    notes: Option<String>,
    #[serde(default)]
    updated_at: Option<DateTime<Utc>>,
    #[serde(default)]
    started_at: Option<DateTime<Utc>>,
    #[serde(default)]
    closed_at: Option<DateTime<Utc>>,
    #[serde(default)]
    defer_until: Option<DateTime<Utc>>,
}

/// One dependency as a row carries it.
#[derive(Deserialize)]
struct RowDependency {
    depends_on_id: String,
    #[serde(rename = "type")]
    edge: Edge,
}

impl Row {
    /// This row as a bead, beside every value a badge could name in it.
    fn into_bead(self, values: BTreeMap<String, String>) -> Bead {
        let row = self;
        Bead {
            values,
            id: row.id,
            title: row.title,
            status: row.status,
            priority: row.priority,
            issue_type: row.issue_type,
            parent: row.parent,
            dependencies: row
                .dependencies
                .into_iter()
                .map(|dependency| Dependency {
                    on: dependency.depends_on_id,
                    edge: dependency.edge,
                })
                .collect(),
            metadata: row.metadata,
            owner: row.owner,
            assignee: row.assignee,
            description: row.description,
            notes: row.notes,
            updated_at: row.updated_at,
            started_at: row.started_at,
            closed_at: row.closed_at,
            defer_until: row.defer_until,
        }
    }
}

/// bd omits a field it has nothing for, and `#[serde(default)]` covers that.
/// It does not extend to an explicit null. A tracker is read whole, so a row
/// bd wrote the other way costs not one bead's edges but every bead in that
/// project.
fn none_is_empty<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<RowDependency>, D::Error> {
    Ok(Option::<Vec<RowDependency>>::deserialize(d)?.unwrap_or_default())
}

/// bd spells an absent parent three ways — `""`, `null`, or no field — and
/// they all mean the top of a chain.
fn empty_is_none<'de, D: Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
    Ok(Option::<String>::deserialize(d)?.filter(|parent| !parent.is_empty()))
}

/// A field bd wrote as null holds what a field bd left out holds: nothing.
fn null_is_default<'de, D, T>(d: D) -> Result<T, D::Error>
where
    D: Deserializer<'de>,
    T: Deserialize<'de> + Default,
{
    Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
}

/// A row whose status is null claims no status, which is outside bd's set
/// rather than any member of it. bdi says that on the screen instead of
/// picking a status the row does not claim.
fn null_is_unrecognised<'de, D: Deserializer<'de>>(d: D) -> Result<Status, D::Error> {
    Ok(Option::<Status>::deserialize(d)?.unwrap_or_else(|| Status::Other(String::new())))
}

/// A bead's metadata is whatever JSON was written into it, and bdi draws it
/// as text. So each value is read as the text it prints as, and a value that
/// is not a string costs nothing.
///
/// bd wrote the object itself as a string spelling one until April 2026, so
/// a tracker that straddles that date holds rows of both shapes and both are
/// read here. Anything else bd could write there — a null, a number, a string
/// spelling something that is not an object — is read as no metadata.
///
/// A tracker is read whole, so the alternative is not a bead without its
/// badge — it is every bead in that project, gone.
fn text_of_each_value<'de, D: Deserializer<'de>>(
    d: D,
) -> Result<BTreeMap<String, String>, D::Error> {
    Ok(Option::<serde_json::Value>::deserialize(d)?
        .as_ref()
        .and_then(object_written_either_way)
        .map(|fields| text_of_each(fields.into_owned()))
        .unwrap_or_default())
}

/// The object a value holds, for a value that is one — either written as an
/// object, or written as a string spelling one, which is how bd wrote a bead's
/// metadata until April 2026.
fn object_written_either_way(
    value: &serde_json::Value,
) -> Option<std::borrow::Cow<'_, serde_json::Map<String, serde_json::Value>>> {
    match value {
        serde_json::Value::Object(fields) => Some(std::borrow::Cow::Borrowed(fields)),
        serde_json::Value::String(spelled) => match serde_json::from_str(spelled) {
            Ok(serde_json::Value::Object(fields)) => Some(std::borrow::Cow::Owned(fields)),
            _ => None,
        },
        _ => None,
    }
}

fn text_of_each(fields: serde_json::Map<String, serde_json::Value>) -> BTreeMap<String, String> {
    fields
        .into_iter()
        .map(|(key, value)| match value {
            serde_json::Value::String(text) => (key, text),
            written => (key, written.to_string()),
        })
        .collect()
}

/// One row of `bd blocked --json`, which carries a blocker set no dep-tree
/// row has.
#[derive(Deserialize)]
struct BlockedRow {
    id: String,
    #[serde(default)]
    blocked_by: Vec<String>,
}

/// bd's CLI, reaching every project's tracker through one runner.
pub struct Cli<'r> {
    runner: &'r dyn Runner,
    /// The credential the shell `bdi` was launched from holds, which a
    /// project configuring none reaches its tracker on. Read once: the shell
    /// `bdi` was launched from does not change while it runs.
    ambient: Option<String>,
    /// The projects whose tracker refused the probe: bd's embedded Dolt has
    /// no server for `bd sql` to reach, and says so the same way on every
    /// refresh. Found out once per project, from the refusal itself, so the
    /// probe is paid for once per run rather than once per refresh.
    without_a_probe: Mutex<BTreeSet<String>>,
}

impl<'r> Cli<'r> {
    pub fn new(runner: &'r dyn Runner) -> Self {
        Self {
            runner,
            ambient: environment::ambient_credential(),
            without_a_probe: Mutex::default(),
        }
    }
}

impl Trackers for Cli<'_> {
    fn of(&self, project: &Project) -> Result<Box<dyn Tracker + '_>, OpenFailure> {
        let env = environment::tracker_env(self.runner, project, self.ambient.as_deref())?;
        Ok(Box::new(Reader {
            runner: self.runner,
            name: project.name.clone(),
            path: project.path.clone(),
            env,
            without_a_probe: &self.without_a_probe,
        }))
    }
}

/// One project's tracker as bd reads it: in the project's directory, with the
/// environment its config asked for.
struct Reader<'r> {
    runner: &'r dyn Runner,
    name: String,
    path: PathBuf,
    env: Env,
    /// The run's memory of which projects' trackers refused the probe,
    /// shared with every reader the run opens.
    without_a_probe: &'r Mutex<BTreeSet<String>>,
}

impl Reader<'_> {
    /// One answer out of the tracker.
    ///
    /// `-C` names the tracker outright, and it outranks `BEADS_DIR` in both
    /// directions: a wrong variable still resolves the project, and a wrong
    /// directory is refused rather than resolved to something plausible. That
    /// is what makes entering the directory safe, because direnv can quietly
    /// do nothing. Clearing the inherited variables stays as well; together
    /// they mean a misconfiguration fails loudly.
    ///
    /// Every subcommand composed here is a read, and that rests on the command
    /// lines below rather than on bd. It is not why `bdi` never writes to a
    /// tracker, because bd writes to one on its own account: it rewrites
    /// `.beads/.local_version` and runs its schema auto-migration on finding
    /// itself newer than the bd that last opened that tracker, before the
    /// subcommand runs and whatever the subcommand is. `docs/design.md`'s
    /// *Reading a tracker is not leaving it alone* carries the measurement.
    /// `--readonly` vetoes bd's mutating subcommands,
    /// so a mutating call arriving here later is refused rather than run — a
    /// guard on the next edit, and a veto over subcommands rather than a
    /// property of the tracker's files. `sql` is outside even that: it is a
    /// general executor, bd's own help for it warns that direct database
    /// access bypasses the storage layer, and `--readonly` does not veto it —
    /// measured against this project's own tracker on 2026-09-01. What holds
    /// there instead is `WORKING_ROOT`, a constant nothing composes, reached
    /// from one method that takes no argument.
    fn asked(&self, subcommand: &[&str]) -> Result<String, RunFailure> {
        let named = self.path.to_string_lossy();
        let mut argv = vec!["-C", named.as_ref(), "--readonly"];
        argv.extend_from_slice(subcommand);
        self.runner
            .run("bd", &argv, Some(&self.path), &self.env)
            .map_err(|failure| failure.reading(subcommand[0]))
    }

    /// The tracker's Dolt working root: one hash over everything the
    /// database holds, committed or not.
    ///
    /// Not the committed head, because `bdi` reads wisps and the head cannot
    /// see them. `wisps` and `wisp_%` are in `dolt_ignore`, so they live in
    /// the working set and never reach `dolt_log` — measured against this
    /// project's own tracker on 2026-09-01, one `bd create --ephemeral` left
    /// `hashof('HEAD')` identical either side of it and moved this. A caller
    /// gating on the head would leave a wisp-only change off the screen until
    /// some unrelated write moved it.
    ///
    /// A read does not move it: three of these with a whole cascade between
    /// them answered the same hash, measured the same day. That is what makes
    /// it worth asking, because a hash that moved on being read would report
    /// a change every time and cost 0.2s to learn nothing.
    fn working_root(&self) -> Result<String, RunFailure> {
        let out = self.asked(&["sql", "--json", WORKING_ROOT])?;
        let rows: Vec<HashRow> =
            serde_json::from_str(&out).map_err(|e| RunFailure::parse("bd", e).reading("sql"))?;
        rows.into_iter()
            .next()
            .map(|row| row.h)
            .ok_or_else(|| RunFailure::parse("bd", "the answer holds no row").reading("sql"))
    }

    /// A tracker's wisps, closed ones included.
    ///
    /// A second call, because bd keeps its ephemeral beads in a table `bd
    /// list` does not read: measured against this project's own tracker on
    /// 2026-08-31, `bd list --all` answered 120 rows both before and after two
    /// wisps were written, and `bd list --wisp-type heartbeat` answered `[]`
    /// against a heartbeat wisp that existed. `bd query` is the one call that
    /// reads them, and it writes the same row `bd list` does.
    fn wisps(&self) -> Result<String, RunFailure> {
        self.asked(&["query", EPHEMERAL, "--all", "--limit", "0", "--json"])
    }
}

impl Tracker for Reader<'_> {
    /// bd over a Dolt server has a probe. bd over its embedded Dolt refuses
    /// it, and that refusal is what tells a tracker with no probe from a
    /// server that did not answer: the second is asked again next refresh,
    /// the first is remembered and never asked again this run.
    fn fingerprint(&self) -> Option<Result<String, RunFailure>> {
        if self.without_a_probe.lock().unwrap().contains(&self.name) {
            return None;
        }
        match self.working_root() {
            Err(failure) if failure.kind == FailureKind::Unsupported => {
                self.without_a_probe
                    .lock()
                    .unwrap()
                    .insert(self.name.clone());
                None
            }
            answer => Some(answer),
        }
    }

    /// One call per project rather than one per root, because a tree is
    /// drawn from dependency edges and `bd dep tree` cannot carry them: it
    /// walks dependents and dedupes, so what comes back is a spanning tree —
    /// each bead with the one edge the walk first reached it by, and every
    /// other edge into it missing. Measured against this project's own
    /// tracker on 2026-08-30, that walk carried 93 of the 176 edges among the
    /// beads it returned. It is also the reason `blocked` is asked for
    /// separately.
    ///
    /// `--all` is load-bearing: without it bd answers about open beads only,
    /// and a smaller correct-looking answer about a different population is
    /// the kind of wrong that reads as right.
    fn all(&self) -> Result<Vec<Bead>, RunFailure> {
        let out = self.asked(&["list", "--all", "--limit", "0", "--json"])?;
        let mut beads = rows(&out, "list")?;
        beads.extend(rows(&self.wisps()?, "query")?);
        Ok(beads)
    }

    /// bd computes readiness itself and treats it as a state of its own, so
    /// it is asked for rather than inferred from status.
    fn ready(&self) -> Result<BTreeSet<String>, RunFailure> {
        let out = self.asked(&["ready", "--limit", "0", "--json"])?;
        Ok(rows(&out, "ready")?
            .into_iter()
            .map(|bead| bead.id)
            .collect())
    }

    /// A dep-tree row carries its tree parent, not its blocker set: a bead
    /// blocked by two others appears once, under one of them, with the second
    /// nowhere in the output. `bd blocked` takes no limit of its own.
    fn blocked(&self) -> Result<BTreeMap<String, Vec<String>>, RunFailure> {
        let out = self.asked(&["blocked", "--json"])?;
        let blocked: Vec<BlockedRow> = serde_json::from_str(&out)
            .map_err(|e| RunFailure::parse("bd", e).reading("blocked"))?;
        Ok(blocked
            .into_iter()
            .map(|row| (row.id, row.blocked_by))
            .collect())
    }
}

/// The whole of the SQL `bdi` writes.
///
/// `dolt_hashof_db()` answers for the database bd is already connected to, as
/// one row and one column. `SHOW VARIABLES LIKE '%_working'` reaches the same
/// hash and is worse three ways: it answers for every attached database at
/// once, `skip_networking` matches that pattern as well, and the `@@` form
/// cannot be quoted through `bd sql` because a database name may hold a
/// hyphen.
const WORKING_ROOT: &str = "SELECT dolt_hashof_db() AS h";

/// The one row `WORKING_ROOT` answers with.
#[derive(Deserialize)]
struct HashRow {
    h: String,
}

/// The `bd query` expression that selects wisps and nothing else.
const EPHEMERAL: &str = "ephemeral=true";

/// `bd list`, `bd ready` and `bd query` all answer with the same rows, and
/// each names itself so a reader is sent back to the one that broke.
///
/// The root cause rather than the whole chain: `parse_beads` wraps the
/// parser's account in a sentence saying the answer was not understood, which
/// is what the phrase around this already says.
fn rows(out: &str, read: &str) -> Result<Vec<Bead>, RunFailure> {
    parse_beads(out).map_err(|e| RunFailure::parse("bd", e.root_cause()).reading(read))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::types::{Dependency, Edge, Status};

    const FIXTURE: &str = include_str!("../../tests/fixtures/bd_list.json");

    fn fixture() -> Vec<Bead> {
        parse_beads(FIXTURE).expect("the captured rows parse")
    }

    fn row(id: &str) -> Bead {
        fixture()
            .into_iter()
            .find(|b| b.id == id)
            .unwrap_or_else(|| panic!("{id} is in the fixture"))
    }

    #[test]
    fn parses_every_row() {
        assert_eq!(fixture().len(), 7);
    }

    const JOINED: &str = include_str!("../../tests/fixtures/joined_bd_list.json");

    /// The bead as `bd show` gives it is in the rows `bd list` already
    /// writes, so showing one costs no further call. Asserted on a capture
    /// rather than a row typed here, because a key a capture carries is a
    /// measurement of what bd writes.
    #[test]
    fn a_captured_row_carries_the_description_the_notes_and_the_owner() {
        let rows = parse_beads(JOINED).expect("the captured rows parse");
        let bead = rows
            .iter()
            .find(|b| b.id == "orb-9fw")
            .expect("orb-9fw is in the capture");

        assert!(
            bead.description
                .as_deref()
                .is_some_and(|said| said.starts_with("`orbital` reads a repository")),
            "{:?}",
            bead.description
        );
        assert!(
            bead.notes
                .as_deref()
                .is_some_and(|said| said.starts_with("Correction to this bead's roster")),
            "{:?}",
            bead.notes
        );
        assert_eq!(bead.owner.as_deref(), Some("mira@orbital.invalid"));
    }

    /// bd leaves both out of a row that has neither, and a row it writes
    /// that way is a bead with nothing to say, not one that will not parse.
    #[test]
    fn a_row_without_a_description_or_notes_parses_with_neither() {
        let bead = row("bdi-2bb.4");

        assert_eq!(bead.description, None);
        assert_eq!(bead.notes, None);
    }

    /// A captured row names every bead it depends on, and the kinds differ
    /// within the one row: the tree cannot be built from the parent edges
    /// alone.
    #[test]
    fn a_captured_row_carries_every_edge_out_of_it() {
        assert_eq!(
            row("bdi-2bb.4").dependencies,
            vec![
                Dependency {
                    on: "bdi-2bb".to_string(),
                    edge: Edge::ParentChild,
                },
                Dependency {
                    on: "bdi-2bb.3".to_string(),
                    edge: Edge::Blocks,
                },
                Dependency {
                    on: "bdi-2bb.9".to_string(),
                    edge: Edge::Blocks,
                },
            ]
        );
    }

    #[test]
    fn statuses_map_onto_the_enum() {
        assert_eq!(row("bdi-r5l").status, Status::InProgress);
        assert_eq!(row("bdi-2bb").status, Status::Open);
        assert_eq!(row("bdi-2bb.9").status, Status::Closed);
    }

    #[test]
    fn every_status_spelling_bd_writes_is_recognised() {
        let spellings = ["open", "in_progress", "blocked", "closed", "deferred"];
        let expected = [
            Status::Open,
            Status::InProgress,
            Status::Blocked,
            Status::Closed,
            Status::Deferred,
        ];

        for (spelling, want) in spellings.iter().zip(expected) {
            let json = format!(r#"[{{"id":"x","title":"t","status":"{spelling}"}}]"#);
            assert_eq!(parse_beads(&json).unwrap()[0].status, want);
        }
    }

    #[test]
    fn a_status_a_later_bd_invents_is_kept_rather_than_rejected() {
        let json = r#"[{"id":"x","title":"t","status":"marinating"}]"#;
        let beads = parse_beads(json).expect("an unknown status still parses");
        assert_eq!(beads[0].status, Status::Other("marinating".to_string()));
    }

    #[test]
    fn an_edge_a_later_bd_invents_is_kept_rather_than_rejected() {
        let json = r#"[{"id":"x","title":"t","status":"open","dependencies":[
          {"depends_on_id":"y","type":"discovered-by"}]}]"#;
        let beads = parse_beads(json).expect("an unknown edge still parses");
        assert_eq!(
            beads[0].dependencies,
            vec![Dependency {
                on: "y".to_string(),
                edge: Edge::Other("discovered-by".to_string()),
            }]
        );
    }

    #[test]
    fn metadata_is_carried_inline_and_absent_metadata_is_an_empty_map() {
        let carrying = row("bdi-r5l");
        assert_eq!(
            carrying.metadata.get("agent_pane").map(String::as_str),
            Some("wCW:p2M")
        );

        assert!(row("bdi-2bb.3").metadata.is_empty());
    }

    /// A row's own fields travel beside its metadata, so a badge can read one
    /// bdi holds no field of its own for.
    #[test]
    fn a_rows_fields_are_carried_under_the_names_bd_spells_them() {
        let rows = r#"[
            {"id":"a","title":"t","status":"open","issue_type":"feature",
             "external_ref":"https://jira.invalid/browse/HELIO-412",
             "metadata":{"jira":"ATLAS-19","helio.ticket":"HELIO-9"}}
        ]"#;

        let fields = &parse_beads(rows).expect("the row parses")[0].values;

        assert_eq!(
            fields.get("external_ref").map(String::as_str),
            Some("https://jira.invalid/browse/HELIO-412")
        );
        assert_eq!(fields.get("id").map(String::as_str), Some("a"));
        assert_eq!(
            fields.get("issue_type").map(String::as_str),
            Some("feature")
        );
        assert_eq!(
            fields.get("metadata.jira").map(String::as_str),
            Some("ATLAS-19")
        );
        assert_eq!(
            fields.get("metadata.helio.ticket").map(String::as_str),
            Some("HELIO-9"),
            "a key holding a dot of its own is named by the whole of it"
        );
    }

    /// A value is what a badge draws, so a row carries the three kinds that
    /// are one. A null is the field unset and reads as the field being absent,
    /// which is what a badge on an unset field rests on: it would otherwise
    /// draw the four letters `null` on every bead of a tracker nothing syncs.
    /// An array and an object are not one value at all.
    #[test]
    fn a_row_carries_every_value_a_badge_could_draw_and_nothing_that_is_not_one() {
        let rows = r#"[
            {"id":"a","title":"t","status":"open","priority":1,"pinned":true,
             "external_ref":null,"parent":"",
             "dependencies":[{"depends_on_id":"b","type":"blocks"}],
             "metadata":{"jira":"ATLAS-19"}}
        ]"#;

        let fields = &parse_beads(rows).expect("the row parses")[0].values;

        assert_eq!(fields.get("priority").map(String::as_str), Some("1"));
        assert_eq!(fields.get("pinned").map(String::as_str), Some("true"));
        for absent in ["external_ref", "parent", "dependencies", "metadata"] {
            assert_eq!(fields.get(absent), None, "{absent} is no value to draw");
        }
    }

    /// A member of a field's object is judged by what it is, exactly as the
    /// field itself is. The metadata a bead carries is arbitrary JSON, so a
    /// member that is a list or an object of its own is the case this meets,
    /// and rendering one would put its braces on a row beside a title.
    #[test]
    fn a_member_of_an_object_is_one_value_on_the_same_terms_as_a_field() {
        let rows = r#"[
            {"id":"a","title":"t","status":"open",
             "metadata":{"attempts":3,"waiting":false,"phase":"vacuum-soak",
                         "cleared":null,"note":"",
                         "seats":["ada","grace"],"budget":{"hours":4}}}
        ]"#;

        let values = &parse_beads(rows).expect("the row parses")[0].values;

        assert_eq!(
            values.get("metadata.attempts").map(String::as_str),
            Some("3")
        );
        assert_eq!(
            values.get("metadata.waiting").map(String::as_str),
            Some("false")
        );
        assert_eq!(
            values.get("metadata.phase").map(String::as_str),
            Some("vacuum-soak")
        );
        for absent in [
            "metadata.cleared",
            "metadata.note",
            "metadata.seats",
            "metadata.budget",
        ] {
            assert_eq!(values.get(absent), None, "{absent} is no value to draw");
        }
    }

    /// A tracker's metadata is arbitrary JSON, and bdi draws it as text. A
    /// value that is not a string is read as the text it prints as, because
    /// a tracker is read whole and refusing one value loses every bead in it.
    ///
    /// Measured on a real tracker, 2026-08-31: two beads of 1886 carried
    /// `blocks_backstop_removal: true`, and the whole project failed to read.
    #[test]
    fn a_metadata_value_that_is_not_a_string_is_read_as_its_text() {
        let rows = r#"[
            {"id":"a","title":"t","status":"open",
             "metadata":{"blocks_backstop_removal":true}},
            {"id":"b","title":"t","status":"open",
             "metadata":{"attempts":3,"working_topic":"x"}}
        ]"#;

        let beads = parse_beads(rows).expect("one non-string value does not lose a tracker");

        assert_eq!(
            beads[0].metadata.get("blocks_backstop_removal"),
            Some(&"true".to_string())
        );
        assert_eq!(beads[1].metadata.get("attempts"), Some(&"3".to_string()));
        assert_eq!(
            beads[1].metadata.get("working_topic"),
            Some(&"x".to_string()),
            "a string keeps its own text, without the quotes JSON writes it in"
        );
    }

    /// bd wrote a bead's whole metadata object as a string spelling one until
    /// April 2026, and a tracker old enough to straddle that holds rows of
    /// both shapes.
    #[test]
    fn a_metadata_written_as_a_string_is_read_as_the_object_it_spells() {
        let rows = r#"[
            {"id":"a","title":"t","status":"open","metadata":"{}"},
            {"id":"b","title":"t","status":"open",
             "metadata":"{\"phase\":\"vacuum-soak\",\"attempts\":3}"}
        ]"#;

        let beads = parse_beads(rows).expect("a metadata written as a string still parses");

        assert!(beads[0].metadata.is_empty());
        assert_eq!(
            beads[1].metadata.get("phase"),
            Some(&"vacuum-soak".to_string())
        );
        assert_eq!(
            beads[1].metadata.get("attempts"),
            Some(&"3".to_string()),
            "a value inside the string is read the way one inside an object is"
        );
    }

    /// The other things that string could hold, and the other types the field
    /// could be written as, read as no metadata rather than being refused: a
    /// badge nobody can draw costs one bead, and a refusal costs the project.
    #[test]
    fn a_metadata_that_spells_no_object_is_read_as_none() {
        let rows = r#"[
            {"id":"a","title":"t","status":"open","metadata":"the sails"},
            {"id":"b","title":"t","status":"open","metadata":7}
        ]"#;

        let beads = parse_beads(rows).expect("neither costs the tracker it is in");

        assert!(beads[0].metadata.is_empty());
        assert!(beads[1].metadata.is_empty());
    }

    /// bd omits a field it has nothing for, and `#[serde(default)]` covers
    /// that. It does not extend to an explicit null, which is the same
    /// nothing written the other way.
    #[test]
    fn a_field_written_null_reads_as_the_field_bd_left_out() {
        let rows = r#"[{"id":"a","title":null,"status":"open",
                        "priority":null,"issue_type":null,"metadata":null,
                        "owner":null,"updated_at":null}]"#;

        let beads = parse_beads(rows).expect("a null field does not lose a tracker");

        assert_eq!(beads[0].title, "");
        assert_eq!(beads[0].priority, 0);
        assert_eq!(beads[0].issue_type, "");
        assert!(beads[0].metadata.is_empty());
    }

    /// A null status is not a status bd wrote, so bdi does not put one on the
    /// bead. It reads as a status outside bd's set, which the screen says it
    /// does not recognise — where reading it as `open` would have the bead
    /// claim a status nothing wrote.
    #[test]
    fn a_null_status_is_a_status_bdi_does_not_recognise() {
        let rows = r#"[{"id":"a","title":"t","status":null}]"#;

        let beads = parse_beads(rows).expect("a null status does not lose a tracker");

        assert_eq!(beads[0].status, Status::Other(String::new()));
    }

    /// Leniency about null is not leniency about absence. bd writes a title
    /// and a status on every row, so a listing with neither is a shape bdi
    /// does not understand rather than a row with nothing in those fields.
    #[test]
    fn a_row_that_names_no_title_or_no_status_is_still_an_error() {
        assert!(parse_beads(r#"[{"id":"a","status":"open"}]"#).is_err());
        assert!(parse_beads(r#"[{"id":"a","title":"t"}]"#).is_err());
    }

    #[test]
    fn the_timestamps_the_age_rules_need_follow_the_row() {
        let closed = row("bdi-2bb.9");
        assert!(closed.started_at.is_some());
        assert!(closed.closed_at.is_some());

        let open = row("bdi-2bb");
        assert_eq!(open.started_at, None);
        assert_eq!(open.closed_at, None);
        assert!(open.updated_at.is_some());
    }

    #[test]
    fn an_unclaimed_bead_has_no_assignee() {
        assert_eq!(row("bdi-2bb.9").assignee.as_deref(), Some("Graeme Foster"));
        assert_eq!(row("bdi-2bb").assignee, None);
    }

    #[test]
    fn issue_type_distinguishes_the_root_epic_from_its_tasks() {
        assert_eq!(row("bdi-2bb").issue_type, "epic");
        assert_eq!(row("bdi-2bb.9").issue_type, "task");
    }

    #[test]
    fn a_wrongly_typed_field_is_an_error_not_a_default() {
        let bad = r#"[{"id":"x","title":"t","status":"open","priority":"high"}]"#;
        assert!(parse_beads(bad).is_err());
    }

    #[test]
    fn work_in_flight_ranks_ahead_of_work_that_is_finished() {
        let mut statuses = vec![
            Status::Closed,
            Status::Open,
            Status::Other("marinating".to_string()),
            Status::InProgress,
            Status::Deferred,
            Status::Blocked,
        ];
        statuses.sort_by_key(Status::rank);

        assert_eq!(
            statuses,
            vec![
                Status::InProgress,
                Status::Blocked,
                Status::Open,
                Status::Deferred,
                Status::Closed,
                Status::Other("marinating".to_string()),
            ]
        );
        assert!(Status::Closed.is_closed());
        assert!(!Status::Open.is_closed());
    }

    use crate::collect::environment::CREDENTIAL_VAR;
    use crate::collect::run::testing::FakeRunner;
    use crate::collect::run::FailureKind;
    use crate::collect::tracker::Trackers;
    use crate::config::{Command, Project};
    use std::path::PathBuf;

    /// A project's directory, named so that nothing is ever there, for the
    /// reason `collect::environment`'s own says: an environment is detected
    /// from what the directory holds, so a path that exists would make these
    /// answer differently on a machine with direnv.
    fn project_dir() -> PathBuf {
        PathBuf::from("/nowhere/a-project")
    }

    /// A bd call as the runner spells it: the tracker named outright, and
    /// writes refused. Every call carries both, so the tests name the
    /// subcommand and this holds the invocation round it.
    fn spelled(subcommand: &str) -> String {
        format!("bd -C {} --readonly {subcommand}", project_dir().display())
    }

    fn credentialled() -> Env {
        Env::from([(CREDENTIAL_VAR.to_string(), "hunter2".to_string())])
    }

    /// The tracker under `project_dir()`, opened on its credential.
    fn opened(runner: &FakeRunner) -> Reader<'_> {
        Reader {
            runner,
            name: "atlas".to_string(),
            path: project_dir(),
            env: credentialled(),
            without_a_probe: Box::leak(Box::default()),
        }
    }

    /// A project entry as the config takes it by default: a path and nothing
    /// else, read in `bdi`'s own environment.
    fn ambient_project() -> Project {
        Project {
            name: "atlas".to_string(),
            path: project_dir(),
            environment_command: None,
            credential_command: None,
            poll: true,
            badges: Vec::new(),
            worktrees: Vec::new(),
        }
    }

    /// bd's CLI as `bdi` holds it when launched from a shell holding
    /// `ambient`, or from one holding no credential.
    fn launched_with<'a>(runner: &'a FakeRunner, ambient: Option<&str>) -> Cli<'a> {
        Cli {
            runner,
            ambient: ambient.map(str::to_string),
            without_a_probe: Mutex::default(),
        }
    }

    /// The wrapper a direnv setup names, written relative because the command
    /// runs in the project's own directory.
    const DIRENV: &str = "direnv exec .";

    /// The call that reproduces entering `project_dir()`: the configured
    /// wrapper with `bdi`'s own probe appended, through `sh`.
    fn entering_the_directory() -> String {
        format!("{DIRENV} env -0")
    }

    /// The seam's promise: a tracker opened for a project is read in the
    /// environment that project's config asks for, so nothing above the
    /// adapter threads an environment through its calls.
    #[test]
    fn a_tracker_opened_for_a_project_is_read_in_the_environment_its_config_asks_for() {
        let runner = FakeRunner::default()
            .with(
                &entering_the_directory(),
                "BEADS_DOLT_PASSWORD=the-projects-own-password",
            )
            .with(&spelled(TRACKER_CALL), FIXTURE)
            .with(&spelled(WISP_CALL), "[]");
        let project = Project {
            environment_command: Some(Command::Line(DIRENV.to_string())),
            ..ambient_project()
        };

        let cli = launched_with(&runner, Some("the-launching-shells-password"));
        let tracker = cli.of(&project).expect("the directory can be entered");
        tracker.all().expect("the tracker answers");

        let call = runner.call(&spelled(TRACKER_CALL));
        assert_eq!(call.cwd.as_deref(), Some(project_dir().as_path()));
        assert_eq!(
            call.env,
            Env::from([(
                CREDENTIAL_VAR.to_string(),
                "the-projects-own-password".to_string()
            )]),
            "the credential entering the directory produced is the one bd was given"
        );
    }

    /// A project that configures nothing is read on the credential the shell
    /// `bdi` was launched from holds, which the adapter captured once.
    #[test]
    fn a_project_configuring_nothing_is_read_on_the_ambient_credential() {
        let runner = FakeRunner::default().with(&spelled("ready --limit 0 --json"), "[]");

        let cli = launched_with(&runner, Some("hunter2"));
        let tracker = cli
            .of(&ambient_project())
            .expect("nothing is run to open an ambient project");
        tracker.ready().expect("the tracker answers");

        assert_eq!(
            runner.call(&spelled("ready --limit 0 --json")).env,
            credentialled()
        );
    }

    /// Opening is where the environment capture fails, and a project whose
    /// directory cannot be entered is that project's failure before bd is
    /// asked anything — the fake would panic on a bd call nobody staged.
    #[test]
    fn a_project_whose_directory_cannot_be_entered_fails_before_bd_is_asked_anything() {
        let runner = FakeRunner::default().failing(
            &entering_the_directory(),
            RunFailure::unstartable("direnv", "No such file or directory"),
        );
        let project = Project {
            environment_command: Some(Command::Line(DIRENV.to_string())),
            ..ambient_project()
        };

        let failure = launched_with(&runner, None)
            .of(&project)
            .err()
            .expect("the project cannot be opened");

        assert_eq!(failure, OpenFailure::NoEnvironment);
        assert!(
            runner
                .calls()
                .iter()
                .all(|call| !call.argv.starts_with("bd ")),
            "bd was asked something for a project that could not be opened"
        );
    }

    /// The one call a project's whole forest is drawn from, spelled as bd
    /// takes it. `--all` is what makes it the whole tracker rather than its
    /// open beads.
    const TRACKER_CALL: &str = "list --all --limit 0 --json";

    /// The second call the same forest needs, because `bd list` answers
    /// about the permanent table only.
    const WISP_CALL: &str = "query ephemeral=true --all --limit 0 --json";

    const WISPS: &str = include_str!("../../tests/fixtures/bd_wisps.json");

    /// The whole invocation the probe makes, spelled out rather than built
    /// from the constant it asserts about: this is the one place `bdi` writes
    /// SQL, and a change to that statement should have to be made twice.
    const PROBE_CALL: &str = "sql --json SELECT dolt_hashof_db() AS h";

    /// A working root as this tracker's Dolt server answers with one,
    /// captured 2026-09-01.
    const A_WORKING_ROOT: &str = "24eg8eff89bggt3t50ft6lctiu9rlpts";

    #[test]
    fn the_working_root_is_one_hash_out_of_one_statement() {
        let runner = FakeRunner::default().with(
            &spelled(PROBE_CALL),
            &format!(r#"[{{"h":"{A_WORKING_ROOT}"}}]"#),
        );

        let root = opened(&runner)
            .fingerprint()
            .expect("bd has a probe")
            .expect("the tracker answered its working root");

        assert_eq!(root, A_WORKING_ROOT);
        assert_eq!(
            runner.call(&spelled(PROBE_CALL)).env,
            credentialled(),
            "the probe reaches the tracker on the project's own credential"
        );
    }

    /// bd's refusal of the probe on a store that cannot run it, as the runner
    /// classifies it.
    fn cannot_run_the_probe() -> RunFailure {
        RunFailure {
            kind: FailureKind::Unsupported,
            program: "bd".to_string(),
            detail: "bd cannot run that against this tracker".to_string(),
            unreadable: None,
        }
    }

    /// A Dolt server that did not answer the probe, as the runner classifies
    /// it.
    fn did_not_answer_the_probe() -> RunFailure {
        RunFailure {
            kind: FailureKind::Unavailable,
            program: "bd".to_string(),
            detail: "bd could not reach the tracker".to_string(),
            unreadable: None,
        }
    }

    /// How many times the probe was run against `project_dir()`.
    fn probes(runner: &FakeRunner) -> usize {
        runner
            .calls()
            .iter()
            .filter(|call| call.argv == spelled(PROBE_CALL))
            .count()
    }

    /// bd's default store is its embedded Dolt, which refuses `bd sql`, and
    /// the refusal is the same on every refresh. So a tracker found to have
    /// no probe is read in full from then on without the probe being paid
    /// for again: one failing bd process per project per run, not per
    /// refresh.
    #[test]
    fn a_tracker_found_to_have_no_probe_is_not_probed_again_that_run() {
        let runner = FakeRunner::default().failing(&spelled(PROBE_CALL), cannot_run_the_probe());
        let cli = launched_with(&runner, None);
        let project = ambient_project();

        let first = cli.of(&project).expect("opened").fingerprint();
        let second = cli.of(&project).expect("opened").fingerprint();

        assert!(
            first.is_none(),
            "the refusal is a tracker with no probe: {first:?}"
        );
        assert!(second.is_none(), "and stays one: {second:?}");
        assert_eq!(probes(&runner), 1, "the probe was paid for once");
    }

    /// A Dolt server that is down answers the probe with nothing, and comes
    /// back. That is a probe worth asking again, and it is not remembered:
    /// a run that took an outage for "no probe" would never take the fast
    /// path again once the server was up.
    #[test]
    fn a_server_that_did_not_answer_the_probe_is_probed_again_on_the_next_refresh() {
        let runner =
            FakeRunner::default().failing(&spelled(PROBE_CALL), did_not_answer_the_probe());
        let cli = launched_with(&runner, None);
        let project = ambient_project();

        for refresh in 1..=2 {
            let failure = cli
                .of(&project)
                .expect("opened")
                .fingerprint()
                .expect("a server has a probe")
                .expect_err("the server did not answer");
            assert_eq!(failure.kind, FailureKind::Unavailable);
            assert_eq!(probes(&runner), refresh, "one probe per refresh");
        }
    }

    /// What is remembered is which tracker has no probe, not that the run
    /// has stopped probing: a second project on a Dolt server is probed as
    /// ever alongside one that refused.
    #[test]
    fn no_probe_is_remembered_for_the_tracker_that_refused_and_not_its_neighbours() {
        let harbour = Project {
            name: "harbour".to_string(),
            path: PathBuf::from("/tmp/harbour"),
            ..ambient_project()
        };
        let harbours_probe = format!("bd -C {} --readonly {PROBE_CALL}", harbour.path.display());
        let runner = FakeRunner::default()
            .failing(&spelled(PROBE_CALL), cannot_run_the_probe())
            .with(&harbours_probe, &format!(r#"[{{"h":"{A_WORKING_ROOT}"}}]"#));
        let cli = launched_with(&runner, None);

        assert!(cli
            .of(&ambient_project())
            .expect("opened")
            .fingerprint()
            .is_none());
        let root = cli
            .of(&harbour)
            .expect("opened")
            .fingerprint()
            .expect("harbour's server has a probe")
            .expect("and answered it");

        assert_eq!(root, A_WORKING_ROOT);
    }

    /// An answer with no row is a tracker that cannot be compared against,
    /// not a tracker that has not moved — so it fails rather than answering
    /// something a caller would gate on.
    #[test]
    fn a_probe_that_answers_no_row_is_a_failure_rather_than_a_hash() {
        let runner = FakeRunner::default().with(&spelled(PROBE_CALL), "[]");

        let failure = opened(&runner)
            .fingerprint()
            .expect("bd has a probe")
            .expect_err("no row is no answer");

        assert_eq!(failure.kind, FailureKind::Parse);
    }

    /// A tracker with no `dolt_hashof_db` — a SQLite-backed one — answers
    /// with something this cannot read, and that is a failure the caller has
    /// to see rather than a hash it would compare against.
    #[test]
    fn a_probe_answering_something_else_is_a_failure_rather_than_a_hash() {
        let runner = FakeRunner::default().with(&spelled(PROBE_CALL), "no such function");

        let failure = opened(&runner)
            .fingerprint()
            .expect("bd has a probe")
            .expect_err("an answer that is not the row is no answer");

        assert_eq!(failure.kind, FailureKind::Parse);
    }

    #[test]
    fn the_tracker_is_read_in_the_projects_directory_with_its_credential() {
        let runner = FakeRunner::default()
            .with(&spelled(TRACKER_CALL), FIXTURE)
            .with(&spelled(WISP_CALL), "[]");

        let beads = opened(&runner).all().unwrap();

        assert_eq!(beads.len(), 7);
        for subcommand in [TRACKER_CALL, WISP_CALL] {
            let call = runner.call(&spelled(subcommand));
            assert_eq!(call.cwd.as_deref(), Some(project_dir().as_path()));
            assert_eq!(call.env, credentialled());
        }
    }

    /// `bd list` answers about the permanent table, so it returns no wisp at
    /// all — not under `--all`, and not under its own `--wisp-type` filter.
    /// A tracker read only that way draws none of them.
    #[test]
    fn a_tracker_answers_with_its_wisps_as_well_as_its_permanent_beads() {
        let runner = FakeRunner::default()
            .with(&spelled(TRACKER_CALL), FIXTURE)
            .with(&spelled(WISP_CALL), WISPS);

        let beads = opened(&runner).all().unwrap();

        let ids: Vec<&str> = beads.iter().map(|bead| bead.id.as_str()).collect();
        assert!(
            ids.contains(&"bdi-7ao.17.2"),
            "the wisp under a bead: {ids:?}"
        );
        assert!(
            ids.contains(&"bdi-wisp-w3m"),
            "the free-standing wisp: {ids:?}"
        );
        assert_eq!(beads.len(), 9, "both answers, neither replacing the other");
    }

    /// bd omits a field it has nothing for rather than writing it as null:
    /// measured across the 73 ephemeral rows of a tracker on 2026-08-31,
    /// eleven keys are universal and every other one is absent when empty.
    /// So this row is not a shape bd writes today. It is covered because
    /// `#[serde(default)]` does not extend to an explicit null, and a
    /// tracker is read whole — a single row bd wrote differently would cost
    /// every bead in that project rather than its own edges.
    #[test]
    fn a_row_naming_its_dependencies_as_null_still_parses() {
        let json = r#"[{"id":"nix-wisp-gvi","title":"t","status":"open",
                        "issue_type":"molecule","parent":null,"dependencies":null}]"#;

        let bead = &parse_beads(json).expect("the row parses")[0];

        assert_eq!(bead.dependencies, vec![]);
    }

    /// A wisp bd writes under a parent is a child like any other: a dotted id
    /// and a real parent-child edge. One written without a parent has neither,
    /// so nothing but root discovery can place it.
    #[test]
    fn a_wisp_carries_the_edge_that_hangs_it_under_a_bead_where_it_has_one() {
        let wisps = parse_beads(WISPS).expect("the captured wisps parse");
        let by_id = |id: &str| {
            wisps
                .iter()
                .find(|wisp| wisp.id == id)
                .unwrap_or_else(|| panic!("{id} is in the fixture"))
                .clone()
        };

        assert_eq!(
            by_id("bdi-7ao.17.2").dependencies,
            vec![Dependency {
                on: "bdi-7ao.17".to_string(),
                edge: Edge::ParentChild,
            }]
        );
        assert_eq!(by_id("bdi-wisp-w3m").dependencies, vec![]);
    }

    /// One completed molecule and its sixteen steps, from a real wisp run on
    /// another project's tracker. It is here as evidence of what bd writes,
    /// which a constant somebody typed cannot be: the author of a constant
    /// supplies the keys they remember, so a key absent from a capture is a
    /// measurement and a key absent from a constant is authorship.
    ///
    /// Its two-row neighbour is not replaced by it. That one carries a
    /// free-standing wisp under no parent, which a molecule run has none of.
    ///
    /// Every `title` in it is invented, and says so in its own value. The
    /// capture arrived without the key: the redaction dropped `title`,
    /// `description`, `notes`, `owner`, `created_by`, `assignee`,
    /// `close_reason` and `dependencies[].created_by` whole, because one
    /// close reason named a person. `Bead::title` is required, so the file
    /// could not be parsed without one. Nothing else was touched — key order
    /// is the capture's and no value it carried was rewritten. Assert on a
    /// title and you are asserting on something we made up.
    const MOLECULE: &str = include_str!("../../tests/fixtures/bd_wisp_molecule.json");

    /// A row bd writes carries keys bdi does not read, and the ones bd will
    /// write next are not knowable. `await_type`, on the gate step of this
    /// run, is one nothing else in the tree has — which is the point of
    /// keeping a capture rather than a constant, because a constant carries
    /// only the keys its author already knew about.
    ///
    /// That `Bead` ignores such a key rather than rejecting the row is held
    /// by most of this module already. What is held here is the evidence:
    /// tidying the capture down to the fields bdi reads is what this refuses,
    /// because the untidy keys are the measurement.
    ///
    /// The counts go with it so a file shortened by accident is noticed. They
    /// are not evidence of anything — a run of any length can be typed.
    #[test]
    fn the_capture_keeps_a_field_bdi_does_not_read() {
        let run = parse_beads(MOLECULE).expect("the captured molecule parses");

        assert!(
            MOLECULE.contains(r#""await_type""#),
            "the capture still carries the key this is about"
        );
        assert_eq!(run.len(), 17, "the molecule and its steps");
        assert_eq!(
            run.iter()
                .map(|bead| bead.dependencies.len())
                .sum::<usize>(),
            37,
            "the edges bd wrote between them"
        );
        assert_eq!(
            run.iter()
                .filter(|bead| bead.issue_type == "molecule")
                .count(),
            1
        );
    }

    /// bd omits a field it has nothing for rather than writing it as null,
    /// which is what lets every field bdi reads carry `#[serde(default)]`.
    /// That is a claim about a program we do not own, so this holds the
    /// evidence for it: seventeen rows and their thirty-seven edges as bd
    /// wrote them, with no null anywhere — including on the molecule, which
    /// omits `parent` and `dependencies` rather than nulling them.
    ///
    /// It goes red if a later bd starts writing nulls, which is the day
    /// `none_is_empty` stops being enough.
    #[test]
    fn bd_omits_what_it_has_nothing_for_rather_than_writing_null() {
        let rows: serde_json::Value = serde_json::from_str(MOLECULE).expect("the capture is json");

        fn nulls(value: &serde_json::Value, at: &str, found: &mut Vec<String>) {
            match value {
                serde_json::Value::Null => found.push(at.to_string()),
                serde_json::Value::Object(fields) => {
                    for (key, field) in fields {
                        nulls(field, &format!("{at}.{key}"), found);
                    }
                }
                serde_json::Value::Array(items) => {
                    for (i, item) in items.iter().enumerate() {
                        nulls(item, &format!("{at}[{i}]"), found);
                    }
                }
                _ => {}
            }
        }

        let mut found = Vec::new();
        nulls(&rows, "", &mut found);

        assert_eq!(found, Vec::<String>::new(), "nulls bd wrote");
    }

    #[test]
    fn a_row_carries_every_bead_it_depends_on_and_the_kind_of_each() {
        let json = r#"[{"id":"p-1.4","title":"t","status":"open","dependencies":[
          {"issue_id":"p-1.4","depends_on_id":"p-1","type":"parent-child"},
          {"issue_id":"p-1.4","depends_on_id":"p-1.3","type":"blocks"}]}]"#;
        let bead = &parse_beads(json).expect("the row parses")[0];

        assert_eq!(
            bead.dependencies,
            vec![
                Dependency {
                    on: "p-1".to_string(),
                    edge: Edge::ParentChild,
                },
                Dependency {
                    on: "p-1.3".to_string(),
                    edge: Edge::Blocks,
                },
            ]
        );
    }

    #[test]
    fn ready_ids_returns_the_set_bd_considers_startable() {
        let out = r#"[{"id":"p-1.1","title":"a","status":"open"},
                      {"id":"p-1.3","title":"b","status":"open"}]"#;
        let runner = FakeRunner::default().with(&spelled("ready --limit 0 --json"), out);

        let got = opened(&runner).ready().unwrap();

        assert!(got.contains("p-1.1"));
        assert!(got.contains("p-1.3"));
        assert!(
            !got.contains("p-1.4"),
            "a bead bd did not list is not ready"
        );
    }

    /// The shape a real tracker produces: a bead blocked by two beads, whose
    /// dep-tree row names only one of them.
    #[test]
    fn blocked_by_carries_every_blocker_not_only_the_one_the_tree_shows() {
        let out = r#"[{"id":"p-1.9","title":"a","status":"blocked","blocked_by_count":2,
                       "blocked_by":["p-1.2","p-1.5"]},
                      {"id":"p-1.11","title":"b","status":"open","blocked_by_count":1,
                       "blocked_by":["p-1.10"]}]"#;
        let runner = FakeRunner::default().with(&spelled("blocked --json"), out);

        let got = opened(&runner).blocked().unwrap();

        assert_eq!(
            got.get("p-1.9").map(Vec::as_slice),
            Some(["p-1.2".to_string(), "p-1.5".to_string()].as_slice())
        );
        assert_eq!(got.len(), 2);
        assert_eq!(got.get("p-1.1"), None);
    }

    #[test]
    fn a_tracker_that_refuses_the_credential_reaches_the_caller_classified() {
        let runner = FakeRunner::default().failing(
            &spelled(TRACKER_CALL),
            RunFailure {
                kind: FailureKind::Auth,
                program: "bd".to_string(),
                detail: "bd was refused the tracker's credential".to_string(),
                unreadable: None,
            },
        );

        let failure = opened(&runner).all().unwrap_err();

        assert_eq!(failure.kind, FailureKind::Auth);
    }

    /// Which read broke and where in its answer, because that is the whole
    /// of what a reader can do about one: run that read themselves and go to
    /// the row the parser stopped at. The kind alone sends them to a tracker
    /// with five reads in it and no way to tell which.
    #[test]
    fn a_listing_that_will_not_parse_names_the_read_and_where_it_broke() {
        let row = r#"[{"id":"atl-1","title":42,"status":"open"}]"#;
        let runner = FakeRunner::default().with(&spelled(TRACKER_CALL), row);

        let unreadable = opened(&runner)
            .all()
            .unwrap_err()
            .unreadable
            .expect("a parse failure knows what would not parse");

        assert_eq!(unreadable.read, "list");
        assert_eq!(
            unreadable.cause,
            "invalid type: integer `42`, expected a string at line 1 column 25"
        );
    }

    /// The wisps are a second read of the same rows, and a reader sent to
    /// `bd list` for a row `bd query` answered with looks at an answer that
    /// holds no such row.
    #[test]
    fn a_wisp_that_will_not_parse_names_the_read_that_carried_it() {
        let row = r#"[{"id":"atl-2","title":42,"status":"open"}]"#;
        let runner = FakeRunner::default()
            .with(&spelled(TRACKER_CALL), "[]")
            .with(&spelled(WISP_CALL), row);

        let unreadable = opened(&runner)
            .all()
            .unwrap_err()
            .unreadable
            .expect("a parse failure knows what would not parse");

        assert_eq!(unreadable.read, "query");
    }

    /// Bytes that are not UTF-8 refuse before any row is looked at, so the
    /// read is named by the call that composed the command line rather than
    /// by the parser.
    #[test]
    fn an_answer_that_is_not_text_names_the_read_it_came_from() {
        let runner = FakeRunner::default().failing(
            &spelled("blocked --json"),
            RunFailure::parse("bd", "invalid utf-8 sequence of 1 bytes from index 3"),
        );

        let unreadable = opened(&runner)
            .blocked()
            .unwrap_err()
            .unreadable
            .expect("a parse failure knows what would not parse");

        assert_eq!(unreadable.read, "blocked");
    }

    #[test]
    fn output_bd_could_not_have_written_is_a_parse_failure_not_an_unreachable_tracker() {
        let runner = FakeRunner::default().with(&spelled("blocked --json"), "not json at all");

        let failure = opened(&runner).blocked().unwrap_err();

        assert_eq!(failure.kind, FailureKind::Parse);
    }

    /// The whole of the invocation, in one test because the two halves are
    /// one fact: bd is told which tracker to read, and told it may not write
    /// to it. Asserting the tracker alone would pass with the writes still
    /// allowed.
    #[test]
    fn every_call_names_the_tracker_outright_and_refuses_writes() {
        let runner = FakeRunner::default()
            .with(&spelled(TRACKER_CALL), FIXTURE)
            .with(&spelled(WISP_CALL), "[]");

        opened(&runner).all().unwrap();

        for call in runner.calls() {
            let after_the_program = call
                .argv
                .strip_prefix("bd ")
                .unwrap_or_else(|| panic!("{} is not a bd call", call.argv));
            assert!(
                after_the_program
                    .starts_with(&format!("-C {} --readonly ", project_dir().display())),
                "the tracker is left to the working directory in: {}",
                call.argv
            );
        }
    }

    /// A captured row carries the bead's own parent, which is the one the
    /// walk to a root needs: a dep-tree row's `parent_id` is the traversal's.
    #[test]
    fn a_captured_row_carries_the_bead_it_hangs_under() {
        assert_eq!(row("bdi-2bb.4").parent.as_deref(), Some("bdi-2bb"));
        assert_eq!(row("bdi-2bb").parent.as_deref(), Some("bdi-7ao"));
    }

    /// bd writes a root's absent parent as `null`; the dep tree writes the
    /// same absence as `""`, and an older bd omitted the field. All three
    /// mean the same thing.
    #[test]
    fn a_root_has_no_parent_however_bd_spells_the_absence() {
        for spelling in [r#","parent":null"#, r#","parent":"""#, ""] {
            let out = format!(r#"[{{"id":"p-1","title":"a","status":"open"{spelling}}}]"#);

            assert_eq!(
                parse_beads(&out).expect("the row parses")[0].parent,
                None,
                "on {spelling:?}"
            );
        }
    }
}