beads_rust 0.5.10

Agent-first issue tracker (SQLite + JSONL)
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
//! `br.doctor.capabilities.v1` — machine-readable doctor contract.
//!
//! WP1 emits a *foundation* capabilities document describing the
//! contract surface AI agents can rely on. Concretely:
//!
//! - `doctor_version` — `CARGO_PKG_VERSION`
//! - `contract_version` — `"1"` (frozen for WP1)
//! - `exit_codes` — derived from [`super::exit_codes::DoctorExitCode::all`]
//! - `write_scopes` — `.beads/`, `.doctor/`
//! - `env_vars` — environment variables the doctor honors
//! - `fixers` — currently wired repair/refuse paths
//! - `detectors` — currently wired flat-doctor check IDs
//!
//! Stability: the JSON shape is stable contract. New fields are
//! purely additive; agents must tolerate unknown keys.

#![allow(dead_code)] // WP1 foundation; consumed by WP3-WP12.

use std::path::Path;

use serde::Serialize;

use super::exit_codes::DoctorExitCode;

/// Single exit-code dictionary entry.
#[derive(Debug, Clone, Serialize)]
pub struct ExitCodeEntry {
    /// Numeric exit value.
    pub code: i32,
    /// Stable kebab-case name.
    pub name: &'static str,
    /// Short human description.
    pub description: &'static str,
}

/// Top-level capabilities document.
#[derive(Debug, Clone, Serialize)]
pub struct DoctorCapabilities {
    /// Always `"br.doctor.capabilities"`.
    pub schema: &'static str,
    /// Always `"1"` for the WP1 contract.
    pub contract_version: &'static str,
    /// `CARGO_PKG_VERSION` of the running binary.
    pub doctor_version: &'static str,
    /// The structured exit-code dictionary.
    pub exit_codes: Vec<ExitCodeEntry>,
    /// Workspace-relative directories the doctor may write under
    /// `--repair`. WP1 ships `.beads/` and `.doctor/`; future WPs may
    /// extend.
    pub write_scopes: Vec<String>,
    /// Environment variables the doctor honors. Documented in
    /// `playbook.md` §1.4.
    pub env_vars: Vec<&'static str>,
    /// Fixer registry populated from the currently wired repair/refuse paths.
    pub fixers: Vec<FixerEntry>,
    /// Detector registry populated from the currently wired flat-doctor checks.
    pub detectors: Vec<DetectorEntry>,
    /// Names of every [`super::mutate::Op`] variant the chokepoint
    /// supports plus the parameters each takes. Stable contract: the
    /// names are kebab-case to match `actions.jsonl` `op` values, the
    /// `params` array enumerates the field names a fixer must supply.
    pub ops_supported: Vec<OpEntry>,
    /// Pass-3 finding-id schema unification (`diagnostic_specificity`).
    /// Maps each emitted `check.name` value to its canonical
    /// `fm-<subsystem>-<slug>` identifier from the Phase-1
    /// archaeology. Agents tooling around `br doctor --json` can
    /// translate either way:
    ///
    /// ```jq
    /// .checks[].name as $n
    /// | (.. | .finding_id_map[]? | select(.check_name == $n) | .finding_id) // null
    /// ```
    ///
    /// Stable contract: rows are additive. Unmapped check names
    /// (scaffolding / not-yet-classified) carry no entry rather
    /// than a synthetic placeholder.
    pub finding_id_map: Vec<FindingIdEntry>,
}

/// One row in the check-name → FM-id map.
#[derive(Debug, Clone, Serialize)]
pub struct FindingIdEntry {
    pub check_name: &'static str,
    pub finding_id: &'static str,
}

/// One row in the supported-ops list. Matches the variants in
/// [`super::mutate::Op`] one-for-one so the capabilities envelope
/// surfaces the exact contract a fixer can call into.
#[derive(Debug, Clone, Serialize)]
pub struct OpEntry {
    /// Stable kebab-case name (matches `actions.jsonl` `op` values).
    pub name: &'static str,
    /// Human-readable summary.
    pub summary: &'static str,
    /// Field names the variant requires (informational; agents should
    /// still read the Rust source for the authoritative shape).
    pub params: Vec<&'static str>,
    /// `true` when the op is wired all the way through the chokepoint;
    /// `false` flags ops that ship with safety scaffolding only (e.g.
    /// [`super::mutate::Op::DbMigrate`] until the schema.rs hook lands).
    pub fully_routed: bool,
}

