* fix(configfile): carry graph_mode and graph_* binding through Save Graph-preview builds of bd persist a per-workspace format in metadata.json: "graph_mode": "link" plus graph_scope_url, graph_authority_id, graph_workspace, graph_schema_version and graph_ready, beside an ordinary Dolt backend. configfile.Config had no such fields, so every Save, and Load's config.json -> metadata.json migration, rewrote the file without them, turning a graph workspace's metadata into an ordinary Issue workspace's. Config now carries the marker and the binding as omitempty fields, so a Save round-trips them unchanged and metadata.json written for an ordinary workspace is byte-for-byte what it was. GetGraphMode resolves the marker: absent or "dependency" is the historical default, "link" is recognized, and any other value is an error rather than a fallback to the Issue store. Nothing in this build opens a non-default mode; the CLI refusal follows in the next commit. Ported from the donnabox fork commit deea8d57df (graph_mode.go, graph_mode_test.go and the configfile.go fields), without any graph code. The binding-survives-Save and omitted-from-ordinary-metadata tests are new. Co-authored-by: Donna Box <dbox@boxenllc.com> Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(cli): refuse graph_mode workspaces before opening them A workspace whose metadata.json declares a graph_mode other than "dependency" holds a graph database behind an ordinary Dolt backend, and nothing else in its metadata says so. bd admitted it like any current workspace: `bd list` ran the Issue schema initialization against the graph database (beads_graph_<id>), `bd init --force` wrote a .gitignore and a .beads/dolt root into it, `bd dolt start` started a server for it, and `bd doctor` reported on it as an Issue store. guardLegacyUpgradeWorkspace, the admission check every store-opening command, store-less command with workspace effects, init, doctor and bootstrap already run before touching a workspace, now refuses such a workspace first, before the legacy classifications that would admit it or report it as a legacy store to migrate. An unknown graph_mode value is refused the same way. The refusal is a typed error naming the workspace and the format, rendered with a hint (as JSON under --json) and exit code 16, ExitUnsupportedWorkspaceFormat, so a wrapper can tell "needs a different bd build" from a generic failure. `bd version`, `bd --version`, `bd help` and completion stay exempt, as they are for legacy workspaces. validateConfiguredBackend refuses the same metadata, which covers the store-open paths that skip command admission (routed writes, cross-repository reads, create --repo). Tests: guard and store-factory unit tests; a subprocess e2e test that show/list/create/context/where/dolt start/doctor/bootstrap/init are refused with exit 16 and leave .beads byte-identical (metadata.json and legacy config.json, link and unknown markers, embedded and server layouts), and that store-less commands still run; an embedded test that an ordinary workspace, with the marker absent or "dependency", still creates and lists issues and keeps the marker through a metadata.json rewrite. The guard hunk and graph_mode_admission_e2e_test.go are ported from the donnabox fork commit deea8d57df; the exit code, rendering, store factory backstop and remaining tests are new. Co-authored-by: Donna Box <dbox@boxenllc.com> Agent-Signature: claude-code-claude-opus-5-5-unknown-reasoning on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(cli): refuse graph workspaces reached outside command admission Command admission refuses a graph_mode workspace a command runs in, but bd also reaches workspaces before or without admission: a create --repo target, the path --db or BEADS_DB names, and the stores the factories open for routed and cross-repository work. On those paths a workspace marked only by a legacy config.json was changed before anything refused it: configfile.Load migrates config.json into metadata.json before the format check sees the loaded metadata, and create --repo initialized such a target as a new workspace. Where the refusal did come, create reported it with exit 1 rather than 16. - checkDiscoveredWorkspaceFormat checks a workspace's metadata as configfile.LoadForDiscovery reads it, which never rewrites it. ensureBeadsDirForPath, the dry-run target open and the four store factories (cgo and nocgo builds) run it before their own load. - resolveBeadsDirForDBPath and findDatabaseInBeadsDir locate a workspace with LoadForDiscovery, so resolving --db, BEADS_DB or a create target no longer migrates it. - bd create renders a refused target as the workspace refusal, exit 16 with its hint, on the initializing and both dry-run paths. A dry run without --parent opens no target, so it now checks a local one before rendering the preview (checkRepoTargetFormat). - bd bootstrap, when discovery finds no workspace, reads each .beads from the working directory up to the repository root without migrating it and refuses one in a format this build cannot open, the way commands without a workspace already do. A .beads marked only by config.json is passed over by discovery, so bootstrap reported "no workspace" there instead of exit 16. The walk now returns its candidates (undiscoveredWorkspaceCandidates) to both checks: handing it the check as a func(string) error made gosec's G702 taint analysis connect BEADS_DIR to every func(string) error that runs git. - backendNameForErrorFraming reads with LoadForDiscovery, and loadDoltBackendConfig, bd dolt status and bd dolt show refuse a graph workspace before their migrating configfile.Load. Admission refuses first on every path that reaches them today; this keeps a new caller from migrating a legacy config.json before the refusal. - The CHANGELOG entry and the configfile comment now claim what holds: a routed read fails without touching a graph workspace but not with code 16, and a Save keeps only the known graph_* fields, with the tags graph-preview builds declare. workspace_gate.go no longer lists the pre-gate discovery reads as migrating. - New e2e rows run create --repo from a workspace and from outside one, create --dry-run with and without --parent, --db, BEADS_DB, init --proxied-server, bootstrap in a workspace nested in a graph one, and the hook shim's bd hooks run pre-commit against every fixture; each refusal must exit 16 and name the format and the hint. bootstrap in a workspace marked only by config.json now refuses like the other commands. The store factory test also runs on a config.json graph workspace, TestWorkspaceMetadataReadersLeaveGraphWorkspaceUnchanged covers the framing, bd dolt loader and diagnostic reads, and TestNocgoStoreFactoriesRefuseGraphWorkspace covers the CGO_ENABLED=0 factories; bazel.yml's pure lane runs it by name (PURE_CMD_BD_TESTS, pinned in scripts/ci_workflow_test.go). Measured with gocyclo/gocognit: every function this changes stays below the PR's worst changed function (guardLegacyUpgradeWorkspaceForInit 29/28, resolveBeadsDirForDBPath 26/36); showDoltConfig is 19/31 (was 18/30) and guardUndiscoveredLegacyWorkspace 3/3 (was 9/12). Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Donna Box <dbox@boxenllc.com> Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Co-authored-by: Eddie the Engineer <338826946+gascity-eddie[bot]@users.noreply.github.com>
1620 lines
65 KiB
Go
1620 lines
65 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/spf13/cobra"
|
|
"github.com/steveyegge/beads/cmd/bd/doctor"
|
|
"github.com/steveyegge/beads/internal/configfile"
|
|
"github.com/steveyegge/beads/internal/metrics"
|
|
"github.com/steveyegge/beads/internal/ui"
|
|
)
|
|
|
|
// Status constants for doctor checks
|
|
const (
|
|
statusOK = "ok"
|
|
statusWarning = "warning"
|
|
statusError = "error"
|
|
)
|
|
|
|
type doctorCheck struct {
|
|
Name string `json:"name"`
|
|
Status string `json:"status"` // statusOK, statusWarning, or statusError
|
|
Message string `json:"message"`
|
|
Detail string `json:"detail,omitempty"` // Additional detail like storage type
|
|
Fix string `json:"fix,omitempty"`
|
|
Category string `json:"category,omitempty"` // category for grouping in output
|
|
}
|
|
|
|
type doctorResult struct {
|
|
Path string `json:"path"`
|
|
Checks []doctorCheck `json:"checks"`
|
|
OverallOK bool `json:"overall_ok"`
|
|
CLIVersion string `json:"cli_version"`
|
|
Timestamp string `json:"timestamp,omitempty"` // ISO8601 timestamp for historical tracking
|
|
Platform map[string]string `json:"platform,omitempty"` // platform info for debugging
|
|
SuppressedCount int `json:"suppressed_count,omitempty"` // GH#1095: number of suppressed warnings
|
|
}
|
|
|
|
var (
|
|
doctorFix bool
|
|
doctorYes bool
|
|
doctorInteractive bool // per-fix confirmation mode
|
|
doctorDryRun bool // preview fixes without applying
|
|
doctorOutput string // export diagnostics to file
|
|
doctorFixChildParent bool // opt-in fix for child→parent deps
|
|
doctorVerbose bool // show detailed output during fixes
|
|
perfMode bool
|
|
checkHealthMode bool
|
|
doctorCheckFlag string // run specific check (e.g., "pollution")
|
|
doctorClean bool // for pollution check, delete detected issues
|
|
doctorDeep bool // full graph integrity validation
|
|
doctorOrchestrator bool // running in orchestrator multi-workspace mode
|
|
orchestratorDuplicatesThreshold int // duplicate tolerance threshold for orchestrator mode
|
|
doctorServer bool // run server mode health checks
|
|
doctorMigration string // migration validation mode: "pre" or "post"
|
|
doctorAgent bool // agent-facing diagnostic mode (ZFC-compliant)
|
|
)
|
|
|
|
// ConfigKeyHintsDoctor is the config key for suppressing doctor hints
|
|
const ConfigKeyHintsDoctor = "hints.doctor"
|
|
|
|
var doctorCmd = &cobra.Command{
|
|
Use: "doctor [path]",
|
|
GroupID: "maint",
|
|
// doctor diagnoses installation health and must run without opening the
|
|
// store. It opts out of store init via the annotation seam rather than the
|
|
// noDbCommands list (see commandOptsOutOfStore in main.go).
|
|
Annotations: map[string]string{skipStoreAnnotation: "1"},
|
|
Short: "Check and fix beads installation health (start here)",
|
|
Long: `Sanity check the beads installation for the current directory or specified path.
|
|
|
|
This command checks:
|
|
- If .beads/ directory exists
|
|
- Database version and migration status
|
|
- Schema compatibility (all required tables and columns present)
|
|
- Whether using hash-based vs sequential IDs
|
|
- If CLI version is current (checks GitHub releases)
|
|
- If Claude plugin is current (when running in Claude Code)
|
|
- File permissions
|
|
- Circular dependencies
|
|
- Git hooks (pre-commit, post-merge, pre-push)
|
|
- .beads/.gitignore up to date
|
|
- Metadata.json version tracking (LastBdVersion field)
|
|
|
|
Storage Availability:
|
|
Full diagnostics, --perf, --deep, --server, --migration, and
|
|
--check=validate currently require Dolt server mode. Embedded Dolt
|
|
supports --check=artifacts, --check=conventions, and
|
|
--check=pollution. --check-health has a limited hook-health fallback.
|
|
Unsupported combinations return a notice without changing storage.
|
|
|
|
Performance Mode (--perf):
|
|
Run performance diagnostics on your database:
|
|
- Times key operations (bd ready, bd list, bd show, etc.)
|
|
- Collects system info (OS, arch, database stats)
|
|
- Generates CPU profile for analysis
|
|
- Outputs shareable report for bug reports
|
|
|
|
Export Mode (--output):
|
|
Save diagnostics to a JSON file for historical analysis and bug reporting.
|
|
Includes timestamp and platform info for tracking intermittent issues.
|
|
|
|
Specific Check Mode (--check):
|
|
Run a specific check in detail. Available checks:
|
|
- artifacts: Detect and optionally clean beads classic artifacts
|
|
(stale JSONL, SQLite files, cruft .beads dirs). Use with --clean.
|
|
- conventions: Check for convention drift (lint warnings, stale
|
|
issues, orphaned issues). Advisory only - warns, never blocks.
|
|
- pollution: Detect and optionally clean test issues from database
|
|
- validate: Run focused data-integrity checks (duplicates, orphaned
|
|
deps, test pollution, git conflicts). Use with --fix to auto-repair.
|
|
|
|
Deep Validation Mode (--deep):
|
|
Validate full graph integrity. May be slow on large databases.
|
|
Additional checks:
|
|
- Parent consistency: All parent-child deps point to existing issues
|
|
- Dependency integrity: All deps reference valid issues
|
|
- Epic completeness: Find epics ready to close (all children closed as
|
|
completed work; duplicate/wontfix/superseded closes do not count)
|
|
- Agent bead integrity: Agent beads have valid state values
|
|
- Mail thread integrity: Thread IDs reference existing issues
|
|
- Molecule integrity: Molecules have valid parent-child structures
|
|
|
|
Server Mode (--server):
|
|
Run health checks for Dolt server mode connections (bd-dolt.2.3):
|
|
- Server reachable: Can connect to configured host:port?
|
|
- Dolt version: Is it a Dolt server (not vanilla MySQL)?
|
|
- Database exists: Does the 'beads' database exist?
|
|
- Schema compatible: Can query beads tables?
|
|
- Connection pool: Pool health metrics
|
|
|
|
Legacy Dolt Migration Validation Mode (--migration):
|
|
Retained for older SQLite-to-Dolt migration workflows and available only in
|
|
Dolt server mode. It is not the migration path for removed backends
|
|
(PostgreSQL, MySQL, SQLite); those fail closed with export/import guidance.
|
|
Combine
|
|
with --json for machine-parseable diagnostic output.
|
|
|
|
Agent Mode (--agent):
|
|
Output diagnostics designed for AI agent consumption. Instead of terse
|
|
pass/fail messages, each issue includes:
|
|
- Observed state: what the system actually looks like
|
|
- Expected state: what it should look like
|
|
- Explanation: full prose context about the issue and why it matters
|
|
- Commands: exact remediation commands to run
|
|
- Source files: where in the codebase to investigate further
|
|
- Severity: blocking (prevents operation), degraded (partial function),
|
|
or advisory (informational only)
|
|
ZFC-compliant: Go observes and reports, the agent decides and acts.
|
|
Combine with --json for structured agent-facing output.
|
|
|
|
Suppressing Warnings:
|
|
Suppress specific warnings by setting doctor.suppress.<check-slug> config:
|
|
bd config set doctor.suppress.pending-migrations true
|
|
bd config set doctor.suppress.git-hooks true
|
|
Check names are converted to slugs: "Git Hooks" → "git-hooks".
|
|
Only warnings are suppressed; errors and passing checks always show.
|
|
To unsuppress: bd config unset doctor.suppress.<slug>
|
|
|
|
Examples:
|
|
bd doctor # Check current directory
|
|
bd doctor /path/to/repo # Check specific repository
|
|
bd doctor --json # Machine-readable output
|
|
bd doctor --agent # Agent-facing diagnostic output
|
|
bd doctor --agent --json # Structured agent diagnostics (JSON)
|
|
bd doctor --fix # Automatically fix issues (with confirmation)
|
|
bd doctor --fix --yes # Automatically fix issues (no confirmation)
|
|
bd doctor --fix -i # Confirm each fix individually
|
|
bd doctor --fix --fix-child-parent # Also fix child→parent deps (opt-in)
|
|
bd doctor --fix --force # Force repair even when database can't be opened
|
|
bd doctor --fix --source=jsonl # Rebuild database from a JSONL export
|
|
bd doctor --dry-run # Preview what --fix would do without making changes
|
|
bd doctor --perf # Performance diagnostics
|
|
bd doctor --output diagnostics.json # Export diagnostics to file
|
|
bd doctor --check=artifacts # Show classic artifacts (JSONL, SQLite, cruft dirs)
|
|
bd doctor --check=artifacts --clean # Delete safe-to-delete artifacts (with confirmation)
|
|
bd doctor --check=conventions # Convention drift check (lint, stale, orphans)
|
|
bd doctor --check=pollution # Show potential test issues
|
|
bd doctor --check=pollution --clean # Delete test issues (with confirmation)
|
|
bd doctor --check=validate # Data-integrity checks only
|
|
bd doctor --check=validate --fix # Auto-fix data-integrity issues
|
|
bd doctor --deep # Full graph integrity validation
|
|
bd doctor --server # Dolt server mode health checks
|
|
bd doctor --migration=pre # Legacy Dolt-server migration diagnostic
|
|
bd doctor --migration=post # Legacy Dolt-server completion diagnostic
|
|
bd doctor --migration=pre --json # Machine-parseable legacy diagnostic`,
|
|
SilenceUsage: true,
|
|
SilenceErrors: true,
|
|
RunE: func(cmd *cobra.Command, args []string) error {
|
|
evt := metrics.NewCommandEvent("doctor")
|
|
defer func() {
|
|
if c := metrics.Global(); c != nil {
|
|
c.CloseEventAndAdd(evt)
|
|
}
|
|
}()
|
|
|
|
var checkPath string
|
|
if len(args) > 0 {
|
|
checkPath = args[0]
|
|
} else if beadsDir := os.Getenv("BEADS_DIR"); beadsDir != "" {
|
|
checkPath = filepath.Dir(beadsDir)
|
|
} else {
|
|
checkPath = "."
|
|
}
|
|
|
|
absPath, err := filepath.Abs(checkPath)
|
|
if err != nil {
|
|
return HandleError("failed to resolve path: %v", err)
|
|
}
|
|
if err := checkDoctorMutationGate(absPath); err != nil {
|
|
return err
|
|
}
|
|
if err := validateDoctorWorkspaceBackend(absPath); isLegacyUpgradeRefusal(err) {
|
|
return printLegacyUpgradeDiagnostic(err)
|
|
} else if err != nil {
|
|
return handleWorkspaceGuardError(err)
|
|
}
|
|
|
|
if doctorFix && isOrchestratorRoot(absPath) {
|
|
return HandleErrorWithHint(
|
|
"refusing to run 'bd doctor --fix' at orchestrator workspace root",
|
|
"Run the orchestrator's doctor command from workspace root, or run 'bd doctor --fix' inside a specific project clone",
|
|
)
|
|
}
|
|
|
|
// --check-health has a hook-only fallback for embedded mode
|
|
// (doctor_health.go), so it runs before the embedded-mode gate below.
|
|
if checkHealthMode {
|
|
return runCheckHealth(absPath)
|
|
}
|
|
|
|
// --perf opens a live server-mode connection; route embedded users to
|
|
// the structured stub instead of a hard connection error (GH#3597).
|
|
if perfMode {
|
|
if isEmbeddedMode() {
|
|
printEmbeddedUnsupported("doctor --perf")
|
|
return nil
|
|
}
|
|
if err := doctor.RunPerformanceDiagnostics(absPath); err != nil {
|
|
return HandleError("performance diagnostics: %v", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// GH#4993: assess once, before any branch that can write. Lazy so
|
|
// read-only paths skip the probe; memoised so repeats cannot disagree.
|
|
schemaGate := newSchemaGate(absPath)
|
|
|
|
// artifacts, conventions, and pollution work in embedded mode and run
|
|
// unconditionally; validate still requires a server-mode connection
|
|
// and stays gated (GH#3597).
|
|
if doctorCheckFlag != "" {
|
|
// GH#4993: these handlers return directly, so their destructive
|
|
// paths bypassed the gate. Refuse at the single branch point.
|
|
if err := destructiveCheckRefusal(doctorCheckFlag, doctorClean, doctorFix, schemaGate); err != nil {
|
|
return err
|
|
}
|
|
switch doctorCheckFlag {
|
|
case "artifacts":
|
|
return runArtifactsCheck(absPath, doctorClean, doctorYes)
|
|
case "conventions":
|
|
return runConventionsCheck(absPath)
|
|
case "pollution":
|
|
return runPollutionCheck(absPath, doctorClean, doctorYes)
|
|
case "validate":
|
|
if isEmbeddedMode() {
|
|
printEmbeddedUnsupported("doctor --check=validate")
|
|
return nil
|
|
}
|
|
return runValidateCheck(absPath)
|
|
default:
|
|
return HandleErrorWithHint(fmt.Sprintf("unknown check %q", doctorCheckFlag), "Available checks: artifacts, conventions, pollution, validate")
|
|
}
|
|
}
|
|
|
|
// Bare `bd doctor` and the remaining mode-specific flags (--deep,
|
|
// --server, --migration) aren't wired up for embedded mode yet.
|
|
// Policy (GH#3794): embedded support is enabled one subcommand at a
|
|
// time, each human-vetted — do not lift this gate wholesale. Checks
|
|
// that reach into the database layer stay server-gated until the
|
|
// storage driver interface covers them (AGENTS.md "Storage Boundary").
|
|
if isEmbeddedMode() {
|
|
printEmbeddedUnsupported("doctor")
|
|
return nil
|
|
}
|
|
|
|
if doctorDeep {
|
|
return runDeepValidation(absPath)
|
|
}
|
|
|
|
if doctorServer {
|
|
return runServerHealth(absPath)
|
|
}
|
|
|
|
if doctorMigration != "" {
|
|
return runMigrationValidation(absPath, doctorMigration)
|
|
}
|
|
|
|
result := runDiagnostics(absPath)
|
|
|
|
// GH#4993: guard once, on the result, before any emitter reads it.
|
|
// Per-renderer sanitizing exempted --json, --agent and --output.
|
|
sanitizeFixAdvice(&result, schemaGate())
|
|
|
|
if doctorDryRun {
|
|
previewFixes(result, schemaGate())
|
|
} else if doctorFix {
|
|
applyFixes(result, schemaGate())
|
|
fmt.Println("\nVerifying fixes...")
|
|
result = runDiagnostics(absPath)
|
|
sanitizeFixAdvice(&result, schemaGate())
|
|
}
|
|
|
|
if doctorOutput != "" || jsonOutput {
|
|
result.Timestamp = time.Now().UTC().Format(time.RFC3339)
|
|
result.Platform = doctor.CollectPlatformInfo(absPath)
|
|
}
|
|
|
|
if doctorOutput != "" {
|
|
if err := exportDiagnostics(result, doctorOutput); err != nil {
|
|
return HandleError("failed to export diagnostics: %v", err)
|
|
}
|
|
fmt.Printf("✓ Diagnostics exported to %s\n", doctorOutput)
|
|
}
|
|
|
|
if doctorAgent {
|
|
agentResult := buildAgentResult(result, schemaGate())
|
|
if jsonOutput {
|
|
if err := outputJSON(agentResult); err != nil {
|
|
return err
|
|
}
|
|
} else {
|
|
printAgentDiagnostics(agentResult)
|
|
}
|
|
} else if jsonOutput {
|
|
if err := outputJSON(result); err != nil {
|
|
return err
|
|
}
|
|
} else if doctorOutput == "" {
|
|
printDiagnostics(result, schemaGate())
|
|
}
|
|
|
|
if !result.OverallOK {
|
|
return SilentExit()
|
|
}
|
|
return nil
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
doctorCmd.Flags().BoolVar(&doctorFix, "fix", false, "Automatically fix issues where possible")
|
|
doctorCmd.Flags().BoolVarP(&doctorYes, "yes", "y", false, "Skip confirmation prompt (for non-interactive use)")
|
|
doctorCmd.Flags().BoolVarP(&doctorInteractive, "interactive", "i", false, "Confirm each fix individually")
|
|
doctorCmd.Flags().BoolVar(&doctorDryRun, "dry-run", false, "Preview fixes without making changes")
|
|
doctorCmd.Flags().BoolVar(&doctorFixChildParent, "fix-child-parent", false, "Remove child→parent dependencies (opt-in)")
|
|
doctorCmd.Flags().BoolVarP(&doctorVerbose, "verbose", "v", false, "Show all checks (default shows only warnings/errors)")
|
|
doctorCmd.Flags().BoolVar(&doctorOrchestrator, "orchestrator", false, "Running in orchestrator multi-workspace mode (routes.jsonl is expected, higher duplicate tolerance)")
|
|
doctorCmd.Flags().IntVar(&orchestratorDuplicatesThreshold, "orchestrator-duplicates-threshold", 1000, "Duplicate tolerance threshold for orchestrator mode (wisps are ephemeral)")
|
|
doctorCmd.Flags().BoolVar(&doctorServer, "server", false, "Run Dolt server mode health checks (connectivity, version, schema)")
|
|
doctorCmd.Flags().StringVar(&doctorMigration, "migration", "", "Run legacy Dolt-server migration diagnostics: 'pre' or 'post'")
|
|
doctorCmd.Flags().BoolVar(&doctorAgent, "agent", false, "Agent-facing diagnostic mode: rich context for AI agents (ZFC-compliant)")
|
|
}
|
|
|
|
// doctorMutationOp returns the operation label for a doctor invocation that
|
|
// will mutate the workspace, or "" when this run is diagnosis-only. --fix and
|
|
// --clean are the complete trigger set: every mutating doctor surface
|
|
// (applyFixes, applyFixesInteractive, applyValidateFixes, the pollution and
|
|
// artifacts cleaners) is reached only through one of those two flags.
|
|
func doctorMutationOp() string {
|
|
switch {
|
|
case doctorFix:
|
|
return "doctor --fix"
|
|
case doctorClean:
|
|
return "doctor --clean"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// checkDoctorMutationGate is doctor's stand-in for the CheckReadonly call every
|
|
// other write command makes at the top of its RunE (#6028). Doctor never made
|
|
// that call, and its skipStoreAnnotation opt-out also skips the root
|
|
// PersistentPreRunE's freeze gate, so both `--readonly` and an active
|
|
// MIGRATION-FREEZE were bypassed structurally rather than deliberately.
|
|
//
|
|
// One call, once, at the flag-level flip point — not per fixer: there are 40+
|
|
// fixers and any check sprinkled among them rots the moment one is added. It
|
|
// runs before every mode dispatch (including the embedded-mode gate), so a
|
|
// refused run never half-executes and never needs a store to refuse.
|
|
//
|
|
// There is deliberately no doctor-side override. A migration freeze is exactly
|
|
// when a shared store has mixed-version clients and `bd doctor --fix` is the
|
|
// mid-incident reflex command; the operator clears the freeze first.
|
|
func checkDoctorMutationGate(absPath string) error {
|
|
op := doctorMutationOp()
|
|
if op == "" {
|
|
return nil
|
|
}
|
|
if readonlyMode {
|
|
// Wording matches CheckReadonly (errors.go) exactly; doctor returns the
|
|
// error rather than calling that void helper so its deferred metrics
|
|
// CloseEventAndAdd still runs.
|
|
fmt.Fprintf(os.Stderr, "Error: operation '%s' is not allowed in read-only mode\n", op)
|
|
return &exitError{Code: 1}
|
|
}
|
|
// Doctor is the one write-capable command that takes a target path, so the
|
|
// freeze has to be looked up against that target as well as against the
|
|
// directory bd was launched in: `bd doctor /frozen/repo --fix` from an
|
|
// unfrozen cwd would otherwise walk the wrong tree entirely. ...ErrorFor
|
|
// covers both (FindFrom(absPath) alone would miss a freeze in the caller's
|
|
// own cwd), and doctorCmd already sets SilenceErrors/SilenceUsage
|
|
// statically, so the cobra-silencing gate variant buys nothing here.
|
|
return migrationFreezeErrorFor(op, absPath)
|
|
}
|
|
|
|
func shouldSkipDoctorNetworkChecks() bool {
|
|
return jsonOutput || !ui.IsTerminal()
|
|
}
|
|
|
|
// validateDoctorWorkspaceBackend keeps doctor diagnostics read-only when metadata
|
|
// selects a removed or unknown implementation or cannot be parsed. Doctor contains
|
|
// direct diagnostic store paths and may run under shared-server mode, so corrupt
|
|
// metadata must be rejected before version tracking or any database check begins.
|
|
func validateDoctorWorkspaceBackend(path string) error {
|
|
beadsDir := doctor.ResolveBeadsDirForRepo(path)
|
|
if err := guardLegacyUpgradeWorkspace(beadsDir); err != nil {
|
|
return err
|
|
}
|
|
cfg, err := configfile.LoadForDiscovery(beadsDir)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to load %s: %w; no storage database was opened or modified; fix or restore metadata.json and retry", configfile.ConfigPath(beadsDir), err)
|
|
}
|
|
return validateConfiguredBackend(cfg, beadsDir)
|
|
}
|
|
|
|
// printLegacyUpgradeDiagnostic preserves doctor as a store-free repair path:
|
|
// the workspace is recognized, but no storage or metadata migration is opened.
|
|
func printLegacyUpgradeDiagnostic(err error) error {
|
|
if jsonOutput || doctorAgent {
|
|
return outputJSON(map[string]any{
|
|
"status": "warning",
|
|
"code": "legacy_upgrade_required",
|
|
"message": err.Error(),
|
|
"guide": "docs/getting-started/upgrading.md#cross-era-upgrades",
|
|
})
|
|
}
|
|
_, _ = fmt.Fprintf(os.Stdout, "Warning: %v\n", err)
|
|
_, _ = fmt.Fprintln(os.Stdout, "Follow docs/getting-started/upgrading.md#cross-era-upgrades for the layout-specific migration path.")
|
|
return nil
|
|
}
|
|
|
|
// printEmbeddedUnsupported reports that a doctor variant is not yet wired up
|
|
// for embedded mode. Emits a structured payload to stderr when --json or
|
|
// --agent is set so downstream tooling can detect the gap without parsing
|
|
// prose, and the existing prose stub otherwise (GH#3597).
|
|
//
|
|
// Follows the bd error-JSON contract (docs/JSON_SCHEMA.md): stderr, includes
|
|
// a `code` field, and is wrapped with schema_version. Exit code stays 0 - a
|
|
// benign refusal, not a failure.
|
|
func printEmbeddedUnsupported(commandLabel string) {
|
|
hints := []string{
|
|
"Verify database exists: ls -la .beads/embeddeddolt/",
|
|
"Check bd version: bd version",
|
|
"Reinitialize if needed: bd init --reinit-local",
|
|
"Switch to server mode: bd init --server",
|
|
}
|
|
supported := []string{"artifacts", "conventions", "pollution"}
|
|
unsupported := []string{"validate"}
|
|
|
|
if jsonOutput || doctorAgent {
|
|
payload := map[string]interface{}{
|
|
"error": fmt.Sprintf("'bd %s' is not yet supported in embedded mode", commandLabel),
|
|
"code": "embedded_unsupported",
|
|
"unsupported": true,
|
|
"mode": "embedded",
|
|
"command": commandLabel,
|
|
"checks_supported_in_embedded_mode": supported,
|
|
"checks_unsupported_in_embedded_mode": unsupported,
|
|
"hints": hints,
|
|
}
|
|
encoder := json.NewEncoder(os.Stderr)
|
|
encoder.SetIndent("", " ")
|
|
_ = encoder.Encode(wrapWithSchemaVersion(payload))
|
|
return
|
|
}
|
|
|
|
fmt.Fprintf(os.Stderr, "Note: 'bd %s' is not yet supported in embedded mode.\n\n", commandLabel)
|
|
fmt.Fprintln(os.Stderr, "For embedded mode troubleshooting:")
|
|
for _, h := range hints {
|
|
fmt.Fprintf(os.Stderr, " • %s\n", h)
|
|
}
|
|
fmt.Fprintln(os.Stderr, "")
|
|
fmt.Fprintln(os.Stderr, "Checks available in embedded mode:")
|
|
fmt.Fprintln(os.Stderr, " • bd doctor --check=artifacts")
|
|
fmt.Fprintln(os.Stderr, " • bd doctor --check=conventions")
|
|
fmt.Fprintln(os.Stderr, " • bd doctor --check=pollution")
|
|
}
|
|
|
|
func runDiagnostics(path string) doctorResult {
|
|
result := doctorResult{
|
|
Path: path,
|
|
CLIVersion: Version,
|
|
OverallOK: true,
|
|
}
|
|
|
|
// Auto-detect orchestrator mode: routes.jsonl is only created by orchestrator workspaces
|
|
if !doctorOrchestrator {
|
|
resolvedBeadsDir := doctor.ResolveBeadsDirForRepo(path)
|
|
routesFile := filepath.Join(resolvedBeadsDir, "routes.jsonl")
|
|
if _, err := os.Stat(routesFile); err == nil {
|
|
doctorOrchestrator = true
|
|
}
|
|
}
|
|
|
|
// Check 1: Installation (.beads/ directory)
|
|
installCheck := convertWithCategory(doctor.CheckInstallation(path), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, installCheck)
|
|
if installCheck.Status != statusOK {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check Git Hooks early (even if .beads/ doesn't exist yet)
|
|
hooksCheck := convertWithCategory(doctor.CheckGitHooks(Version), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, hooksCheck)
|
|
// Don't fail overall check for missing hooks, just warn
|
|
|
|
// Check for stale .legacy hook sidecars calling removed "bd hook" command (GH#2398)
|
|
legacyCheck := convertWithCategory(doctor.CheckStaleLegacyHooks(), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, legacyCheck)
|
|
|
|
// Check for a dangling core.hooksPath pointing at a missing directory (GH#4440)
|
|
hooksPathCheck := convertWithCategory(doctor.CheckHooksPath(), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, hooksPathCheck)
|
|
// Warning-class check — don't fail overall check, matching the neighboring hooks checks.
|
|
|
|
// Check git hooks Dolt compatibility (hooks without Dolt check cause errors)
|
|
doltHooksCheck := convertWithCategory(doctor.CheckGitHooksDoltCompatibility(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, doltHooksCheck)
|
|
if doltHooksCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// If no .beads/, skip remaining checks
|
|
if installCheck.Status != statusOK {
|
|
return result
|
|
}
|
|
|
|
// Check 1a: Fresh clone detection
|
|
// Must come early - if this is a fresh clone, other checks may be misleading
|
|
freshCloneCheck := convertWithCategory(doctor.CheckFreshClone(path), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, freshCloneCheck)
|
|
if freshCloneCheck.Status == statusWarning || freshCloneCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 1b: Metadata config file (GH#2478)
|
|
// Must come before database checks since they depend on metadata.json.
|
|
beadsDir := doctor.ResolveBeadsDirForRepo(path)
|
|
configPath := configfile.ConfigPath(beadsDir)
|
|
if _, err := os.Stat(configPath); os.IsNotExist(err) {
|
|
metaCheck := doctorCheck{
|
|
Name: "Metadata Config",
|
|
Status: statusError,
|
|
Message: "metadata.json is missing",
|
|
Fix: "Run 'bd doctor --fix' to regenerate with defaults, or 'bd init --force'",
|
|
Category: doctor.CategoryCore,
|
|
}
|
|
result.Checks = append(result.Checks, metaCheck)
|
|
result.OverallOK = false
|
|
} else {
|
|
result.Checks = append(result.Checks, doctorCheck{
|
|
Name: "Metadata Config",
|
|
Status: statusOK,
|
|
Message: "metadata.json present",
|
|
Category: doctor.CategoryCore,
|
|
})
|
|
}
|
|
|
|
// Check 1c: Managed-city handoff port conflict (GH#3926)
|
|
managedHandoffCheck := convertDoctorCheck(doctor.CheckManagedHandoffPort(path))
|
|
result.Checks = append(result.Checks, managedHandoffCheck)
|
|
if managedHandoffCheck.Status == statusWarning || managedHandoffCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// bd-jgxi: Auto-migrate database version before checking it.
|
|
// Since doctor skips PersistentPreRun DB init (via skipStoreAnnotation),
|
|
// trackBdVersion() and autoMigrateOnVersionBump() haven't run yet.
|
|
//
|
|
// #6028: skipping that hook also skipped its guards on these exact two
|
|
// calls — main.go runs them only when policy.runMaintenance is set and the
|
|
// workspace is not frozen for maintenance. Doctor replicates the calls, so
|
|
// it must replicate the guard, or plain `bd doctor` (no --fix needed)
|
|
// rewrites .beads/.local_version and silently applies a schema migration to
|
|
// a read-only or mid-freeze store: precisely the torn-upgrade write the
|
|
// freeze exists to prevent. Under either gate doctor now *reports* the
|
|
// version/migration mismatch in the checks below instead of healing it.
|
|
//
|
|
// The probe takes beadsDir for the same reason the mutation gate takes
|
|
// absPath: these writes land in the doctor target, so a freeze on that tree
|
|
// must stop them even when bd was launched somewhere unfrozen.
|
|
if !readonlyMode && !migrationFreezeActiveFor(beadsDir) {
|
|
// Scope version tracking to the doctor target. Without this, `bd doctor <path>`
|
|
// can accidentally touch the caller's current repo .beads state.
|
|
origBeadsDir, hadBeadsDir := os.LookupEnv("BEADS_DIR")
|
|
_ = os.Setenv("BEADS_DIR", beadsDir)
|
|
trackBdVersion()
|
|
if hadBeadsDir {
|
|
_ = os.Setenv("BEADS_DIR", origBeadsDir)
|
|
} else {
|
|
_ = os.Unsetenv("BEADS_DIR")
|
|
}
|
|
|
|
autoMigrateOnVersionBump(beadsDir)
|
|
}
|
|
|
|
// Check 1b: Dolt format compatibility (GH#2137)
|
|
// Must run before opening the database — old noms formats cause server panics.
|
|
doltFormatCheck := convertWithCategory(doctor.CheckDoltFormat(path), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, doltFormatCheck)
|
|
if doltFormatCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// GH#2636: Open a single shared store for all database checks.
|
|
// This prevents the infinite Dolt server restart loop that occurred when each
|
|
// check opened and closed its own store (each close kills the server, each
|
|
// open restarts it). The shared store stays alive for the entire doctor run.
|
|
sharedStore := doctor.NewSharedStore(path)
|
|
defer sharedStore.Close()
|
|
|
|
// Check 2: Database version
|
|
dbCheck := convertWithCategory(doctor.CheckDatabaseVersionWithStore(sharedStore, Version), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, dbCheck)
|
|
if dbCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 2a: Schema compatibility
|
|
schemaCheck := convertWithCategory(doctor.CheckSchemaCompatibilityWithStore(sharedStore), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, schemaCheck)
|
|
if schemaCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 2b: Repo fingerprint (detects wrong database or URL change)
|
|
fingerprintCheck := convertWithCategory(doctor.CheckRepoFingerprintWithStore(sharedStore, path), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, fingerprintCheck)
|
|
if fingerprintCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 2c: Database integrity
|
|
integrityCheck := convertWithCategory(doctor.CheckDatabaseIntegrityWithStore(sharedStore), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, integrityCheck)
|
|
if integrityCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 3: ID format (hash vs sequential)
|
|
idCheck := convertWithCategory(doctor.CheckIDFormatWithStore(sharedStore), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, idCheck)
|
|
if idCheck.Status == statusWarning {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Network-based update checks are skipped in machine-readable and other
|
|
// non-interactive contexts so doctor remains deterministic under wrappers.
|
|
versionCheckFn := doctor.CheckCLIVersion
|
|
pluginCheckFn := doctor.CheckClaudePlugin
|
|
if shouldSkipDoctorNetworkChecks() {
|
|
versionCheckFn = doctor.CheckCLIVersionLocalOnly
|
|
pluginCheckFn = doctor.CheckClaudePluginLocalOnly
|
|
}
|
|
|
|
// Check 4: CLI version
|
|
versionCheck := convertWithCategory(versionCheckFn(Version), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, versionCheck)
|
|
// Don't fail overall check for outdated CLI, just warn
|
|
|
|
// Check 4.5: Claude plugin version (if running in Claude Code)
|
|
pluginCheck := convertWithCategory(pluginCheckFn(), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, pluginCheck)
|
|
// Don't fail overall check for outdated plugin, just warn
|
|
|
|
// Check 7: Database/JSONL configuration mismatch
|
|
configCheck := convertWithCategory(doctor.CheckDatabaseConfig(path), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, configCheck)
|
|
if configCheck.Status == statusWarning || configCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 7a: Configuration value validation
|
|
configValuesCheck := convertWithCategory(doctor.CheckConfigValuesWithStore(path, sharedStore), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, configValuesCheck)
|
|
// Don't fail overall check for config value warnings, just warn
|
|
|
|
// Check 7a1: Project identity (GH#2372 backfill)
|
|
projectIDCheck := convertWithCategory(doctor.CheckProjectIdentityWithStore(sharedStore, path), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, projectIDCheck)
|
|
if projectIDCheck.Status == statusWarning || projectIDCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 7b: Multi-repo custom types discovery (bd-9ji4z)
|
|
multiRepoTypesCheck := convertWithCategory(doctor.CheckMultiRepoTypes(path), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, multiRepoTypesCheck)
|
|
// Don't fail overall check for multi-repo types, just informational
|
|
|
|
// Check 7c: Role configuration (beads.role)
|
|
roleCheck := convertDoctorCheck(doctor.CheckBeadsRoleWithStore(path, sharedStore))
|
|
result.Checks = append(result.Checks, roleCheck)
|
|
// Don't fail overall check for role config, just warn - URL heuristic fallback still works
|
|
|
|
// Check 7e: Stale lock files (bootstrap, sync, startup)
|
|
staleLockCheck := convertDoctorCheck(doctor.CheckStaleLockFiles(path))
|
|
result.Checks = append(result.Checks, staleLockCheck)
|
|
if staleLockCheck.Status == statusWarning || staleLockCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 7e1: Corrupt-manifest state (GH#3290). Detection only; the
|
|
// destructive backup+reinit repair runs solely via doctor --fix (bd-6dnrw.6).
|
|
corruptManifestCheck := convertDoctorCheck(doctor.CheckCorruptManifest(path))
|
|
result.Checks = append(result.Checks, corruptManifestCheck)
|
|
if corruptManifestCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 7e2: Stale circuit breaker files
|
|
circuitCheck := convertDoctorCheck(doctor.CheckCircuitBreaker())
|
|
result.Checks = append(result.Checks, circuitCheck)
|
|
if circuitCheck.Status == statusWarning || circuitCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 7f1: Dolt remote URL collision with git origin (be-7eu1d)
|
|
doltOriginCheck := convertWithCategory(doctor.CheckDoltRemoteGitOrigin(path), doctor.CategoryDolt)
|
|
result.Checks = append(result.Checks, doltOriginCheck)
|
|
|
|
// Check 7f: Migration content skew vs the cached remote ref (#4259). Advisory.
|
|
skewCheck := convertWithCategory(doctor.CheckMigrationContentSkew(sharedStore), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, skewCheck)
|
|
|
|
// Dolt health checks (connection, schema, issue count, status).
|
|
for _, dc := range doctor.RunDoltHealthChecks(path) {
|
|
result.Checks = append(result.Checks, convertDoctorCheck(dc))
|
|
}
|
|
|
|
legacyRemoteCheck := convertWithCategory(doctor.CheckLegacyCLIRemotes(path), doctor.CategoryFederation)
|
|
result.Checks = append(result.Checks, legacyRemoteCheck)
|
|
|
|
// Federation health checks (bd-wkumz.6)
|
|
// Check 8d: Federation remotesapi port accessibility
|
|
remotesAPICheck := convertWithCategory(doctor.CheckFederationRemotesAPI(path), doctor.CategoryFederation)
|
|
result.Checks = append(result.Checks, remotesAPICheck)
|
|
// Don't fail overall for federation issues - they're only relevant for Dolt users
|
|
|
|
// Check 8e: Federation peer connectivity
|
|
peerConnCheck := convertWithCategory(doctor.CheckFederationPeerConnectivity(path), doctor.CategoryFederation)
|
|
result.Checks = append(result.Checks, peerConnCheck)
|
|
|
|
// Check 8f: Federation sync staleness
|
|
syncStalenessCheck := convertWithCategory(doctor.CheckFederationSyncStaleness(path), doctor.CategoryFederation)
|
|
result.Checks = append(result.Checks, syncStalenessCheck)
|
|
|
|
// Check 8g: Federation conflict detection
|
|
fedConflictsCheck := convertWithCategory(doctor.CheckFederationConflicts(path), doctor.CategoryFederation)
|
|
result.Checks = append(result.Checks, fedConflictsCheck)
|
|
if fedConflictsCheck.Status == statusError {
|
|
result.OverallOK = false // Unresolved conflicts are a real problem
|
|
}
|
|
|
|
// Check 8h: Dolt server mode configuration check
|
|
doltModeCheck := convertWithCategory(doctor.CheckDoltServerModeMismatch(path), doctor.CategoryFederation)
|
|
result.Checks = append(result.Checks, doltModeCheck)
|
|
|
|
// Check 9: Permissions
|
|
permCheck := convertWithCategory(doctor.CheckPermissionsWithStore(path, sharedStore), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, permCheck)
|
|
if permCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 10: Dependency cycles
|
|
cycleCheck := convertWithCategory(doctor.CheckDependencyCyclesWithStore(sharedStore), doctor.CategoryMetadata)
|
|
result.Checks = append(result.Checks, cycleCheck)
|
|
if cycleCheck.Status == statusError || cycleCheck.Status == statusWarning {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 10b: Rekey-backfill leftovers — randomly-keyed or targetless
|
|
// dependency rows that survive the #4259 migration backfill (bd-6dnrw.17).
|
|
depKeyCheck := convertWithCategory(doctor.CheckDependencyKeysWithStore(sharedStore), doctor.CategoryMetadata)
|
|
result.Checks = append(result.Checks, depKeyCheck)
|
|
if depKeyCheck.Status == statusError || depKeyCheck.Status == statusWarning {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 10c: is_blocked consistency — derived flags a skipped post-pull
|
|
// recompute can leave stale (bd-6dnrw.37). `bd ready` trusts is_blocked, so
|
|
// staleness silently hides ready work; the full recompute repairs it.
|
|
// Warn-only (does not fail OverallOK): this is a new check shipping in a
|
|
// patch, and is_blocked is self-healing via 'bd doctor --fix' / the next
|
|
// pull's recompute — surface it as actionable without turning doctor red
|
|
// across the fleet if an unforeseen dependency shape trips the predicate.
|
|
blockedConsistencyCheck := convertWithCategory(doctor.CheckBlockedConsistencyWithStore(sharedStore), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, blockedConsistencyCheck)
|
|
|
|
// Check 10d: label whitespace damage (#5812) — labels written by a bd that
|
|
// normalized on read but not on write, which no filter can match.
|
|
// Warn-only (does not fail OverallOK), same reasoning as the check above:
|
|
// this ships into databases that already carry the damage, and turning
|
|
// doctor red on pre-existing data across the fleet would be worse than
|
|
// surfacing it as actionable.
|
|
labelWhitespaceCheck := convertWithCategory(doctor.CheckLabelWhitespaceWithStore(sharedStore), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, labelWhitespaceCheck)
|
|
|
|
// Check 11: Claude integration
|
|
claudeCheck := convertWithCategory(doctor.CheckClaude(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, claudeCheck)
|
|
// Don't fail overall check for missing Claude integration, just warn
|
|
|
|
// Check 11a: Claude settings file health (malformed JSON detection)
|
|
claudeSettingsCheck := convertWithCategory(doctor.CheckClaudeSettingsHealth(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, claudeSettingsCheck)
|
|
if claudeSettingsCheck.Status == statusError {
|
|
result.OverallOK = false // Malformed settings is a real problem
|
|
}
|
|
|
|
// Check 11b: Claude hook completeness (both SessionStart and PreCompact)
|
|
claudeHookCheck := convertWithCategory(doctor.CheckClaudeHookCompleteness(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, claudeHookCheck)
|
|
// Don't fail overall check for incomplete hooks, just warn
|
|
|
|
// Check 11c: bd prime output verification
|
|
bdPrimeOutputCheck := convertWithCategory(doctor.VerifyPrimeOutput(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, bdPrimeOutputCheck)
|
|
// Don't fail overall check for prime output issues, just warn
|
|
|
|
// Check 11d: bd in PATH (needed for Claude hooks and other integrations)
|
|
bdPathCheck := convertWithCategory(doctor.CheckBdInPath(), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, bdPathCheck)
|
|
// Don't fail overall check for missing bd in PATH, just warn
|
|
|
|
// Check 11e: Cursor integration (agent hooks)
|
|
cursorCheck := convertWithCategory(doctor.CheckCursor(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, cursorCheck)
|
|
// Don't fail overall check for missing Cursor integration, just warn
|
|
|
|
// Check 11f: Cursor hooks file health (malformed JSON detection)
|
|
cursorSettingsCheck := convertWithCategory(doctor.CheckCursorSettingsHealth(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, cursorSettingsCheck)
|
|
if cursorSettingsCheck.Status == statusError {
|
|
result.OverallOK = false // Malformed hooks.json is a real problem
|
|
}
|
|
|
|
// Check 11g: Cursor hook completeness (all three lifecycle events)
|
|
cursorHookCheck := convertWithCategory(doctor.CheckCursorHookCompleteness(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, cursorHookCheck)
|
|
// Don't fail overall check for incomplete hooks, just warn
|
|
|
|
// Check 11h: Documentation bd prime references match installed version
|
|
bdPrimeDocsCheck := convertWithCategory(doctor.CheckDocumentationBdPrimeReference(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, bdPrimeDocsCheck)
|
|
// Don't fail overall check for doc mismatch, just warn
|
|
|
|
// Check 12: Agent documentation presence
|
|
agentDocsCheck := convertWithCategory(doctor.CheckAgentDocumentation(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, agentDocsCheck)
|
|
// Don't fail overall check for missing docs, just warn
|
|
|
|
// Check 12a: AGENTS.md / CLAUDE.md user-authored divergence
|
|
agentDocDivergenceCheck := convertWithCategory(doctor.CheckAgentDocDivergence(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, agentDocDivergenceCheck)
|
|
// Don't fail overall check for divergence, just warn
|
|
|
|
// Check 13: Legacy beads slash commands in documentation
|
|
legacyDocsCheck := convertWithCategory(doctor.CheckLegacyBeadsSlashCommands(path), doctor.CategoryMetadata)
|
|
result.Checks = append(result.Checks, legacyDocsCheck)
|
|
// Don't fail overall check for legacy docs, just warn
|
|
|
|
// Check 13a: MCP tool references in documentation
|
|
mcpToolRefsCheck := convertWithCategory(doctor.CheckLegacyMCPToolReferences(path), doctor.CategoryIntegration)
|
|
result.Checks = append(result.Checks, mcpToolRefsCheck)
|
|
// Don't fail overall check for MCP tool refs, just warn
|
|
|
|
// Check 14: Gitignore up to date
|
|
gitignoreCheck := convertWithCategory(doctor.CheckGitignore(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, gitignoreCheck)
|
|
// Don't fail overall check for gitignore, just warn
|
|
|
|
// Check 14a: Project-root Dolt exclusion patterns (GH#2034). In stealth mode these live in
|
|
// .git/info/exclude, so check that location instead to avoid recreating .gitignore.
|
|
if isStealthRepo(path) {
|
|
result.Checks = append(result.Checks, convertWithCategory(checkProjectExcludeStealth(path), doctor.CategoryGit))
|
|
} else {
|
|
projectGitignoreCheck := convertWithCategory(doctor.CheckProjectGitignore(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, projectGitignoreCheck)
|
|
}
|
|
// Don't fail overall check for project gitignore, just warn
|
|
|
|
// Check 14b: redirect file tracking (worktree redirect files shouldn't be committed)
|
|
redirectTrackingCheck := convertWithCategory(doctor.CheckRedirectNotTracked(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, redirectTrackingCheck)
|
|
// Don't fail overall check for redirect tracking, just warn
|
|
|
|
// Check 14c: redirect target validity (target exists and has valid db)
|
|
redirectTargetCheck := convertWithCategory(doctor.CheckRedirectTargetValid(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, redirectTargetCheck)
|
|
// Don't fail overall check for redirect target, just warn
|
|
|
|
// Check 14d: redirect target sync worktree (target has beads-sync if needed)
|
|
redirectTargetSyncCheck := convertWithCategory(doctor.CheckRedirectTargetSyncWorktree(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, redirectTargetSyncCheck)
|
|
// Don't fail overall check for redirect target sync, just warn
|
|
|
|
// Check 14e: vestigial sync worktrees (unused worktrees in redirected repos)
|
|
vestigialWorktreesCheck := convertWithCategory(doctor.CheckNoVestigialSyncWorktrees(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, vestigialWorktreesCheck)
|
|
// Don't fail overall check for vestigial worktrees, just warn
|
|
|
|
// Check 14g: last-touched file tracking (runtime state shouldn't be committed)
|
|
lastTouchedTrackingCheck := convertWithCategory(doctor.CheckLastTouchedNotTracked(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, lastTouchedTrackingCheck)
|
|
// Don't fail overall check for last-touched tracking, just warn
|
|
|
|
// Check 14h: tracked runtime/sensitive files (GH#2535)
|
|
trackedRuntimeCheck := convertDoctorCheck(doctor.CheckTrackedRuntimeFiles(path))
|
|
result.Checks = append(result.Checks, trackedRuntimeCheck)
|
|
if trackedRuntimeCheck.Status == statusError {
|
|
result.OverallOK = false // Sensitive files in git is a real problem
|
|
}
|
|
|
|
// Check 15a: Git working tree cleanliness (AGENTS.md hygiene)
|
|
gitWorkingTreeCheck := convertWithCategory(doctor.CheckGitWorkingTree(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, gitWorkingTreeCheck)
|
|
// Don't fail overall check for dirty working tree, just warn
|
|
|
|
// Check 15b: Git upstream sync (ahead/behind/diverged)
|
|
gitUpstreamCheck := convertWithCategory(doctor.CheckGitUpstream(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, gitUpstreamCheck)
|
|
// Don't fail overall check for upstream drift, just warn
|
|
|
|
// Check 16: Metadata.json version tracking
|
|
metadataCheck := convertWithCategory(doctor.CheckMetadataVersionTracking(path, Version), doctor.CategoryMetadata)
|
|
result.Checks = append(result.Checks, metadataCheck)
|
|
// Don't fail overall check for metadata, just warn
|
|
|
|
// Check 17b: Orphaned issues - referenced in commits but still open
|
|
orphanedIssuesCheck := convertWithCategory(doctor.CheckOrphanedIssues(path), doctor.CategoryGit)
|
|
result.Checks = append(result.Checks, orphanedIssuesCheck)
|
|
// Don't fail overall check for orphaned issues, just warn
|
|
|
|
// Check 18: Deletions manifest (legacy)
|
|
deletionsCheck := convertWithCategory(doctor.CheckDeletionsManifest(path), doctor.CategoryMetadata)
|
|
result.Checks = append(result.Checks, deletionsCheck)
|
|
// Don't fail overall check for missing deletions manifest, just warn
|
|
|
|
// Check 20: Untracked .beads/*.jsonl files
|
|
untrackedCheck := convertWithCategory(doctor.CheckUntrackedBeadsFiles(path), doctor.CategoryData)
|
|
result.Checks = append(result.Checks, untrackedCheck)
|
|
// Don't fail overall check for untracked files, just warn
|
|
|
|
// Check 21: Orphaned dependencies (from bd repair-deps, bd validate)
|
|
orphanedDepsCheck := convertDoctorCheck(doctor.CheckOrphanedDependencies(path))
|
|
result.Checks = append(result.Checks, orphanedDepsCheck)
|
|
// Don't fail overall check for orphaned deps, just warn
|
|
|
|
// Check 21b: Clone-local FKs severed by hard resets (bd-7bpkd)
|
|
cloneLocalFKCheck := convertDoctorCheck(doctor.CheckCloneLocalFKs(path))
|
|
result.Checks = append(result.Checks, cloneLocalFKCheck)
|
|
// Don't fail overall check for severed clone-local FKs, just warn
|
|
|
|
// Check 22a: Child→parent dependencies (anti-pattern)
|
|
childParentDepsCheck := convertDoctorCheck(doctor.CheckChildParentDependencies(path))
|
|
result.Checks = append(result.Checks, childParentDepsCheck)
|
|
// Don't fail overall check for child→parent deps, just warn
|
|
|
|
// Check 22b: Parent→own-child close gates (informational, #6506)
|
|
parentCloseGateCheck := convertDoctorCheck(doctor.CheckParentBlocksOwnChild(path))
|
|
result.Checks = append(result.Checks, parentCloseGateCheck)
|
|
// Informational only: these edges are legal and never fail the overall check.
|
|
|
|
// Check 23: Duplicate issues (from bd validate)
|
|
duplicatesCheck := convertDoctorCheck(doctor.CheckDuplicateIssues(path, doctorOrchestrator, orchestratorDuplicatesThreshold))
|
|
result.Checks = append(result.Checks, duplicatesCheck)
|
|
// Don't fail overall check for duplicates, just warn
|
|
|
|
// Check 24: Test pollution (from bd validate)
|
|
pollutionCheck := convertDoctorCheck(doctor.CheckTestPollution(path))
|
|
result.Checks = append(result.Checks, pollutionCheck)
|
|
// Don't fail overall check for test pollution, just warn
|
|
|
|
// Check 26: Stale closed issues (maintenance)
|
|
staleClosedCheck := convertDoctorCheck(doctor.CheckStaleClosedIssues(path))
|
|
result.Checks = append(result.Checks, staleClosedCheck)
|
|
// Don't fail overall check for stale issues, just warn
|
|
|
|
// Check 26a: Stale molecules (complete but unclosed)
|
|
staleMoleculesCheck := convertDoctorCheck(doctor.CheckStaleMolecules(path))
|
|
result.Checks = append(result.Checks, staleMoleculesCheck)
|
|
// Don't fail overall check for stale molecules, just warn
|
|
|
|
// Check 26b: Persistent mol- issues (should have been ephemeral)
|
|
persistentMolCheck := convertDoctorCheck(doctor.CheckPersistentMolIssues(path))
|
|
result.Checks = append(result.Checks, persistentMolCheck)
|
|
// Don't fail overall check for persistent mol issues, just warn
|
|
|
|
// Check 26c: Legacy merge queue files (orchestrator mrqueue remnants)
|
|
staleMQFilesCheck := convertDoctorCheck(doctor.CheckStaleMQFiles(path))
|
|
result.Checks = append(result.Checks, staleMQFilesCheck)
|
|
// Don't fail overall check for legacy MQ files, just warn
|
|
|
|
// Check 26d: Patrol pollution (patrol digests, session beads)
|
|
patrolPollutionCheck := convertDoctorCheck(doctor.CheckPatrolPollution(path))
|
|
result.Checks = append(result.Checks, patrolPollutionCheck)
|
|
// Don't fail overall check for patrol pollution, just warn
|
|
|
|
// Check 29: Database size (pruning suggestion)
|
|
// Note: This check has no auto-fix - pruning is destructive and user-controlled
|
|
sizeCheck := convertDoctorCheck(doctor.CheckDatabaseSizeWithStore(sharedStore))
|
|
result.Checks = append(result.Checks, sizeCheck)
|
|
// Don't fail overall check for size warning, just inform
|
|
|
|
// Check 30: Pending migrations (summarizes all available migrations)
|
|
migrationsCheck := convertDoctorCheck(doctor.CheckPendingMigrations(path))
|
|
result.Checks = append(result.Checks, migrationsCheck)
|
|
// Status is determined by the check itself based on migration priorities
|
|
if migrationsCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 31: KV store sync status
|
|
kvSyncCheck := convertDoctorCheck(doctor.CheckKVSyncStatus(path))
|
|
result.Checks = append(result.Checks, kvSyncCheck)
|
|
// Don't fail overall check for KV sync warning, just inform
|
|
|
|
// Check 32: Dolt locks (uncommitted changes)
|
|
doltLocksCheck := convertDoctorCheck(doctor.CheckDoltLocks(path))
|
|
result.Checks = append(result.Checks, doltLocksCheck)
|
|
// Don't fail overall check for Dolt locks, just warn
|
|
|
|
// Check 33: Classic artifacts (post-Dolt-migration cleanup)
|
|
classicArtifactsCheck := convertDoctorCheck(doctor.CheckClassicArtifacts(path))
|
|
result.Checks = append(result.Checks, classicArtifactsCheck)
|
|
// Don't fail overall check for classic artifacts, just warn
|
|
|
|
// Check 34: Linux btrfs NoCOW on .beads/ (GH nocow-beads-dolt-init)
|
|
// Warns when the dolt data directory sits on btrfs without FS_NOCOW_FL,
|
|
// which causes kworker thrashing on the hot append-only write path. Safe
|
|
// no-op on non-Linux and non-btrfs filesystems.
|
|
btrfsNoCowCheck := convertDoctorCheck(doctor.CheckBtrfsNoCOW(path))
|
|
result.Checks = append(result.Checks, btrfsNoCowCheck)
|
|
// Don't fail overall check for btrfs NoCOW, just warn
|
|
|
|
// GH#1095: Filter out suppressed checks (doctor.suppress.<slug> = true)
|
|
suppressed := doctor.GetSuppressedChecksWithStore(sharedStore)
|
|
if len(suppressed) > 0 {
|
|
var suppressedCount int
|
|
var filtered []doctorCheck
|
|
for _, check := range result.Checks {
|
|
slug := doctor.CheckNameToSlug(check.Name)
|
|
if suppressed[slug] && check.Status == statusWarning {
|
|
suppressedCount++
|
|
continue
|
|
}
|
|
filtered = append(filtered, check)
|
|
}
|
|
if suppressedCount > 0 {
|
|
result.Checks = filtered
|
|
// Recompute OverallOK after filtering
|
|
result.OverallOK = true
|
|
for _, check := range result.Checks {
|
|
if check.Status == statusError {
|
|
result.OverallOK = false
|
|
break
|
|
}
|
|
if check.Status == statusWarning {
|
|
// Some warnings are informational (don't fail), but
|
|
// replicate the per-check logic from above is complex.
|
|
// Conservative: don't change OverallOK for warnings here.
|
|
}
|
|
}
|
|
// Store suppressed count for display
|
|
result.SuppressedCount = suppressedCount
|
|
}
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// runInitDiagnostics runs a limited subset of diagnostics appropriate for a
|
|
// freshly-initialized project. Unlike runDiagnostics (which checks everything),
|
|
// this only validates that the init itself succeeded: the .beads directory exists,
|
|
// the database is openable with correct schema, and permissions are correct.
|
|
// Checks that require git, federation remotes, or other post-setup configuration
|
|
// are skipped since they cannot be satisfied in a fresh project.
|
|
func runInitDiagnostics(path string) doctorResult {
|
|
result := doctorResult{
|
|
Path: path,
|
|
CLIVersion: Version,
|
|
OverallOK: true,
|
|
}
|
|
|
|
// Check 1: Installation (.beads/ directory)
|
|
installCheck := convertWithCategory(doctor.CheckInstallation(path), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, installCheck)
|
|
if installCheck.Status != statusOK {
|
|
result.OverallOK = false
|
|
return result
|
|
}
|
|
|
|
// Check 1b: Dolt format compatibility (GH#2137)
|
|
doltFormatCheck := convertWithCategory(doctor.CheckDoltFormat(path), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, doltFormatCheck)
|
|
if doltFormatCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Open one shared store for the database-backed init checks. Server-mode
|
|
// workspaces may not have a local .beads/dolt directory, so the path-only
|
|
// checks would otherwise report a false missing database.
|
|
sharedStore := doctor.NewSharedStore(path)
|
|
defer sharedStore.Close()
|
|
|
|
// Check 2: Database version
|
|
dbCheck := convertWithCategory(doctor.CheckDatabaseVersionWithStore(sharedStore, Version), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, dbCheck)
|
|
if dbCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 3: Schema compatibility
|
|
schemaCheck := convertWithCategory(doctor.CheckSchemaCompatibilityWithStore(sharedStore), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, schemaCheck)
|
|
if schemaCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 4: Permissions
|
|
permCheck := convertWithCategory(doctor.CheckPermissionsWithStore(path, sharedStore), doctor.CategoryCore)
|
|
result.Checks = append(result.Checks, permCheck)
|
|
if permCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 5: Dolt connection — validates init actually created a working DB
|
|
doltConnCheck := convertDoctorCheck(doctor.CheckDoltConnection(path))
|
|
result.Checks = append(result.Checks, doltConnCheck)
|
|
if doltConnCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
// Check 6: Dolt schema — validates tables were created
|
|
doltSchemaCheck := convertDoctorCheck(doctor.CheckDoltSchema(path))
|
|
result.Checks = append(result.Checks, doltSchemaCheck)
|
|
if doltSchemaCheck.Status == statusError {
|
|
result.OverallOK = false
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// convertDoctorCheck converts doctor package check to main package check
|
|
func convertDoctorCheck(dc doctor.DoctorCheck) doctorCheck {
|
|
return doctorCheck{
|
|
Name: dc.Name,
|
|
Status: dc.Status,
|
|
Message: dc.Message,
|
|
Detail: dc.Detail,
|
|
Fix: dc.Fix,
|
|
Category: dc.Category,
|
|
}
|
|
}
|
|
|
|
// convertWithCategory converts a doctor check and sets its category
|
|
func convertWithCategory(dc doctor.DoctorCheck, category string) doctorCheck {
|
|
check := convertDoctorCheck(dc)
|
|
check.Category = category
|
|
return check
|
|
}
|
|
|
|
// exportDiagnostics writes the doctor result to a JSON file
|
|
func exportDiagnostics(result doctorResult, outputPath string) error {
|
|
// #nosec G304 - outputPath is a user-provided flag value for file generation
|
|
f, err := os.Create(outputPath)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to create output file: %w", err)
|
|
}
|
|
defer f.Close()
|
|
|
|
encoder := json.NewEncoder(f)
|
|
encoder.SetIndent("", " ")
|
|
if err := encoder.Encode(result); err != nil {
|
|
return fmt.Errorf("failed to write JSON: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
// checkFlagWrites reports whether a `--check=<flag>` can modify state and so
|
|
// must clear the schema gate (GH#4993). New destructive checks go here.
|
|
func checkFlagWrites(flag string, clean, fix bool) bool {
|
|
switch flag {
|
|
case "artifacts", "pollution":
|
|
return clean
|
|
case "validate":
|
|
return fix
|
|
}
|
|
return false
|
|
}
|
|
|
|
// checkFlagFixName names the classified repair a destructive `--check=<flag>`
|
|
// performs, so the schema gate can admit it through the same policy that governs
|
|
// the equivalent `bd doctor --fix` repair (GH#4993). "" means the flag's
|
|
// destructive work maps to no single classified fix and is therefore treated as
|
|
// schema-writing, exactly like an unlisted fix name in filesystemOnlyFixes.
|
|
//
|
|
// `pollution --clean` and `validate --fix` deliberately have no entry: both
|
|
// delete or rewrite rows through an opened store.
|
|
func checkFlagFixName(flag string) string {
|
|
if flag == "artifacts" {
|
|
// --clean removes the same on-disk artifacts as the "Classic Artifacts"
|
|
// fix, which fix_gate.go classifies filesystem-only.
|
|
return "Classic Artifacts"
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// assessSchemaFixGate is the schema-gate assessor, indirected so tests can
|
|
// observe when and how often it is evaluated. Production always uses
|
|
// doctor.AssessSchemaFixGate.
|
|
var assessSchemaFixGate = doctor.AssessSchemaFixGate
|
|
|
|
// newSchemaGate returns this invocation's schema gate accessor (GH#4993). Lazy
|
|
// so a read-only path never probes the database, and memoised so every consumer
|
|
// in one invocation sees one verdict that repeats cannot disagree with.
|
|
func newSchemaGate(absPath string) func() doctor.FixGate {
|
|
return sync.OnceValue(func() doctor.FixGate {
|
|
return assessSchemaFixGate(absPath)
|
|
})
|
|
}
|
|
|
|
// destructiveCheckRefusal returns the refusal for a destructive `bd doctor
|
|
// --check=<flag>` the schema gate does not admit, or nil when the command may
|
|
// proceed (GH#4993). gate is an accessor rather than a value so a read-only
|
|
// --check never probes the database.
|
|
//
|
|
// The gate is consulted here, before the caller's switch dispatches to a
|
|
// handler, because the handler's own store open is the hazard: the migrating
|
|
// factory auto-starts a stopped server and applies pending migrations before the
|
|
// write lands.
|
|
func destructiveCheckRefusal(flag string, clean, fix bool, gate func() doctor.FixGate) error {
|
|
if !checkFlagWrites(flag, clean, fix) {
|
|
return nil
|
|
}
|
|
g := gate()
|
|
if !g.BlocksDestructiveWrites() {
|
|
return nil
|
|
}
|
|
// Filesystem-only cleanup is not what the gate is about: `bd doctor --fix`
|
|
// admits the same repair under the same blocked gate, so refusing it here
|
|
// would leave the two planes disagreeing about one operation.
|
|
if name := checkFlagFixName(flag); name != "" && g.AllowsFix(name) {
|
|
return nil
|
|
}
|
|
return HandleErrorWithHint(
|
|
fmt.Sprintf("refusing destructive 'bd doctor --check=%s': %s", flag, g.Reason),
|
|
"Re-run without --clean/--fix to inspect read-only, or resolve the schema state first",
|
|
)
|
|
}
|
|
|
|
// sanitizeFixAdvice rewrites each Fix tip in place so no emitter publishes
|
|
// advice the gate ruled unsafe (GH#4993). Index-based write is load-bearing:
|
|
// ranging by value over []doctorCheck mutates a copy.
|
|
func sanitizeFixAdvice(result *doctorResult, gate doctor.FixGate) {
|
|
if result == nil {
|
|
return
|
|
}
|
|
for i := range result.Checks {
|
|
if result.Checks[i].Fix == "" {
|
|
continue
|
|
}
|
|
result.Checks[i].Fix = doctor.SanitizeFixRecommendation(result.Checks[i].Fix, gate)
|
|
}
|
|
}
|
|
|
|
func printDiagnostics(result doctorResult, gate doctor.FixGate) {
|
|
// GH#4993: tips arrive already sanitized; do not re-assess the gate here.
|
|
|
|
// Pre-calculate counts and collect issues grouped by category
|
|
checksByCategory := make(map[string][]doctorCheck)
|
|
issuesByCategory := make(map[string][]doctorCheck)
|
|
var passCount, warnCount, failCount int
|
|
hasIssues := false
|
|
|
|
for _, check := range result.Checks {
|
|
cat := check.Category
|
|
if cat == "" {
|
|
cat = "Other"
|
|
}
|
|
checksByCategory[cat] = append(checksByCategory[cat], check)
|
|
|
|
switch check.Status {
|
|
case statusOK:
|
|
passCount++
|
|
case statusWarning:
|
|
warnCount++
|
|
issuesByCategory[cat] = append(issuesByCategory[cat], check)
|
|
hasIssues = true
|
|
case statusError:
|
|
failCount++
|
|
issuesByCategory[cat] = append(issuesByCategory[cat], check)
|
|
hasIssues = true
|
|
}
|
|
}
|
|
|
|
// Print header with version and summary
|
|
fmt.Printf("\nbd doctor v%s", result.CLIVersion)
|
|
fmt.Printf(" %s %s %d passed %s %d warnings %s %d errors\n",
|
|
ui.RenderSeparator(),
|
|
ui.RenderPassIcon(), passCount,
|
|
ui.RenderWarnIcon(), warnCount,
|
|
ui.RenderFailIcon(), failCount,
|
|
)
|
|
|
|
if doctorVerbose {
|
|
// Verbose mode: show all checks grouped by category
|
|
fmt.Println()
|
|
printAllChecks(checksByCategory)
|
|
}
|
|
|
|
// Print warnings/errors grouped by category
|
|
if hasIssues {
|
|
fmt.Println()
|
|
|
|
// Walk categories in defined order, only showing those with issues
|
|
for _, category := range doctor.CategoryOrder {
|
|
issues, exists := issuesByCategory[category]
|
|
if !exists || len(issues) == 0 {
|
|
continue
|
|
}
|
|
|
|
// Sort within category: errors first, then warnings
|
|
slices.SortStableFunc(issues, func(a, b doctorCheck) int {
|
|
if a.Status == statusError && b.Status != statusError {
|
|
return -1
|
|
}
|
|
if a.Status != statusError && b.Status == statusError {
|
|
return 1
|
|
}
|
|
return 0
|
|
})
|
|
|
|
// Category header
|
|
catChecks := checksByCategory[category]
|
|
catPass := 0
|
|
for _, c := range catChecks {
|
|
if c.Status == statusOK {
|
|
catPass++
|
|
}
|
|
}
|
|
fmt.Printf("%s %s\n", ui.RenderCategory(category),
|
|
ui.RenderMuted(fmt.Sprintf("(%d/%d passed)", catPass, len(catChecks))))
|
|
|
|
for _, check := range issues {
|
|
line := fmt.Sprintf("%s: %s", check.Name, check.Message)
|
|
if check.Status == statusError {
|
|
fmt.Printf(" %s %s\n", ui.RenderFailIcon(), ui.RenderFail(line))
|
|
} else {
|
|
fmt.Printf(" %s %s\n", ui.RenderWarnIcon(), line)
|
|
}
|
|
if check.Detail != "" {
|
|
fmt.Printf(" %s\n", ui.RenderMuted(check.Detail))
|
|
}
|
|
if check.Fix != "" {
|
|
lines := strings.Split(check.Fix, "\n")
|
|
for j, fixLine := range lines {
|
|
if j == 0 {
|
|
fmt.Printf(" %s%s\n", ui.MutedStyle.Render(ui.TreeLast), fixLine)
|
|
} else {
|
|
fmt.Printf(" %s\n", fixLine)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
// Handle "Other" category
|
|
if otherIssues, exists := issuesByCategory["Other"]; exists && len(otherIssues) > 0 {
|
|
fmt.Printf("%s\n", ui.RenderCategory("Other"))
|
|
for _, check := range otherIssues {
|
|
line := fmt.Sprintf("%s: %s", check.Name, check.Message)
|
|
if check.Status == statusError {
|
|
fmt.Printf(" %s %s\n", ui.RenderFailIcon(), ui.RenderFail(line))
|
|
} else {
|
|
fmt.Printf(" %s %s\n", ui.RenderWarnIcon(), line)
|
|
}
|
|
if check.Detail != "" {
|
|
fmt.Printf(" %s\n", ui.RenderMuted(check.Detail))
|
|
}
|
|
if check.Fix != "" {
|
|
lines := strings.Split(check.Fix, "\n")
|
|
for j, fixLine := range lines {
|
|
if j == 0 {
|
|
fmt.Printf(" %s%s\n", ui.MutedStyle.Render(ui.TreeLast), fixLine)
|
|
} else {
|
|
fmt.Printf(" %s\n", fixLine)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
if !doctorVerbose {
|
|
fmt.Printf("%s\n", ui.RenderMuted("Run with --verbose to see all checks"))
|
|
}
|
|
} else {
|
|
fmt.Println()
|
|
fmt.Printf("%s\n", ui.RenderPass("✓ All checks passed"))
|
|
if !doctorVerbose {
|
|
fmt.Printf("%s\n", ui.RenderMuted("Run with --verbose to see all checks"))
|
|
}
|
|
}
|
|
|
|
// GH#1095: Notify user about suppressed checks
|
|
if result.SuppressedCount > 0 {
|
|
noun := "warning"
|
|
if result.SuppressedCount > 1 {
|
|
noun = "warnings"
|
|
}
|
|
fmt.Printf("%s\n", ui.RenderMuted(fmt.Sprintf("(%d %s suppressed via doctor.suppress config)", result.SuppressedCount, noun)))
|
|
}
|
|
|
|
// GH#4993: surface the schema gate verdict assessed once in RunE.
|
|
if gate.Reason != "" {
|
|
fmt.Printf("\n%s Schema fix-gate: %s\n", ui.RenderWarn("⚠"), gate.Reason)
|
|
}
|
|
}
|
|
|
|
// printAllChecks prints all checks grouped by category with section headers.
|
|
func printAllChecks(checksByCategory map[string][]doctorCheck) {
|
|
// Print checks in defined category order
|
|
for _, category := range doctor.CategoryOrder {
|
|
checks, exists := checksByCategory[category]
|
|
if !exists || len(checks) == 0 {
|
|
continue
|
|
}
|
|
|
|
fmt.Println(ui.RenderCategory(category))
|
|
|
|
for _, check := range checks {
|
|
var statusIcon string
|
|
switch check.Status {
|
|
case statusOK:
|
|
statusIcon = ui.RenderPassIcon()
|
|
case statusWarning:
|
|
statusIcon = ui.RenderWarnIcon()
|
|
case statusError:
|
|
statusIcon = ui.RenderFailIcon()
|
|
}
|
|
|
|
fmt.Printf(" %s %s", statusIcon, check.Name)
|
|
if check.Message != "" {
|
|
fmt.Printf("%s", ui.RenderMuted(" "+check.Message))
|
|
}
|
|
fmt.Println()
|
|
|
|
if check.Detail != "" {
|
|
fmt.Printf(" %s%s\n", ui.MutedStyle.Render(ui.TreeLast), ui.RenderMuted(check.Detail))
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
// Print any checks without a known category
|
|
if otherChecks, exists := checksByCategory["Other"]; exists && len(otherChecks) > 0 {
|
|
fmt.Println(ui.RenderCategory("Other"))
|
|
for _, check := range otherChecks {
|
|
var statusIcon string
|
|
switch check.Status {
|
|
case statusOK:
|
|
statusIcon = ui.RenderPassIcon()
|
|
case statusWarning:
|
|
statusIcon = ui.RenderWarnIcon()
|
|
case statusError:
|
|
statusIcon = ui.RenderFailIcon()
|
|
}
|
|
fmt.Printf(" %s %s", statusIcon, check.Name)
|
|
if check.Message != "" {
|
|
fmt.Printf("%s", ui.RenderMuted(" "+check.Message))
|
|
}
|
|
fmt.Println()
|
|
if check.Detail != "" {
|
|
fmt.Printf(" %s%s\n", ui.MutedStyle.Render(ui.TreeLast), ui.RenderMuted(check.Detail))
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
}
|
|
|
|
// runMigrationValidation runs Dolt migration validation checks.
|
|
// Phase can be "pre" (before migration) or "post" (after migration).
|
|
// Outputs machine-parseable JSON when --json flag is set.
|
|
func runMigrationValidation(path string, phase string) error {
|
|
var check doctorCheck
|
|
var result doctor.MigrationValidationResult
|
|
|
|
switch phase {
|
|
case "pre":
|
|
dc, mr := doctor.CheckMigrationReadiness(path)
|
|
check = convertDoctorCheck(dc)
|
|
result = mr
|
|
case "post":
|
|
dc, mr := doctor.CheckMigrationCompletion(path)
|
|
check = convertDoctorCheck(dc)
|
|
result = mr
|
|
default:
|
|
return HandleError("invalid migration phase %q (use 'pre' or 'post')", phase)
|
|
}
|
|
|
|
if jsonOutput {
|
|
output := struct {
|
|
Check doctorCheck `json:"check"`
|
|
Validation doctor.MigrationValidationResult `json:"validation"`
|
|
CLIVersion string `json:"cli_version"`
|
|
Timestamp string `json:"timestamp"`
|
|
}{
|
|
Check: check,
|
|
Validation: result,
|
|
CLIVersion: Version,
|
|
Timestamp: time.Now().UTC().Format(time.RFC3339),
|
|
}
|
|
if err := outputJSON(output); err != nil {
|
|
return err
|
|
}
|
|
if !result.Ready {
|
|
return SilentExit()
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Human-readable output
|
|
fmt.Printf("\nbd doctor --migration=%s v%s\n\n", phase, Version)
|
|
|
|
// Print main status
|
|
var statusIcon string
|
|
switch check.Status {
|
|
case statusOK:
|
|
statusIcon = ui.RenderPassIcon()
|
|
case statusWarning:
|
|
statusIcon = ui.RenderWarnIcon()
|
|
case statusError:
|
|
statusIcon = ui.RenderFailIcon()
|
|
}
|
|
|
|
fmt.Printf("%s %s: %s\n", statusIcon, check.Name, check.Message)
|
|
if check.Detail != "" {
|
|
for _, line := range strings.Split(check.Detail, "\n") {
|
|
fmt.Printf(" %s\n", ui.RenderMuted(line))
|
|
}
|
|
}
|
|
|
|
// Print validation details
|
|
fmt.Println()
|
|
fmt.Println(ui.RenderCategory("Validation Details"))
|
|
fmt.Printf(" Backend: %s\n", result.Backend)
|
|
fmt.Printf(" JSONL Count: %d\n", result.JSONLCount)
|
|
if result.SQLiteCount > 0 {
|
|
fmt.Printf(" SQLite Count: %d\n", result.SQLiteCount)
|
|
}
|
|
if result.DoltCount > 0 {
|
|
fmt.Printf(" Dolt Count: %d\n", result.DoltCount)
|
|
}
|
|
fmt.Printf(" JSONL Valid: %v\n", result.JSONLValid)
|
|
if result.JSONLMalformed > 0 {
|
|
fmt.Printf(" Malformed Lines: %d\n", result.JSONLMalformed)
|
|
}
|
|
|
|
// Print warnings
|
|
if len(result.Warnings) > 0 {
|
|
fmt.Println()
|
|
fmt.Println(ui.RenderCategory("Warnings"))
|
|
for _, warn := range result.Warnings {
|
|
fmt.Printf(" %s %s\n", ui.RenderWarnIcon(), warn)
|
|
}
|
|
}
|
|
|
|
// Print errors
|
|
if len(result.Errors) > 0 {
|
|
fmt.Println()
|
|
fmt.Println(ui.RenderCategory("Errors"))
|
|
for _, err := range result.Errors {
|
|
fmt.Printf(" %s %s\n", ui.RenderFailIcon(), err)
|
|
}
|
|
}
|
|
|
|
// Print fix suggestion
|
|
if check.Fix != "" {
|
|
fmt.Println()
|
|
fmt.Printf("%s %s\n", ui.RenderMuted("Fix:"), check.Fix)
|
|
}
|
|
|
|
fmt.Println()
|
|
if result.Ready {
|
|
fmt.Printf("%s\n", ui.RenderPass("✓ Migration validation passed"))
|
|
return nil
|
|
}
|
|
fmt.Printf("%s\n", ui.RenderFail("✗ Migration validation failed"))
|
|
return SilentExit()
|
|
}
|