diff --git a/cmd/bd/doctor.go b/cmd/bd/doctor.go index 875a12a2d..ec8d81ca4 100644 --- a/cmd/bd/doctor.go +++ b/cmd/bd/doctor.go @@ -212,6 +212,9 @@ Examples: 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 { @@ -354,6 +357,57 @@ func init() { 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() } @@ -528,18 +582,32 @@ func runDiagnostics(path string) doctorResult { // Since doctor skips PersistentPreRun DB init (via skipStoreAnnotation), // trackBdVersion() and autoMigrateOnVersionBump() haven't run yet. // - // Scope version tracking to the doctor target. Without this, `bd doctor ` - // 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") - } + // #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 ` + // 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) + autoMigrateOnVersionBump(beadsDir) + } // Check 1b: Dolt format compatibility (GH#2137) // Must run before opening the database — old noms formats cause server panics. diff --git a/cmd/bd/doctor_mutation_gate_test.go b/cmd/bd/doctor_mutation_gate_test.go new file mode 100644 index 000000000..44d463c14 --- /dev/null +++ b/cmd/bd/doctor_mutation_gate_test.go @@ -0,0 +1,226 @@ +// Tests for doctor's mutation gate (#6028): `bd doctor --fix` / `--clean` must +// refuse to run under strict --readonly, exactly like the ~120 write commands +// that call CheckReadonly at the top of their RunE. Doctor never made that call +// — it opts out of the root PersistentPreRunE store init via +// skipStoreAnnotation, which also opted it out of that hook's gates — so both +// --readonly and an active MIGRATION-FREEZE were bypassed structurally. +// +// The freeze half of the same gate lives in migration_freeze_gate_test.go, +// beside the rest of the freeze suite; both halves share the helpers below and +// the hermetic subprocess harness declared there. +// +// This file MUST NOT carry a cgo build tag: it drives a bd binary built with +// the gms_pure_go tag via subprocess, and asserts only on files and output. + +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// doctorMutationSurface is one class of doctor invocation that mutates the +// workspace. Section 2 of the #6028 design enumerates the complete set: every +// mutating path is reached through --fix or --clean and nothing else, so these +// five rows cover the whole write surface, including fixers added later. +type doctorMutationSurface struct { + name string + args []string + // op is the operation label the gate reports, derived from which flag made + // the run mutating (--fix wins when both are set). + op string +} + +func doctorMutationSurfaces() []doctorMutationSurface { + return []doctorMutationSurface{ + {name: "fix", args: []string{"doctor", "--fix", "--yes"}, op: "doctor --fix"}, + {name: "fix-interactive", args: []string{"doctor", "--fix", "-i"}, op: "doctor --fix"}, + {name: "validate-fix", args: []string{"doctor", "--check=validate", "--fix", "--yes"}, op: "doctor --fix"}, + {name: "pollution-clean", args: []string{"doctor", "--check=pollution", "--clean", "--yes"}, op: "doctor --clean"}, + {name: "artifacts-clean", args: []string{"doctor", "--check=artifacts", "--clean", "--yes"}, op: "doctor --clean"}, + } +} + +// doctorWorkspaceFingerprint captures the two workspace files a refused doctor +// run is most likely to have touched: .local_version (trackBdVersion's target) +// and metadata.json (the Metadata Config / Database fixers' target). +func doctorWorkspaceFingerprint(t *testing.T, dir string) map[string][]byte { + t.Helper() + fingerprint := make(map[string][]byte) + for _, name := range []string{localVersionFile, "metadata.json"} { + path := filepath.Join(dir, ".beads", name) + data, err := os.ReadFile(path) + if err != nil { + if !os.IsNotExist(err) { + t.Fatalf("fingerprinting %s: %v", path, err) + } + continue + } + fingerprint[name] = data + } + return fingerprint +} + +// assertDoctorWorkspaceUnchanged proves the refusal happened before any +// mutation, not merely that the refusal message was printed. +func assertDoctorWorkspaceUnchanged(t *testing.T, dir string, before map[string][]byte) { + t.Helper() + after := doctorWorkspaceFingerprint(t, dir) + if len(after) != len(before) { + t.Errorf("workspace file set changed across a refused doctor run: had %d tracked files, now %d", len(before), len(after)) + } + for name, want := range before { + got, ok := after[name] + if !ok { + t.Errorf(".beads/%s was deleted by a refused doctor run", name) + continue + } + if string(got) != string(want) { + t.Errorf(".beads/%s was rewritten by a refused doctor run:\nbefore:\n%s\nafter:\n%s", name, want, got) + } + } +} + +// assertDoctorRefusalIsClean checks the shared shape of every gate refusal: +// nothing on stdout, and none of the output a fix or clean run would produce. +func assertDoctorRefusalIsClean(t *testing.T, stdout string) { + t.Helper() + if strings.TrimSpace(stdout) != "" { + t.Errorf("stdout should be empty when doctor is refused, got:\n%s", stdout) + } + for _, marker := range []string{"Applying fixes", "Deleting", "Verifying fixes"} { + if strings.Contains(stdout, marker) { + t.Errorf("refused doctor run produced %q on stdout — it started mutating before refusing:\n%s", marker, stdout) + } + } +} + +// TestDoctorMutationBlockedInReadonlyMode is the readonly half of the gate. +// One workspace serves every row: a refused run must leave it untouched, so a +// row that leaks a mutation is caught by the next row's fingerprint too. +func TestDoctorMutationBlockedInReadonlyMode(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + before := doctorWorkspaceFingerprint(t, dir) + + for _, tt := range doctorMutationSurfaces() { + t.Run(tt.name, func(t *testing.T) { + args := append(append([]string{}, tt.args...), "--readonly") + stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, args...) + + if code != 1 { + t.Fatalf("exit code = %d, want 1\nstdout:\n%s\nstderr:\n%s", code, stdout, stderr) + } + want := "operation '" + tt.op + "' is not allowed in read-only mode" + if !strings.Contains(stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, stderr) + } + assertDoctorRefusalIsClean(t, stdout) + assertDoctorWorkspaceUnchanged(t, dir, before) + }) + } +} + +// TestDoctorDiagnosisWorksInReadonlyMode pins the other half of the contract: +// the gate keys on --fix/--clean alone, so every diagnosis mode still runs +// under --readonly. Diagnosing a sandboxed workspace is the whole point. +func TestDoctorDiagnosisWorksInReadonlyMode(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + + for _, args := range [][]string{ + {"doctor"}, + {"doctor", "--dry-run"}, + {"doctor", "--check=pollution"}, + {"doctor", "--check=artifacts"}, + } { + t.Run(strings.Join(args, "_"), func(t *testing.T) { + stdout, stderr, _ := runBDMigrationFreeze(t, bd, dir, append(args, "--readonly")...) + if strings.Contains(stderr, "not allowed in read-only mode") { + t.Errorf("bd %v was refused under --readonly but mutates nothing:\nstderr:\n%s\nstdout:\n%s", args, stderr, stdout) + } + }) + } +} + +// TestDoctorMaintenanceSkippedInReadonlyMode is the readonly twin of +// TestDoctorMaintenanceSkippedDuringMigrationFreeze — see that test for why +// plain `bd doctor` had hidden writes at all, and for the shared-server setup. +func TestDoctorMaintenanceSkippedInReadonlyMode(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + seedStaleLocalVersion(t, dir) + + stdout, stderr, _ := runBDMigrationFreezeWithEnv(t, bd, dir, doctorMaintenanceEnv(), "doctor", "--readonly") + + assertDoctorReportedStaleVersionWithoutHealing(t, dir, stdout, stderr) + if strings.Contains(stderr, "not allowed in read-only mode") { + t.Errorf("plain 'bd doctor --readonly' must diagnose, not refuse:\nstderr:\n%s", stderr) + } +} + +// TestDoctorMutationNotBlockedWithoutGates is the regression-safety control: +// with no freeze sentinel and no --readonly, the gate must be invisible. The +// fix outcome itself is not this test's business — only that neither refusal +// fires and neither exit path is the gate's. +func TestDoctorMutationNotBlockedWithoutGates(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + + for _, tt := range doctorMutationSurfaces() { + t.Run(tt.name, func(t *testing.T) { + stdout, stderr, code := runBDMigrationFreeze(t, bd, dir, tt.args...) + if code == ExitMigrationFrozen || strings.Contains(stderr, "frozen for migration") { + t.Errorf("bd %v hit the freeze gate with no marker present (exit %d):\nstderr:\n%s", tt.args, code, stderr) + } + if strings.Contains(stderr, "not allowed in read-only mode") { + t.Errorf("bd %v hit the readonly gate without --readonly (exit %d):\nstderr:\n%s", tt.args, code, stderr) + } + _ = stdout + }) + } +} + +// TestDoctorMaintenanceStillRunsWithoutGates is the companion control for the +// diagnosis-path change: unfrozen and not read-only, plain `bd doctor` must +// still reconcile a stale .local_version exactly as it did before #6028. +func TestDoctorMaintenanceStillRunsWithoutGates(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + seedStaleLocalVersion(t, dir) + + stdout, stderr, _ := runBDMigrationFreezeWithEnv(t, bd, dir, doctorMaintenanceEnv(), "doctor") + + if !strings.Contains(stderr, "auto-migrate:") { + t.Errorf("expected autoMigrateOnVersionBump to run (an 'auto-migrate:' debug line) with no gate active, got none:\nstderr:\n%s", stderr) + } + got := readWorkspaceLocalVersion(t, dir) + if got == staleLocalVersion { + t.Errorf("%s = %q — trackBdVersion did not run with no gate active; the #6028 skip is too broad:\nstdout:\n%s", + localVersionFile, got, stdout) + } +} + +// TestDoctorReadonlyWinsOverMigrationFreeze pins the branch order inside the +// gate: --readonly is checked first, so a workspace that is both frozen and +// sandboxed reports the readonly refusal. This mirrors CheckReadonly, which +// also answers readonly before delegating to the freeze check. Either refusal +// stops the run, but they carry different exit codes — 1 vs ExitMigrationFrozen +// — so which one wins is observable, and the precedence has to be deliberate. +func TestDoctorReadonlyWinsOverMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + writeFreezeMarker(t, dir, "migrator", "dolt v2 migration") + before := doctorWorkspaceFingerprint(t, dir) + + stdout, stderr, code := runBDFrozen(t, bd, dir, "doctor", "--fix", "--yes", "--readonly") + + if code != 1 { + t.Fatalf("exit code = %d, want 1 (not %d — readonly is answered before the freeze)\nstdout:\n%s\nstderr:\n%s", + code, ExitMigrationFrozen, stdout, stderr) + } + if !strings.Contains(stderr, "operation 'doctor --fix' is not allowed in read-only mode") { + t.Errorf("stderr missing the readonly refusal (readonly must be checked before the freeze):\n%s", stderr) + } + if strings.Contains(stderr, "frozen for migration") { + t.Errorf("stderr carries the freeze refusal too; the gate should report exactly one reason:\n%s", stderr) + } + assertDoctorRefusalIsClean(t, stdout) + assertDoctorWorkspaceUnchanged(t, dir, before) +} diff --git a/cmd/bd/errors.go b/cmd/bd/errors.go index 02bea8351..f06d94b81 100644 --- a/cmd/bd/errors.go +++ b/cmd/bd/errors.go @@ -308,7 +308,16 @@ func migrationFreezeErrorFor(operation string, extraRoots ...string) error { // paths that keep running while frozen but must not apply version tracking or // schema auto-migration. func migrationFreezeActive() bool { - return migration.Find(freezeSearchRoots()...).Frozen() + return migrationFreezeActiveFor() +} + +// migrationFreezeActiveFor is migrationFreezeActive against extra roots — the +// probe half of the migrationFreezeErrorFor pair, for a diagnosis path handed a +// workspace that is not the one bd was launched in. `bd doctor /frozen/repo` +// skips its own maintenance writes on the strength of this, so it has to look +// at the tree it is about to write to and not just at the caller's cwd. +func migrationFreezeActiveFor(extraRoots ...string) bool { + return migration.Find(freezeRootsWith(extraRoots)...).Frozen() } func freezeRootsWith(extraRoots []string) []string { diff --git a/cmd/bd/migration_freeze_gate_test.go b/cmd/bd/migration_freeze_gate_test.go index ae74990a1..5210ec748 100644 --- a/cmd/bd/migration_freeze_gate_test.go +++ b/cmd/bd/migration_freeze_gate_test.go @@ -851,6 +851,220 @@ func TestAutoMigrateSkippedDuringMigrationFreeze(t *testing.T) { } } +// TestDoctorMutationBlockedDuringMigrationFreeze covers the freeze half of +// doctor's mutation gate (#6028). Doctor was the one write-capable command the +// dc-6jaq gate above never reached: it carries skipStoreAnnotation, so the root +// PersistentPreRunE returns before its freeze check ever runs, and doctor's own +// RunE never called CheckReadonly. Its fixers then opened stores directly — two +// of them by shelling out to a child bd — and mutated straight through an +// active freeze. +// +// One row per writing surface class. The gate fires before doctor's +// embedded-mode gate, so these refusals need no Dolt server, and the +// interactive row proves the refusal precedes any prompt (stdin is closed; a +// hang here is the failure). +func TestDoctorMutationBlockedDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + marker := writeFreezeMarker(t, dir, "migrator", "dolt v2 migration") + before := doctorWorkspaceFingerprint(t, dir) + + for _, tt := range doctorMutationSurfaces() { + t.Run(tt.name, func(t *testing.T) { + stdout, stderr, code := runBDFrozen(t, bd, dir, tt.args...) + + if code != ExitMigrationFrozen { + t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr) + } + for _, want := range []string{ + "workspace is frozen for migration", + "bd " + tt.op + " is blocked by the freeze marker at " + marker, + "To resume writes, remove that file.", + } { + if !strings.Contains(stderr, want) { + t.Errorf("stderr missing %q:\n%s", want, stderr) + } + } + assertVendorNeutral(t, stderr) + assertDoctorRefusalIsClean(t, stdout) + assertDoctorWorkspaceUnchanged(t, dir, before) + }) + } +} + +// TestDoctorPathArgBlockedByTargetFreeze covers the reason doctor's gate takes +// the resolved target path: doctor is the only write-capable command that +// operates on a directory named on the command line, so keying the lookup on +// the caller's cwd alone would let `bd doctor /frozen/repo --fix` walk an +// entirely unrelated tree and mutate straight through the marker. +func TestDoctorPathArgBlockedByTargetFreeze(t *testing.T) { + target := t.TempDir() + bd := setupMigrationFreezeWorkspaceIn(t, target) + marker := writeFreezeMarker(t, target, "migrator", "dolt v2 migration") + before := doctorWorkspaceFingerprint(t, target) + + // cwd is an unrelated, unfrozen workspace; only the target is frozen. + outside := t.TempDir() + setupMigrationFreezeWorkspaceIn(t, outside) + + stdout, stderr, code := runBDFrozen(t, bd, outside, "doctor", target, "--fix", "--yes") + + if code != ExitMigrationFrozen { + t.Fatalf("exit code = %d, want %d\nstdout:\n%s\nstderr:\n%s", code, ExitMigrationFrozen, stdout, stderr) + } + if !strings.Contains(stderr, marker) { + t.Errorf("refusal should name the target's own marker %q:\n%s", marker, stderr) + } + assertVendorNeutral(t, stderr) + assertDoctorRefusalIsClean(t, stdout) + assertDoctorWorkspaceUnchanged(t, target, before) +} + +// TestDoctorPathArgMaintenanceSkippedByTargetFreeze is the diagnosis-side twin: +// plain `bd doctor ` writes .local_version into the *target*, so the skip +// probe has to key on the target too, not merely on where bd was launched. +func TestDoctorPathArgMaintenanceSkippedByTargetFreeze(t *testing.T) { + target := t.TempDir() + bd := setupMigrationFreezeWorkspaceIn(t, target) + seedStaleLocalVersion(t, target) + writeFreezeMarker(t, target, "migrator", "dolt v2 migration") + + outside := t.TempDir() + setupMigrationFreezeWorkspaceIn(t, outside) + + _, stderr, _ := runBDMigrationFreezeWithEnv(t, bd, outside, + append(freezeWalkEnv(), doctorMaintenanceEnv()...), "doctor", target) + + if got := readWorkspaceLocalVersion(t, target); got != staleLocalVersion { + t.Errorf("%s in the frozen target = %q, want unchanged %q — the maintenance probe keyed on cwd, not on the target", + localVersionFile, got, staleLocalVersion) + } + if strings.Contains(stderr, "auto-migrate:") { + t.Errorf("autoMigrateOnVersionBump ran against a frozen target:\n%s", stderr) + } +} + +// TestDoctorDiagnosisWorksDuringMigrationFreeze is the constraint that shapes +// the whole gate: a freeze is exactly when an operator needs to diagnose, so +// every non-mutating doctor mode must keep running. The gate keys on +// --fix/--clean and nothing else. +func TestDoctorDiagnosisWorksDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + writeFreezeMarker(t, dir, "migrator", "dolt v2 migration") + + for _, args := range [][]string{ + {"doctor"}, + {"doctor", "--check=pollution"}, + {"doctor", "--check=artifacts"}, + {"doctor", "--check=conventions"}, + } { + t.Run(strings.Join(args, "_"), func(t *testing.T) { + stdout, stderr, code := runBDFrozen(t, bd, dir, args...) + if code == ExitMigrationFrozen || strings.Contains(stderr, "frozen for migration") { + t.Errorf("bd %v was refused during a freeze but mutates nothing (exit %d):\nstderr:\n%s\nstdout:\n%s", + args, code, stderr, stdout) + } + }) + } +} + +// TestDoctorDryRunWorksDuringMigrationFreeze pins the dry-run boundary: plain +// --dry-run only previews and stays available, while --fix --dry-run is +// refused (the gate reads the mutating flag, not the preview flag — the same +// posture the freeze gate takes on every other command's --dry-run). +func TestDoctorDryRunWorksDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + writeFreezeMarker(t, dir, "migrator", "dolt v2 migration") + + stdout, stderr, code := runBDFrozen(t, bd, dir, "doctor", "--dry-run") + if code == ExitMigrationFrozen || strings.Contains(stderr, "frozen for migration") { + t.Errorf("'bd doctor --dry-run' previews only and must not be refused (exit %d):\nstderr:\n%s\nstdout:\n%s", code, stderr, stdout) + } + + stdout, stderr, code = runBDFrozen(t, bd, dir, "doctor", "--fix", "--dry-run") + if code != ExitMigrationFrozen || !strings.Contains(stderr, "workspace is frozen for migration") { + t.Errorf("'bd doctor --fix --dry-run' must be refused (exit %d, want %d):\nstderr:\n%s\nstdout:\n%s", + code, ExitMigrationFrozen, stderr, stdout) + } +} + +// staleLocalVersion is an implausibly old recorded version: it forces +// trackBdVersion to see a version "bump" so the maintenance work under test +// actually does something observable instead of short-circuiting. +const staleLocalVersion = "0.0.1" + +func seedStaleLocalVersion(t *testing.T, dir string) { + t.Helper() + path := filepath.Join(dir, ".beads", localVersionFile) + if err := os.WriteFile(path, []byte(staleLocalVersion+"\n"), 0644); err != nil { + t.Fatalf("writing stale %s: %v", localVersionFile, err) + } +} + +// readWorkspaceLocalVersion reads .beads/.local_version out of a test +// workspace (the production readLocalVersion takes the file path directly). +func readWorkspaceLocalVersion(t *testing.T, dir string) string { + t.Helper() + data, err := os.ReadFile(filepath.Join(dir, ".beads", localVersionFile)) + if err != nil { + t.Fatalf("reading %s: %v", localVersionFile, err) + } + return strings.TrimSpace(string(data)) +} + +// doctorMaintenanceEnv puts doctor on its full diagnosis path. runDiagnostics — +// where the maintenance calls under test live — sits behind doctor's +// embedded-mode gate, so the workspace has to look server-backed; +// BEADS_DOLT_SHARED_SERVER is enough, and no server needs to answer, because +// the maintenance block runs before doctor opens its shared store. BD_DEBUG +// surfaces autoMigrateOnVersionBump's own "auto-migrate:" logging, so the +// absence of that line is direct evidence the function was never entered. +func doctorMaintenanceEnv() []string { + return []string{"BEADS_DOLT_SHARED_SERVER=1", "BD_DEBUG=1"} +} + +// assertDoctorReportedStaleVersionWithoutHealing is the #6028 diagnosis +// contract in one place: doctor reports the version mismatch as a finding and +// leaves the store alone. +func assertDoctorReportedStaleVersionWithoutHealing(t *testing.T, dir, stdout, stderr string) { + t.Helper() + if got := readWorkspaceLocalVersion(t, dir); got != staleLocalVersion { + t.Errorf("%s = %q, want unchanged %q — doctor's diagnosis rewrote it through an active gate", + localVersionFile, got, staleLocalVersion) + } + if strings.Contains(stderr, "auto-migrate:") { + t.Errorf("autoMigrateOnVersionBump ran its store-opening body during a gated 'bd doctor' "+ + "(found an 'auto-migrate:' debug line) — diagnosis must not apply schema migrations:\n%s", stderr) + } + if !strings.Contains(stdout, "Version Tracking") || !strings.Contains(stdout, staleLocalVersion) { + t.Errorf("doctor should still REPORT the stale version %q as a finding, not silently skip it:\n%s", + staleLocalVersion, stdout) + } +} + +// TestDoctorMaintenanceSkippedDuringMigrationFreeze is the regression test for +// the sharpest half of #6028: plain `bd doctor` — no --fix, no --clean — wrote +// to a frozen store. runDiagnostics re-implements PersistentPreRunE's two +// maintenance side effects (trackBdVersion, autoMigrateOnVersionBump) because +// doctor skips that hook, but it inherited none of the hook's guards, so it +// rewrote .beads/.local_version and could auto-apply a schema migration +// mid-freeze — the exact torn-upgrade write the freeze exists to prevent. +// +// This is the doctor-side twin of TestAutoMigrateSkippedDuringMigrationFreeze +// above, which pins the same two calls on the PersistentPreRunE path. +func TestDoctorMaintenanceSkippedDuringMigrationFreeze(t *testing.T) { + bd, dir := setupMigrationFreezeWorkspace(t) + seedStaleLocalVersion(t, dir) + writeFreezeMarker(t, dir, "migrator", "dolt v2 migration") + + stdout, stderr, code := runBDMigrationFreezeWithEnv(t, bd, dir, + append(freezeWalkEnv(), doctorMaintenanceEnv()...), "doctor") + + assertDoctorReportedStaleVersionWithoutHealing(t, dir, stdout, stderr) + if code == ExitMigrationFrozen || strings.Contains(stderr, "frozen for migration") { + t.Errorf("plain 'bd doctor' must diagnose during a freeze, not refuse (exit %d):\nstderr:\n%s", code, stderr) + } +} + // TestAutoMigrateStillRunsWithoutFreeze is the companion regression-safety // check for the ask-#2 fix: without a freeze marker, the new early gate in // PersistentPreRunE must not interfere with autoMigrateOnVersionBump's normal