/// One row in the fixer registry. Stable shape.
#[derive(Debug, Clone, Serialize)]
pub struct FixerEntry {
    pub id: String,
    pub subsystem: String,
    pub auto_fixable: bool,
    pub mutates: bool,
    pub addressed_findings: Vec<String>,
    /// The `fm-<subsystem>-<slug>` id(s) this fixer's `--only`/`--skip`
    /// gate consults (`FixerFilter::allows`). This — not
    /// `finding_id_map`, which speaks check-name vocabulary — is the
    /// authoritative vocabulary for the `--only`/`--skip` flags: an
    /// `--only` list disables every fixer whose ids it omits. Empty for
    /// refuse gates, which are not filterable.
    pub filter_ids: Vec<String>,
}

/// One row in the detector registry. Stable shape.
#[derive(Debug, Clone, Serialize)]
pub struct DetectorEntry {
    pub id: String,
    pub subsystem: String,
    pub severity_default: String,
    pub fast_path: bool,
}

impl DoctorCapabilities {
    /// Build a fresh capabilities document. Pure (no I/O).
    #[must_use]
    pub fn build() -> Self {
        let exit_codes = DoctorExitCode::all()
            .iter()
            .map(|code| ExitCodeEntry {
                code: code.as_i32(),
                name: code.as_str(),
                description: code.description(),
            })
            .collect();

        Self {
            schema: "br.doctor.capabilities",
            contract_version: "1",
            doctor_version: env!("CARGO_PKG_VERSION"),
            exit_codes,
            write_scopes: vec![".beads/".into(), ".doctor/".into()],
            env_vars: vec![
                super::run_dir::ENV_RUNS_DIR,
                "BR_NO_AUTOFLUSH",
                "BD_NO_AUTOFLUSH",
                "RUST_LOG",
                "BD_DB",
                "BEADS_JSONL",
            ],
            fixers: build_fixer_registry(),
            detectors: build_detector_registry(),
            ops_supported: vec![
                OpEntry {
                    name: "write_file",
                    summary: "Atomic create-or-overwrite via tmpfile + rename(2).",
                    params: vec!["content", "mode"],
                    fully_routed: true,
                },
                OpEntry {
                    name: "append_file",
                    summary: "Append-only write; creates the file if missing.",
                    params: vec!["content"],
                    fully_routed: true,
                },
                OpEntry {
                    name: "rename",
                    summary: "Move a path within write_scopes (no Op::Delete by design).",
                    params: vec!["to"],
                    fully_routed: true,
                },
                OpEntry {
                    name: "chmod",
                    summary: "Set the mode bits of a path.",
                    params: vec!["mode"],
                    fully_routed: true,
                },
                OpEntry {
                    name: "symlink_atomic",
                    summary: "Replace the symlink at path with one pointing at target.",
                    params: vec!["target"],
                    fully_routed: true,
                },
                OpEntry {
                    name: "db_exec",
                    summary: "Run a parameterized SQL statement inside BEGIN IMMEDIATE; \
                              snapshots affected rows to backups/db/ before COMMIT.",
                    params: vec!["sql", "args", "affected_tables", "affected_predicate"],
                    fully_routed: true,
                },
                OpEntry {
                    name: "db_migrate",
                    summary: "Versioned schema migration. Verifies PRAGMA user_version \
                              matches `from`, snapshots the DB file verbatim to \
                              backups/db/beads.db.pre-migrate, then drives \
                              schema::run_migrations_atomic inside BEGIN IMMEDIATE / COMMIT \
                              (rolls back + restores from snapshot on failure).",
                    params: vec!["from", "to"],
                    fully_routed: true,
                },
            ],
            finding_id_map: build_finding_id_map(),
        }
    }

    /// Render to pretty JSON (stable key order via `serde_json` map
    /// iteration).
    ///
    /// # Errors
    ///
    /// Returns [`serde_json::Error`] on serialization failure (effectively
    /// never with the data shapes used here).
    pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    /// Convenience: render against an arbitrary repo root for callers
    /// that want absolute scope paths. Currently a no-op aside from
    /// validation. Reserved for future extension.
    #[must_use]
    pub fn build_for_repo(_repo_root: &Path) -> Self {
        Self::build()
    }
}

/// Detector registry — populated from the canonical `check_*` family
/// in `src/cli/commands/doctor.rs`. Phase 10 cold-prober finding
/// (`beads_rust-3idn`): a cold agent reading
/// `br doctor capabilities --format json` previously saw `detectors:
/// []` and read it as "the contract is half-wired". This list pins
/// the agent-visible name of every detector the flat `br doctor`
/// surface runs, so consumers can build allow-lists, `--only`/`--skip`
/// selectors (future), and `--quick` parity tables against it.
///
/// `fast_path: true` flags the detectors the `--quick` mode keeps
/// (cheap stat / parse / single-PRAGMA checks); `false` flags the
/// ones `--quick` drops for sub-second pre-commit latency.
type DetectorRow = (&'static str, &'static str, &'static str, bool);

const DETECTOR_ROWS: &[DetectorRow] = &[
    ("beads_dir", "configs", "error", true),
    ("metadata", "configs", "error", true),
    ("gitignore.beads_inner", "configs", "warn", true),
    ("gitignore.root", "configs", "warn", true),
    ("routes_jsonl", "routes_external", "warn", true),
    ("routes.targets", "routes_external", "warn", true),
    ("rust_log", "observability", "warn", true),
    ("permissions.beads_dir", "permissions", "warn", true),
    ("config.yaml", "configs", "warn", true),
    ("config.unknown_keys", "configs", "warn", true),
    ("metadata.json", "configs", "warn", true),
    ("binary_version", "external_artifacts", "warn", true),
    ("write_lock", "concurrency_primitives", "warn", true),
    ("jsonl.parse", "state_files", "error", true),
    ("jsonl.merge_artifacts", "state_files", "warn", true),
    ("base_jsonl", "state_files", "warn", true),
    (
        "base_jsonl.missing_post_flush",
        "state_files",
        "warn",
        false,
    ),
    ("dirty_bitmap", "caches_indexes", "warn", false),
    ("doctor.runs_dir", "observability", "warn", true),
    ("doctor.runs_creatable", "permissions", "warn", true),
    ("permissions.recovery_dir", "permissions", "warn", true),
    ("permissions.write_lock", "permissions", "warn", true),
    ("permissions.root_gitignore", "permissions", "warn", true),
    ("permissions.db_sidecars", "permissions", "warn", true),
    ("jsonl.duplicate_ids", "state_files", "warn", false),
    ("comments.orphans", "caches_indexes", "warn", false),
    ("labels.orphans", "caches_indexes", "warn", false),
    ("dependencies.orphans", "caches_indexes", "warn", false),
    (
        "permissions.config_yaml_secrets",
        "permissions",
        "warn",
        true,
    ),
    ("br_path_dupes", "external_artifacts", "warn", true),
    ("gitignore.beads_inner_present", "configs", "warn", true),
    (
        "permissions.jsonl_world_writable",
        "permissions",
        "warn",
        true,
    ),
    ("tmp_files_orphan", "state_files", "warn", true),
    ("jsonl_size", "state_files", "warn", true),
    ("br_history.size", "state_files", "warn", true),
    ("jsonl_eof_newline", "state_files", "warn", true),
    ("jsonl_crlf", "state_files", "warn", true),
    ("jsonl_bom", "state_files", "warn", true),
    ("db_bloat", "caches_indexes", "warn", true),
    ("wal_size", "state_files", "warn", true),
    ("startup_cache.health", "configs", "warn", true),
    ("sync_jsonl_path", "state_files", "warn", true),
    ("sync_conflict_markers", "state_files", "error", true),
    ("db.exists", "state_files", "error", true),
    ("db.open", "state_files", "error", true),
    ("db.sidecars", "state_files", "error", true),
    (
        "db.read_only_open_observational",
        "state_files",
        "warn",
        true,
    ),
    ("db.recovery_artifacts", "state_files", "info", true),
    ("db.recovery_artifacts.aged", "state_files", "warn", true),
    ("db.foreign_recovery_debris", "state_files", "info", true),
    ("db.export_hash_cache", "caches_indexes", "warn", true),
    ("schema.tables", "schemas", "error", true),
    ("schema.columns", "schemas", "error", true),
    ("schema.inspect", "schemas", "error", true),
    ("db.null_defaults", "schemas", "warn", true),
    ("sqlite.integrity_check", "state_files", "error", true),
    // --quick drops these:
    ("db.recoverable_anomalies", "caches_indexes", "warn", false),
    ("counts.db_vs_jsonl", "state_files", "warn", false),
    ("sync.metadata", "state_files", "warn", false),
    ("sqlite3.integrity_check", "state_files", "error", false),
    ("db.write_probe", "state_files", "warn", false),
    (
        "audit.suspect_close_reasons",
        "agent_coordination",
        "warn",
        true,
    ),
];

fn build_detector_registry() -> Vec<DetectorEntry> {
    DETECTOR_ROWS
        .iter()
        .map(|(id, subsystem, sev, fast)| DetectorEntry {
            id: (*id).to_string(),
            subsystem: (*subsystem).to_string(),
            severity_default: (*sev).to_string(),
            fast_path: *fast,
        })
        .collect()
}

/// Fixer registry — one entry per `repair_*` path currently wired in
/// `src/cli/commands/doctor.rs`. Phase 10 cold-prober finding
/// (`beads_rust-3idn`): with this populated, an agent can list every
/// fixer the doctor can apply under `--repair` without reading source.
///
/// `auto_fixable: true` means `--repair` will attempt the fix without
/// further prompts; `false` reserved for advisory-only / refuse paths
/// and fixers that need an explicit opt-in flag beyond `--repair`.
/// `mutates: true` means the fixer routes writes through the
/// `mutate()` chokepoint (per WP1+WP3 contract); `false` flags the
/// few legacy paths that still bypass the chokepoint (see
/// `beads_rust-8fud` for the migration plan). The final element is the
/// fixer's `--only`/`--skip` filter-id set (see
/// [`FixerEntry::filter_ids`]); the drift gate
/// `every_fixer_filter_gate_id_is_advertised_in_capabilities` in
/// `doctor.rs` keeps it in sync with the `FixerFilter::allows` call
/// sites.
type FixerRow = (
    &'static str,
    &'static str,
    bool,
    bool,
    &'static [&'static str],
    &'static [&'static str],
);

const EARLY_CHOKEPOINT_FIXER_ROWS: &[FixerRow] = &[
    (
        "doctor.gitignore_repair",
        "configs",
        true,
        true,
        &["gitignore.beads_inner", "gitignore.root"],
        &["fm-configs-gitignore-leaking-beads"],
    ),
    (
        "doctor.merge_artifact_quarantine",
        "state_files",
        true,
        true,
        &["jsonl.merge_artifacts"],
        &["fm-state_files-merge-artifact-stuck"],
    ),
    (
        "doctor.startup_cache_quarantine",
        "configs",
        true,
        true,
        &["startup_cache.health"],
        &["fm-configs-startup-cache-poisoned"],
    ),
    (
        "doctor.recovery_artifacts_aged_quarantine",
        "state_files",
        true,
        true,
        &["db.recovery_artifacts.aged"],
        &["fm-state_files-recovery-artifacts-orphaned"],
    ),
    (
        "doctor.export_hash_cache_repair",
        "caches_indexes",
        true,
        true,
        &["db.export_hash_cache"],
        &["fm-caches_indexes-export-hash-cache-divergence"],
    ),
    (
        "doctor.base_jsonl_symlink_quarantine",
        "state_files",
        true,
        true,
        &["base_jsonl"],
        &["fm-state_files-base-jsonl-missing-or-stale"],
    ),
    (
        "doctor.base_jsonl_regen",
        "state_files",
        true,
        true,
        &["base_jsonl"],
        &["fm-state_files-base-jsonl-missing-or-stale"],
    ),
    (
        "doctor.orphan_tmp_quarantine",
        "state_files",
        true,
        true,
        &["tmp_files_orphan"],
        &["fm-state_files-orphan-tmp-files"],
    ),
    (
        "doctor.jsonl_trailing_newline_append",
        "state_files",
        true,
        true,
        &["jsonl_eof_newline"],
        &["fm-state_files-jsonl-missing-trailing-newline"],
    ),
    (
        "doctor.jsonl_bom_strip",
        "state_files",
        true,
        true,
        &["jsonl_bom"],
        &["fm-state_files-jsonl-utf8-bom-prefix"],
    ),
    (
        "doctor.jsonl_crlf_to_lf",
        "state_files",
        true,
        true,
        &["jsonl_crlf"],
        &["fm-state_files-jsonl-crlf-line-endings"],
    ),
    (
        "doctor.jsonl_world_writable_chmod",
        "permissions",
        true,
        true,
        &["permissions.jsonl_world_writable"],
        &["fm-permissions-jsonl-world-writable"],
    ),
    (
        "doctor.config_yaml_secret_chmod",
        "permissions",
        true,
        true,
        &["permissions.config_yaml_secrets"],
        &["fm-permissions-config-yaml-mode-leaks-secrets"],
    ),
    (
        "doctor.db_sidecar_mode_chmod",
        "permissions",
        true,
        true,
        &["permissions.db_sidecars"],
        &["fm-permissions-db-sidecar-mode-too-open"],
    ),
    (
        "doctor.inner_gitignore_append",
        "configs",
        true,
        true,
        &["gitignore.beads_inner_present"],
        &["fm-configs-gitignore-leaking-beads"],
    ),
    (
        "doctor.dirty_bitmap_orphan_prune",
        "caches_indexes",
        true,
        true,
        &["dirty_bitmap"],
        &["fm-caches_indexes-dirty-bitmap-divergence"],
    ),
    (
        "doctor.comments_orphan_prune",
        "caches_indexes",
        true,
        true,
        &["comments.orphans"],
        &["fm-caches_indexes-comments-orphans"],
    ),
    (
        "doctor.labels_orphan_prune",
        "caches_indexes",
        true,
        true,
        &["labels.orphans"],
        &["fm-caches_indexes-labels-orphans"],
    ),
    (
        "doctor.dependencies_orphan_prune",
        "caches_indexes",
        true,
        true,
        &["dependencies.orphans"],
        &["fm-caches_indexes-dependencies-orphans"],
    ),
    (
        "doctor.wal_checkpoint_truncate",
        "state_files",
        true,
        true,
        &["wal_size"],
        &["fm-state_files-wal-oversized"],
    ),
    // Pass-8 cycle 61: backfill schema-declared defaults into NULL
    // NOT-NULL columns via Op::DbExec (previously missing from the
    // registry entirely — beads_rust-oow2).
    (
        "doctor.null_defaults_backfill",
        "schemas",
        true,
        true,
        &["db.null_defaults"],
        &["fm-schemas-missing-required-column"],
    ),
];

const fn early_chokepoint_fixer_rows() -> &'static [FixerRow] {
    EARLY_CHOKEPOINT_FIXER_ROWS
}

fn legacy_fixer_rows() -> &'static [FixerRow] {
    &[
        (
            "doctor.repair_recoverable_db_state",
            "caches_indexes",
            true,
            false,
            &["db.recoverable_anomalies", "db.sidecars"],
            &[
                "fm-caches_indexes-blocked-cache-stale",
                "fm-state_files-wal-shm-sidecar-orphan",
            ],
        ),
        // The partial-index REINDEX pass repairs "row N missing from
        // index" warnings, which surface under the integrity checks —
        // not `db.recoverable_anomalies` (corrected: beads_rust-oow2).
        (
            "doctor.repair_partial_indexes",
            "caches_indexes",
            true,
            false,
            &["sqlite.integrity_check", "sqlite3.integrity_check"],
            &["fm-caches_indexes-partial-index-stale"],
        ),
        (
            "doctor.repair_via_vacuum",
            "state_files",
            true,
            false,
            &["sqlite.integrity_check", "sqlite3.integrity_check"],
            &["fm-state_files-sqlite-page-malformed"],
        ),
        // Pass-10 cycle 62: VACUUM on db bloat. Requires the explicit
        // `--unsafe-auto-fix` opt-in on top of `--repair`, hence
        // auto_fixable=false (previously missing from the registry
        // entirely — beads_rust-oow2).
        (
            "doctor.db_bloat_vacuum",
            "caches_indexes",
            false,
            false,
            &["db_bloat"],
            &["fm-caches_indexes-db-bloat-vs-jsonl"],
        ),
    ]
}

fn rebuild_fixer_rows() -> &'static [FixerRow] {
    &[
        (
            "doctor.repair_database_from_jsonl",
            "state_files",
            true,
            true,
            &[
                "db.open",
                "counts.db_vs_jsonl",
                "schema.tables",
                "schema.columns",
            ],
            &[
                "fm-state_files-jsonl-row-count-mismatch",
                "fm-state_files-empty-or-truncated-database",
                "fm-state_files-sqlite-page-malformed",
                "fm-schemas-missing-required-table",
                "fm-schemas-missing-required-column",
                "fm-caches_indexes-blocked-cache-stale",
            ],
        ),
        (
            "doctor.repair_database_sidecars",
            "state_files",
            true,
            true,
            &["db.sidecars"],
            &["fm-state_files-wal-shm-sidecar-orphan"],
        ),
    ]
}

fn refuse_gate_fixer_rows() -> &'static [FixerRow] {
    &[
        (
            "refuse_gates.schema_version_downgrade",
            "schemas",
            false,
            false,
            &["schema.columns"],
            &[],
        ),
        (
            "refuse_gates.recovery_fingerprint_integrity",
            "state_files",
            false,
            false,
            &["db.recovery_artifacts"],
            &[],
        ),
    ]
}

fn fixer_entry_from_row(row: &FixerRow) -> FixerEntry {
    let (id, subsystem, auto_fixable, mutates, addressed, filter_ids) = *row;
    FixerEntry {
        id: id.to_string(),
        subsystem: subsystem.to_string(),
        auto_fixable,
        mutates,
        addressed_findings: addressed.iter().map(|s| (*s).to_string()).collect(),
        filter_ids: filter_ids.iter().map(|s| (*s).to_string()).collect(),
    }
}

fn build_fixer_registry() -> Vec<FixerEntry> {
    // (id, subsystem, auto_fixable, mutates_via_chokepoint,
    //  addressed_findings, filter_ids)
    early_chokepoint_fixer_rows()
        .iter()
        .chain(legacy_fixer_rows())
        .chain(rebuild_fixer_rows())
        .chain(refuse_gate_fixer_rows())
        .map(fixer_entry_from_row)
        .collect()
}

/// Build the check-name → finding-id map from the canonical table in
/// `super::super::doctor::CHECK_NAME_TO_FINDING_ID`. Pass-3 gap item
/// #3 (`diagnostic_specificity`): every agent reading
/// `br doctor --json` should be able to translate a check.name to
/// its stable `fm-<subsystem>-<slug>` identifier without
/// out-of-band knowledge.
fn build_finding_id_map() -> Vec<FindingIdEntry> {
    super::super::doctor::CHECK_NAME_TO_FINDING_ID
        .iter()
        .map(|(check_name, finding_id)| FindingIdEntry {
            check_name,
            finding_id,
        })
        .collect()
}

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

    #[test]
    fn capabilities_builds_with_expected_shape() {
        let caps = DoctorCapabilities::build();
        assert_eq!(caps.schema, "br.doctor.capabilities");
        assert_eq!(caps.contract_version, "1");
        assert_eq!(caps.doctor_version, env!("CARGO_PKG_VERSION"));
        assert!(!caps.exit_codes.is_empty());
        // Healthy / RefusedUnsafe / IoError must always be present.
        let mut codes: Vec<i32> = caps.exit_codes.iter().map(|e| e.code).collect();
        codes.sort_unstable();
        assert!(codes.contains(&0));
        assert!(codes.contains(&4));
        assert!(codes.contains(&74));
        // Scopes are non-empty.
        assert!(caps.write_scopes.contains(&".beads/".to_string()));
        assert!(caps.write_scopes.contains(&".doctor/".to_string()));
        // Env vars include the run-dir override.
        assert!(caps.env_vars.contains(&super::super::run_dir::ENV_RUNS_DIR));
    }

    #[test]
    fn capabilities_is_stable_json() {
        let caps = DoctorCapabilities::build();
        let json = caps.to_pretty_json().expect("json");
        let parsed: serde_json::Value = serde_json::from_str(&json).expect("parse");
        assert_eq!(parsed["schema"], "br.doctor.capabilities");
        assert_eq!(parsed["contract_version"], "1");
        assert!(parsed["exit_codes"].is_array());
        assert!(parsed["fixers"].is_array());
        assert!(parsed["detectors"].is_array());
        // WP4: ops_supported must enumerate the chokepoint contract.
        let ops = parsed["ops_supported"]
            .as_array()
            .expect("ops_supported array");
        assert!(
            ops.iter()
                .any(|o| o["name"] == "db_exec" && o["fully_routed"] == true),
            "db_exec must be advertised as fully routed"
        );
        assert!(
            ops.iter()
                .any(|o| o["name"] == "db_migrate" && o["fully_routed"] == true),
            "db_migrate must be advertised as fully routed (beads_rust-folg)"
        );
        for op in ops {
            assert!(op["params"].is_array(), "op.params must be an array: {op}");
        }
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn capabilities_detectors_and_fixers_are_populated() {
        // Phase 10 cold-prober finding (`beads_rust-3idn`): a cold
        // agent must see the actual detector + fixer registries, not
        // empty arrays. Lock the floor so future refactors can't
        // silently drop entries back to [].
        let caps = DoctorCapabilities::build();
        assert!(
            !caps.detectors.is_empty(),
            "detector registry must enumerate the check_* family"
        );
        assert!(
            !caps.fixers.is_empty(),
            "fixer registry must enumerate the repair_* family"
        );
        // Canonical entries must be present.
        let detector_ids: Vec<&str> = caps.detectors.iter().map(|d| d.id.as_str()).collect();
        let mut sorted_detector_ids = detector_ids.clone();
        sorted_detector_ids.sort_unstable();
        sorted_detector_ids.dedup();
        assert_eq!(
            sorted_detector_ids.len(),
            detector_ids.len(),
            "detector registry must not contain duplicate ids"
        );
        for required in &[
            "gitignore.beads_inner",
            "jsonl.parse",
            "db.open",
            "sqlite.integrity_check",
            "schema.tables",
        ] {
            assert!(
                detector_ids.contains(required),
                "detector registry missing {required}"
            );
        }
        for obsolete in &["merge_artifacts", "sqlite.cli_integrity"] {
            assert!(
                !detector_ids.contains(obsolete),
                "detector registry must not advertise obsolete check id {obsolete}"
            );
        }
        let detector = |id: &str| {
            caps.detectors
                .iter()
                .find(|d| d.id == id)
                .unwrap_or_else(|| panic!("missing detector {id}"))
        };
        assert_eq!(detector("jsonl.merge_artifacts").severity_default, "warn");
        assert_eq!(detector("schema.inspect").severity_default, "error");
        let fixer_ids: Vec<&str> = caps.fixers.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(
            fixer_ids,
            vec![
                "doctor.gitignore_repair",
                "doctor.merge_artifact_quarantine",
                "doctor.startup_cache_quarantine",
                "doctor.recovery_artifacts_aged_quarantine",
                "doctor.export_hash_cache_repair",
                "doctor.base_jsonl_symlink_quarantine",
                "doctor.base_jsonl_regen",
                "doctor.orphan_tmp_quarantine",
                "doctor.jsonl_trailing_newline_append",
                "doctor.jsonl_bom_strip",
                "doctor.jsonl_crlf_to_lf",
                "doctor.jsonl_world_writable_chmod",
                "doctor.config_yaml_secret_chmod",
                "doctor.db_sidecar_mode_chmod",
                "doctor.inner_gitignore_append",
                "doctor.dirty_bitmap_orphan_prune",
                "doctor.comments_orphan_prune",
                "doctor.labels_orphan_prune",
                "doctor.dependencies_orphan_prune",
                "doctor.wal_checkpoint_truncate",
                "doctor.null_defaults_backfill",
                "doctor.repair_recoverable_db_state",
                "doctor.repair_partial_indexes",
                "doctor.repair_via_vacuum",
                "doctor.db_bloat_vacuum",
                "doctor.repair_database_from_jsonl",
                "doctor.repair_database_sidecars",
                "refuse_gates.schema_version_downgrade",
                "refuse_gates.recovery_fingerprint_integrity",
            ],
            "fixer registry order is part of the stable capabilities JSON"
        );
        for required in &[
            "doctor.gitignore_repair",
            "doctor.merge_artifact_quarantine",
            "doctor.repair_via_vacuum",
            "doctor.repair_database_from_jsonl",
            "refuse_gates.schema_version_downgrade",
        ] {
            assert!(
                fixer_ids.contains(required),
                "fixer registry missing {required}"
            );
        }
        // Every detector must declare a subsystem the existing checks
        // recognize.
        for d in &caps.detectors {
            assert!(
                !d.subsystem.is_empty(),
                "detector {} missing subsystem",
                d.id
            );
        }
        // At least one fixer must route through the chokepoint (WP3+).
        assert!(
            caps.fixers.iter().any(|f| f.mutates),
            "at least one fixer must route through mutate()"
        );
    }
}