beads/cmd/bd/migrate.go
Steve Yegge 70f9e2f8a3
Beads 1.2 remediation: migration-consent gate — bd never migrates an existing database without explicit consent (#5764)
* feat(schema): never migrate an existing database without explicit consent (bd-qhn8y)

Beads 1.2 release remediation. 1.2.0/1.2.1 auto-applied migrations 54-65 at
store open on ANY command, including reads; older binaries then refuse the
migrated database. MigrateUp now refuses pending main-sequence migrations on
an existing database before any write (dolt_ignore seeding included) unless
the operator consented: bd migrate / bd migrate schema (preview flags
withhold), bd migrate --force, or BD_ALLOW_MIGRATE=1
(BD_ALLOW_REMOTE_MIGRATE honored as an alias). Fresh init and at-latest
databases are unaffected; the #4259 remote gate keeps all its protections.

Also: freeze shipped migrations (hash-pin test, main 0001-0065 + ignored
0001-0024), retract v1.2.0/v1.2.1 in go.mod, agent-executable un-migrate
runbook (docs/recovery/unmigrate-schema-v65.md), and the upgrade smoke +
historical migration harnesses now model the consent contract and assert
the refusal carries guidance.

No version bump here by design: cutting the release stays with the release
owner.

Rebased onto main 800d43eb8d: the go.mod retract hunk is dropped -
main already retracts v1.2.0/v1.2.1 (and v1.1.1) since #5782. The
uow consent grant moves into the TestMain main added in #6441 (a
second TestMain no longer compiles), and the new files are listed
in the BUILD.bazel targets main now carries (gazelle).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix(schema): cloned-workspace bootstrap carries creation-consent (bd-qhn8y)

The consent gate treated a workspace `bd init --remote` / `bd bootstrap`
just cloned into existence like a pre-existing database, refusing the
smart gate's provably-safe first-mover migration and stranding init in
the generic open-error path (bypassing the bd-4mpy7 finalize+guidance
ergonomics). Cloning IS creating: those paths now record consent
explicitly, and the #4259 remote-migrate gate still applies to them
unchanged (consent is not its designated-migrator override). Fixes CI
TestEmbeddedInit/remote_behind_schema_gate.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* test(migration): consent first in main's wisp lanes too (bd-qhn8y)

The rebase onto 800d43eb8d brought in #6049's wisp-plane lanes, which
postdate this PR's harness changes. Each one makes an ordinary candidate
command the first touch on an old-schema database, and the consent gate
refuses it:

- historical-dolt-upgrade-test.sh run_wisp_plane_upgrade opens with
  `bd list` before any migrate: "candidate could not open the seeded
  wisp workspace" for v1.0.1, v1.1.0, v1.1.2 and v1.2.2 (the
  Migration Test Harness dolt-runtime shard).
- run_dirty_tracked_wisp_scenario (v1.1.2): the consent refusal stops
  the open before MigrateUp reaches the #5816 dirty tables, so the lane
  fails "without naming them".
- upgrade-smoke-test.sh "Wisp plane survives upgrade" upgrades with a
  bare cand_init, so list/ready/blocked/update all hit the refusal
  (4 failures each for v1.3.0 and v1.3.1, both in the PR smoke set).

Use the PR's own pattern: the explicit `bd migrate schema` is the first
candidate touch (cand_upgrade in the smoke script). Base 800d43eb8d
passes these lanes unchanged; with this fixup the full 14-version
historical corpus and all five PR smoke versions pass.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(schema): close consent-gate review findings (bd-qhn8y)

Review fixes for the migration-consent gate (adopt-pr review, attempts
1 and 2).

Majors:

- #4566 deadlock rebuilt one check earlier: on a database that is both
  behind and dirty, the consent refusal fired before the dirty-table
  guard, whose remedy (`bd dolt commit`) opens without consent. The
  working-set-reconcile opens now tolerate MigrateConsentError: embedded
  (toleratesConsentRefusal, WSR intent only) and server mode
  (LenientOpen's warnLenientOpenRefusal) print WorkingSetWarning and
  commit at the current schema; strict, read-only and RemoteSync opens
  still refuse. Covered by an embedded test (a refused open writes
  nothing: dolt_status, dolt_ignore and schema_migrations unchanged) and
  a server-mode integration subtest.
- Bare `bd migrate` consented: isMigrateConsentCommand now matches only
  the schema verb, so `bd migrate` (metadata reconcile, including
  --update-repo-id, --inspect and --dry-run) no longer consents to a
  one-way migration; `bd migrate schema` and --force do.
  TestLocalMigrateConsentScope pins the scope through the root pre-run.
  The dirty-table warnings name `bd migrate schema` accordingly.
- Runnable JSON hint: the JSON refusal follows the #4259 AgentDirective
  convention, a non-runnable hint plus a migrate_consent object
  (versions, pending, severity, human_decision_required, options) whose
  commands are retargeted with --global for the shared global database.
  The text refusal prints the same --global hint under `bd --global`.
- Freeze floor: the hash-pinned freeze now covers what v1.3.x shipped,
  main 0001-0066 and ignored 0001-0026; the CHANGELOG puts new
  migrations in 0070+ / 0028+.
- Fresh-bootstrap heal: MigrateUpWithLock with heal authority takes the
  consent-free migrate path, so a retried bd init whose first pass left
  a non-zero cursor converges; other lock callers keep the gate.

Minors: the uow team-server guards are repinned on `bd migrate schema`;
the un-migrate runbook is linked from the recovery index and
cross-linked with the 1.2.1 repair-forward doc; the CHANGELOG BREAKING
entry matches the shipped contract; harness comment grammar.

Docs: the user docs and README named bare `bd migrate` as the step that
applies schema migrations; they now say `bd migrate schema`, which also
exists in the pinned docs release (v1.2.2) and in v1.3.x. The
`bd migrate schema` help no longer claims migrations run automatically
on store open. The Go remedy that sends a remote-gate stop to bare
`bd migrate` for its migrate-or-adopt options is unchanged (pinned by
TestNoticeSharedMigrateRefusalPerDecision).

Upgrade smoke (attempt 2): the consent-gate assertion is graded only when
the old binary left a database. Releases before v1.0 have no
`init --non-interactive`, so prev_init creates nothing there and the
candidate's `bd list` fails with "no beads database found", which has no
consent guidance. Main's Bazel smoke lane (#7331) runs the newest 30
releases, 20 of them pre-1.0, under the required ci-gate; all 20 went red
on the merge. The 10 v1.x releases still take the refusal branch.

Shard manifest (pre-approval CI): the new embedded test
TestEmbeddedMigrateConsent_BehindAndDirtyWorkingSetReconcileRecovers is
listed in the Bazel 15-shard block of embedded-storage-test-shards.txt
(incremental --write; shard 15). Main's ci lane runs
TestStorageEmbeddedShardManifestGeneratorNotStale in //scripts:scripts_test,
which fails on any unlisted top-level embeddeddolt test.

Not addressed (optional): env-only consent docs for embedders, the
unparseable BD_ALLOW_REMOTE_MIGRATE alias hint, and the harness
`|| true` on `cand migrate schema`.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Eddie the Engineer <julianknutsen@users.noreply.github.com>
Co-authored-by: Eddie the Engineer <adopt-pr@gascity.com>
2026-10-08 08:21:31 +00:00

958 lines
31 KiB
Go

package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/debug"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/schema"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
"github.com/steveyegge/beads/issueops"
)
var migrateCmd = &cobra.Command{
Use: "migrate",
GroupID: "maint",
Short: "Database migration commands",
Long: `Database migration and data transformation commands.
Without subcommand, checks and updates database metadata to current version.
Subcommands:
hooks Plan git hook migration to marker-managed format
issues Move issues between repositories
schema Apply pending schema migrations (idempotent)
sync Set up sync.branch workflow for multi-clone setups
from-server-to-proxied-server [EXPERIMENTAL] Switch server mode to proxied-server mode
from-proxied-server-to-server [EXPERIMENTAL] Switch proxied-server mode to server mode
from-shared-server-to-proxied-server [EXPERIMENTAL] Switch shared-server mode to proxied-server mode
from-proxied-server-to-shared-server [EXPERIMENTAL] Switch proxied-server mode to shared-server mode
On a remote-backed database with pending schema migrations bd refuses to
migrate in place (#4259): migrating two clones independently forks the schema
so bd dolt pull can no longer merge — the break is silent and unrecoverable.
Use --force to confirm you are the single designated migrator, after which you
should publish the migrated schema with 'bd dolt push'. The env-var equivalent
BD_ALLOW_REMOTE_MIGRATE=1 remains supported for scripted/CI use.
`,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, _ []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("migrate is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("migrate")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
autoYes, _ := cmd.Flags().GetBool("yes")
dryRun, _ := cmd.Flags().GetBool("dry-run")
updateRepoID, _ := cmd.Flags().GetBool("update-repo-id")
inspect, _ := cmd.Flags().GetBool("inspect")
if !dryRun && !inspect {
CheckReadonly("migrate")
}
if updateRepoID {
return handleUpdateRepoID(dryRun, autoYes)
}
if inspect {
return handleInspect()
}
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
cfg, err := loadOrCreateConfig(beadsDir)
if err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "config_load_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("failed to load config: %v", err)
}
return handleDoltMetadataUpdate(cfg, beadsDir, dryRun)
},
}
// handleDoltMetadataUpdate handles version metadata updates for Dolt backends.
// beadsDir is the resolved .beads directory (honoring -C); repo-derived metadata
// is computed from it rather than the process cwd so `bd -C <dir> migrate`
// fingerprints the target repo, not the caller's (GH#4361).
func handleDoltMetadataUpdate(cfg *configfile.Config, beadsDir string, dryRun bool) error {
ctx := rootCtx
store := getStore()
if store == nil {
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": "no_databases",
"message": "No Dolt database found in .beads/",
})
}
fmt.Fprintf(os.Stderr, "No Dolt database found. Run 'bd init' to create a new database.\n")
return nil
}
currentVersion, _ := store.GetLocalMetadata(ctx, "bd_version")
currentRepoID, _ := store.GetMetadata(ctx, "repo_id")
currentCloneID, _ := store.GetMetadata(ctx, "clone_id")
needsVersionUpdate := currentVersion != Version
needsRepoID := currentRepoID == ""
needsCloneID := currentCloneID == ""
if !needsVersionUpdate && !needsRepoID && !needsCloneID {
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": "current",
"message": fmt.Sprintf("Dolt database already at version %s", Version),
})
}
fmt.Printf("Dolt database version: %s\n", currentVersion)
fmt.Printf("%s\n", ui.RenderPass("✓ Version matches"))
fmt.Printf("%s\n", ui.RenderPass("✓ All metadata fields present"))
return nil
}
if dryRun {
dryRunResult := map[string]interface{}{
"dry_run": true,
"needs_version_update": needsVersionUpdate,
"needs_repo_id": needsRepoID,
"needs_clone_id": needsCloneID,
}
if needsVersionUpdate {
dryRunResult["current_version"] = currentVersion
dryRunResult["target_version"] = Version
}
if jsonOutput {
return outputJSON(dryRunResult)
}
fmt.Println("Dry run mode - no changes will be made")
if needsVersionUpdate {
fmt.Printf("Would update Dolt version: %s → %s\n", currentVersion, Version)
}
if needsRepoID {
fmt.Println("Would set repo_id")
}
if needsCloneID {
fmt.Println("Would set clone_id")
}
return nil
}
versionUpdated := false
repoIDSet := false
cloneIDSet := false
// Update bd_version if needed
if needsVersionUpdate {
if !jsonOutput {
fmt.Printf("Updating Dolt schema version: %s → %s\n", currentVersion, Version)
}
// Detect and set issue_prefix if missing
prefix, err := store.GetConfig(ctx, "issue_prefix")
if err != nil || prefix == "" {
issues, err := store.SearchIssues(ctx, "", types.IssueFilter{})
if err == nil && len(issues) > 0 {
detectedPrefix := utils.ExtractIssuePrefix(issues[0].ID)
if detectedPrefix != "" {
if err := store.SetConfig(ctx, "issue_prefix", detectedPrefix); err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to set issue prefix: %v\n", err)
}
} else if !jsonOutput {
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("✓ Detected and set issue prefix: %s", detectedPrefix)))
}
}
}
}
if err := store.SetLocalMetadata(ctx, "bd_version", Version); err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "version_update_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("failed to update version: %v", err)
}
versionUpdated = true
if !jsonOutput {
fmt.Printf("%s\n", ui.RenderPass("✓ Version updated"))
}
}
// Set repo_id if missing (non-fatal — may fail in non-git environments)
if needsRepoID {
computed, err := beads.ComputeRepoIDForPath(beadsDir)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: could not compute repo_id: %v\n", err)
}
} else {
if err := store.SetMetadata(ctx, "repo_id", computed); err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to set repo_id: %v\n", err)
}
} else {
repoIDSet = true
if !jsonOutput {
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("✓ Set repo_id: %s", truncateID(computed, 8))))
}
}
}
}
// Set clone_id if missing (non-fatal — may fail in non-git environments)
if needsCloneID {
computed, err := beads.GetCloneIDForPath(beadsDir)
if err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: could not compute clone_id: %v\n", err)
}
} else {
if err := store.SetMetadata(ctx, "clone_id", computed); err != nil {
if !jsonOutput {
fmt.Fprintf(os.Stderr, "Warning: failed to set clone_id: %v\n", err)
}
} else {
cloneIDSet = true
if !jsonOutput {
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("✓ Set clone_id: %s", truncateID(computed, 8))))
}
}
}
}
if versionUpdated || repoIDSet || cloneIDSet {
commandDidWrite.Store(true)
}
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": "success",
"current_database": cfg.Database,
"backend": "dolt",
"version": Version,
"version_updated": versionUpdated,
"repo_id_set": repoIDSet,
"clone_id_set": cloneIDSet,
})
}
fmt.Printf("\nDolt database: %s (version %s)\n", cfg.Database, Version)
return nil
}
// truncateID safely truncates an ID string to maxLen characters.
func truncateID(id string, maxLen int) string {
if len(id) <= maxLen {
return id
}
return id[:maxLen]
}
// loadOrCreateConfig loads metadata.json or creates default if not found
func loadOrCreateConfig(beadsDir string) (*configfile.Config, error) {
cfg, err := configfile.Load(beadsDir)
if err != nil {
return nil, err
}
// Create default if no config exists
if cfg == nil {
cfg = configfile.DefaultConfig()
}
return cfg, nil
}
// pathHashRepoIDStampNotice returns the propagation warning for replacing an
// existing repository ID with a path-derived one, or "" when none applies
// (no stored id, no change, or a remote-derived new id).
func pathHashRepoIDStampNotice(oldRepoID, newRepoID string, source beads.RepoIDSource) string {
if oldRepoID == "" || oldRepoID == newRepoID || source != beads.RepoIDSourcePath {
return ""
}
return "Warning: stamping a path-hash repository ID (this checkout has no origin remote).\n" +
"It is local to this host but will propagate to every clone on the next sync.\n" +
"On a synced clone, keep the stored ID instead (see 'bd doctor').\n"
}
func handleUpdateRepoID(dryRun bool, autoYes bool) error {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "no_database",
"message": "No beads database found. " + diagHint() + ".",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint("no beads database found", diagHint())
}
// Compute new repo ID from the resolved .beads directory (honoring -C),
// not the process cwd. Otherwise `bd -C <dir> migrate --update-repo-id`
// stamps the target DB with the caller repo's fingerprint and the bad
// value propagates to every clone on the next sync (GH#4361).
newRepoID, newRepoIDSource, err := beads.ComputeRepoIDForPathWithSource(beadsDir)
if err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "compute_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("failed to compute repository ID: %v", err)
}
store := getStore()
if store == nil {
return HandleError("no database — run 'bd init' first")
}
ctx := rootCtx
oldRepoID, err := store.GetMetadata(ctx, "repo_id")
if err != nil && err.Error() != "metadata key not found: repo_id" {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "read_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("failed to read repo_id: %v", err)
}
oldDisplay := "none"
if len(oldRepoID) >= 8 {
oldDisplay = oldRepoID[:8]
}
if dryRun {
if jsonOutput {
return outputJSON(map[string]interface{}{
"dry_run": true,
"old_repo_id": oldDisplay,
"new_repo_id": truncateID(newRepoID, 8),
})
}
fmt.Println("Dry run mode - no changes will be made")
fmt.Printf("Would update repository ID:\n")
fmt.Printf(" Old: %s\n", oldDisplay)
fmt.Printf(" New: %s\n", truncateID(newRepoID, 8))
return nil
}
if oldRepoID != "" && oldRepoID != newRepoID && !autoYes && !jsonOutput {
fmt.Printf("WARNING: Changing repository ID can break sync if other clones exist.\n")
// bd-46vla: repo_id lives in the versioned metadata table, so the new
// value propagates to every clone on the next sync. A path-fallback id
// (no origin remote here) is host-local — stamping it into shared
// state is almost never right on a synced clone.
if newRepoIDSource == beads.RepoIDSourcePath {
fmt.Printf("The new ID is a path hash (this checkout has no origin remote); it is\n")
fmt.Printf("local to this host but will propagate to every clone on the next sync.\n")
fmt.Printf("On a synced clone, keep the stored ID instead (see 'bd doctor').\n")
}
fmt.Printf("\n")
fmt.Printf("Current repo ID: %s\n", oldDisplay)
fmt.Printf("New repo ID: %s\n\n", truncateID(newRepoID, 8))
fmt.Printf("Continue? [y/N] ")
var response string
_, _ = fmt.Scanln(&response)
if strings.ToLower(response) != "y" && strings.ToLower(response) != "yes" {
fmt.Println("Canceled")
return nil
}
}
// bd-ek28z: --yes and --json skip the confirm block above, so scripted
// callers stamped a host-local path hash with no warning at all — the
// GH#4361 recurrence hole. Print the notice (not the prompt) on those
// paths too.
pathHashNotice := pathHashRepoIDStampNotice(oldRepoID, newRepoID, newRepoIDSource)
if pathHashNotice != "" && (autoYes || jsonOutput) {
fmt.Fprint(os.Stderr, pathHashNotice)
}
if err := store.SetMetadata(ctx, "repo_id", newRepoID); err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "update_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("failed to update repo_id: %v", err)
}
commandDidWrite.Store(true)
if jsonOutput {
payload := map[string]interface{}{
"status": "success",
"old_repo_id": oldDisplay,
"new_repo_id": truncateID(newRepoID, 8),
"repo_id_source": string(newRepoIDSource),
}
if pathHashNotice != "" {
payload["warning"] = "new repository ID is a path hash (no origin remote); it will propagate to every clone on the next sync"
}
return outputJSON(payload)
}
fmt.Printf("%s\n\n", ui.RenderPass("✓ Repository ID updated"))
fmt.Printf(" Old: %s\n", oldDisplay)
fmt.Printf(" New: %s\n", truncateID(newRepoID, 8))
return nil
}
func handleInspect() error {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
dbExists := getStore() != nil
if !dbExists {
result := map[string]interface{}{
"registered_migrations": listMigrations(),
"current_state": map[string]interface{}{
"schema_version": "missing",
"issue_count": 0,
"config": map[string]string{},
"missing_config": []string{},
"db_exists": false,
},
"warnings": []string{"Database does not exist - " + diagHint()},
"invariants_to_check": []string{},
}
if jsonOutput {
return outputJSON(result)
}
fmt.Println("\nMigration Inspection")
fmt.Println("====================")
fmt.Println("Database: missing")
fmt.Println("\n⚠ Database does not exist - " + diagHint())
return nil
}
store := getStore()
if store == nil {
return HandleError("no database — run 'bd init' first")
}
ctx := rootCtx
// Get current schema version
schemaVersion, err := store.GetLocalMetadata(ctx, "bd_version")
if err != nil {
schemaVersion = "unknown"
}
// Get issue count
issueCount := 0
if stats, err := store.GetStatistics(ctx); err == nil {
issueCount = stats.TotalIssues
}
// Get config
configMap := make(map[string]string)
prefix, _ := store.GetConfig(ctx, "issue_prefix")
if prefix != "" {
configMap["issue_prefix"] = prefix
}
// Detect missing config
missingConfig := []string{}
if issueCount > 0 && prefix == "" {
missingConfig = append(missingConfig, "issue_prefix")
}
// Get registered migrations
registeredMigrations := listMigrations()
// Generate warnings
warnings := []string{}
if issueCount > 0 && prefix == "" {
detectedPrefix := ""
if issues, err := store.SearchIssues(ctx, "", types.IssueFilter{}); err == nil && len(issues) > 0 {
detectedPrefix = utils.ExtractIssuePrefix(issues[0].ID)
}
warnings = append(warnings, fmt.Sprintf("issue_prefix config not set - may break commands after migration (detected: %s)", detectedPrefix))
}
if schemaVersion != Version {
warnings = append(warnings, fmt.Sprintf("schema version mismatch (current: %s, expected: %s)", schemaVersion, Version))
}
// Output result
result := map[string]interface{}{
"registered_migrations": registeredMigrations,
"current_state": map[string]interface{}{
"schema_version": schemaVersion,
"issue_count": issueCount,
"config": configMap,
"missing_config": missingConfig,
"db_exists": true,
},
"warnings": warnings,
"invariants_to_check": []string{},
}
if jsonOutput {
return outputJSON(result)
}
fmt.Println("\nMigration Inspection")
fmt.Println("====================")
fmt.Printf("Schema Version: %s\n", schemaVersion)
fmt.Printf("Issue Count: %d\n", issueCount)
fmt.Printf("Registered Migrations: %d\n", len(registeredMigrations))
if len(warnings) > 0 {
fmt.Println("\nWarnings:")
for _, w := range warnings {
fmt.Printf(" ⚠ %s\n", w)
}
}
if len(missingConfig) > 0 {
fmt.Println("\nMissing Config:")
for _, k := range missingConfig {
fmt.Printf(" - %s\n", k)
}
}
fmt.Println()
return nil
}
func handleSchemaMigrate() error {
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
store := getStore()
if store == nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "no_database",
"message": "No database found. Run 'bd init' to create a new database.",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint("no database", "Run 'bd init' to create a new database")
}
migrator, ok := storage.UnwrapStore(store).(storage.SchemaMigrator)
if !ok {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "unsupported_backend",
"message": "current storage backend does not support schema migration",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("current storage backend does not support schema migration")
}
applied, err := migrator.ApplySchemaMigrations(rootCtx)
if err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "schema_migration_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
var dirtyErr *schema.DirtyTablesError
if errors.As(err, &dirtyErr) {
// The dirty guard's own remedy is `bd dolt commit`, which on a
// shared server opens writably, hits the migrate gate, and is told
// to run this command — the two messages point at each other and
// the operator loops (gastownhall/beads#5920 review). Name the
// sequence that actually terminates.
return HandleErrorWithHint(
fmt.Sprintf("schema migration failed: %v", err),
"in server mode `bd dolt commit` is itself gated, so commit the working set on the server first "+
"(`CALL DOLT_COMMIT('-Am', 'pre-migration working set')` over the sql-server, or "+
schema.AllowRemoteMigrateEnv+"=1 bd dolt commit), then re-run this command")
}
return HandleError("schema migration failed: %v", err)
}
latest := schema.LatestVersion()
status := "current"
if applied > 0 {
status = "applied"
commandDidWrite.Store(true)
// Stamp the version markers the refused version-bump reconciliation
// could not (gastownhall/beads#5920 review). autoMigrateOnVersionBump
// is the only automatic writer of bd_version, it was refused by the
// gate this command just satisfied, and its one-shot .local_version
// signal is already consumed — so without this, `bd doctor` and the
// git-hook health check keep reporting a version mismatch after the
// operator has done everything the refusal told them to.
stampWorkspaceVersionAfterMigrate(store)
}
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": status,
"applied": applied,
"latest_version": latest,
})
}
if applied == 0 {
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("✓ Schema already at v%d", latest)))
return nil
}
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("✓ Applied %d schema migration(s); schema now at v%d", applied, latest)))
return nil
}
// stampWorkspaceVersionAfterMigrate records this binary's version through the
// store's own reconciler, exactly as autoMigrateOnVersionBump would have.
//
// Best-effort by design, and deliberately not fatal: the migration itself has
// already succeeded and been reported, so a marker write that fails must not
// turn a successful migration into a failed command. A stale marker is a
// cosmetic doctor warning; a false "schema migration failed" is not.
func stampWorkspaceVersionAfterMigrate(store storage.DoltStorage) {
reconciler, err := store.VersionReconciler()
if err != nil {
debug.Logf("migrate schema: version markers unavailable: %v", err)
return
}
if _, err := reconciler.ReconcileVersion(rootCtx, issueops.VersionReconcileRequest{CLIVersion: Version}); err != nil {
debug.Logf("migrate schema: failed to record workspace version: %v", err)
}
}
// reportProxiedSchemaMigrate is `bd migrate schema`'s proxied-server arm. The
// provider open already reconciled the schema under this verb's consent, so
// there is nothing left to do but say so — and say it in the same shape the
// direct path uses, since a caller parsing --json should not have to branch on
// the workspace's storage mode.
//
// The open reports its own failures: a gate refusal or a failed migration
// aborts the command in root pre-run and never reaches RunE, so arriving here
// means the schema is reconciled. The applied count is not observable from
// here (it belongs to an open that has already returned), hence the "current"
// status rather than a count.
//
// No version stamping here, unlike the direct path: reconcileVersionProxiedServer
// already runs in the root pre-run after a successful provider open, so the
// marker the gate refusal held back is written as soon as the open succeeds.
func reportProxiedSchemaMigrate() error {
latest := schema.LatestVersion()
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": "current",
"latest_version": latest,
"mode": "proxied-server",
"note": "schema reconciled during provider open",
})
}
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf(
"✓ Schema reconciled during provider open (proxied-server mode); schema now at v%d", latest)))
return nil
}
func handleToSeparateBranch(branch string, dryRun bool) error {
b := strings.TrimSpace(branch)
if b == "" || strings.ContainsAny(b, " \t\n") {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "invalid_branch",
"message": "Branch name cannot be empty or contain whitespace",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint(fmt.Sprintf("invalid branch name '%s'", branch), "branch name cannot be empty or contain whitespace")
}
beadsDir := beads.FindBeadsDir()
if beadsDir == "" {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "no_beads_directory",
"message": activeWorkspaceNotFoundMessage() + " " + diagHint() + ".",
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint())
}
store := getStore()
if store == nil {
return HandleError("no database — run 'bd init' first")
}
ctx := rootCtx
current, _ := store.GetConfig(ctx, "sync.branch")
if dryRun {
if jsonOutput {
return outputJSON(map[string]interface{}{
"dry_run": true,
"previous": current,
"branch": b,
"changed": current != b,
})
}
fmt.Println("Dry run mode - no changes will be made")
if current == b {
fmt.Printf("sync.branch already set to '%s'\n", b)
} else {
fmt.Printf("Would set sync.branch: '%s' → '%s'\n", current, b)
}
return nil
}
if current == b {
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": "noop",
"branch": b,
"message": "sync.branch already set to this value",
})
}
fmt.Printf("%s\n", ui.RenderPass(fmt.Sprintf("✓ sync.branch already set to '%s'", b)))
fmt.Println("No changes needed")
return nil
}
if err := store.SetConfig(ctx, "sync.branch", b); err != nil {
if jsonOutput {
if jerr := outputJSON(map[string]interface{}{
"error": "config_update_failed",
"message": err.Error(),
}); jerr != nil {
return jerr
}
return SilentExit()
}
return HandleError("failed to set sync.branch: %v", err)
}
commandDidWrite.Store(true)
if jsonOutput {
return outputJSON(map[string]interface{}{
"status": "success",
"previous": current,
"branch": b,
"message": "Enabled separate branch workflow",
})
}
fmt.Printf("%s\n\n", ui.RenderPass("✓ Enabled separate branch workflow"))
fmt.Printf("Set sync.branch to '%s'\n\n", b)
fmt.Println("Next steps:")
fmt.Println(" 1. No restart required. sync.branch is active immediately.")
fmt.Printf(" bd dolt push\n\n")
fmt.Println(" 2. Your existing data is preserved - no changes to git history")
fmt.Println(" 3. Future issue updates are stored in Dolt directly")
return nil
}
// listMigrations returns registered Dolt schema migrations. The compat runner
// was retired once all historical migrations had SQL equivalents; this is
// kept as a stable hook for `bd migrate --inspect` output.
func listMigrations() []string {
return nil
}
// migrateSyncCmd is the "bd migrate sync <branch>" subcommand that
// configures the separate-branch workflow for multi-clone setups.
// Previously this was documented but never wired as an actual subcommand,
// so bd doctor's recommendation to run "bd migrate sync beads-sync" would fail.
var migrateSyncCmd = &cobra.Command{
Use: "sync <branch>",
Short: "Set up sync.branch workflow for multi-clone setups",
Long: `Configure separate branch workflow for multi-clone setups.
This sets the sync.branch config value so that issue data is committed
to a dedicated branch, keeping your main branch clean.
Example:
bd migrate sync beads-sync`,
Args: cobra.ExactArgs(1),
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("migrate sync is not supported in proxied-server mode")
}
evt := metrics.NewCommandEvent("migrate-sync")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
dryRun, _ := cmd.Flags().GetBool("dry-run")
if !dryRun {
CheckReadonly("migrate sync")
}
return handleToSeparateBranch(args[0], dryRun)
},
}
var migrateSchemaCmd = &cobra.Command{
Use: "schema",
Short: "Apply pending schema migrations (idempotent)",
Long: `Apply pending schema migrations idempotently.
bd does not apply pending schema migrations to an existing database without
the operator's consent, and running this command is that consent
(BD_ALLOW_MIGRATE=1 is the scripted form). On a remote-backed database the
remote-migrate gate still applies: --force confirms you are the single
designated migrator. Migrating is one-way: bd releases built for an older
schema refuse the migrated database.
On an up-to-date database this is a no-op, so it is safe to run in CI,
release gates, and recovery scenarios.
Example:
bd migrate schema
bd migrate schema --json`,
Args: cobra.NoArgs,
SilenceUsage: true,
SilenceErrors: true,
RunE: func(cmd *cobra.Command, _ []string) error {
if usesProxiedServer() {
// Proxied mode has no store-level SchemaMigrator to call: the
// provider open IS the migration, and by the time RunE runs it has
// already happened — with this verb's consent, which the root
// pre-run set before the open (schema.SetSharedMigrateConsent).
// So report, rather than refuse a verb that just did its job.
return reportProxiedSchemaMigrate()
}
CheckReadonly("migrate schema")
evt := metrics.NewCommandEvent("migrate-schema")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
return handleSchemaMigrate()
},
}
func init() {
migrateCmd.Flags().Bool("yes", false, "Auto-confirm prompts")
migrateCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateCmd.Flags().Bool("update-repo-id", false, "Update repository ID (use after changing git remote)")
migrateCmd.Flags().Bool("inspect", false, "Show migration plan and database state for AI agent analysis")
// --force bypasses the remote-migrate gate (#4259) as the single designated
// migrator. No -f shorthand: deliberate typing for a fork-risk bypass.
migrateCmd.Flags().Bool("force", false, "Bypass the remote-migrate gate as the single designated migrator (equivalent to BD_ALLOW_REMOTE_MIGRATE=1)")
migrateSyncCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateCmd.AddCommand(migrateSyncCmd)
migrateHooksCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateHooksCmd.Flags().Bool("apply", false, "Apply planned hook migration changes")
migrateHooksCmd.Flags().Bool("yes", false, "Skip confirmation prompt for --apply")
migrateCmd.AddCommand(migrateHooksCmd)
// --force on migrate schema mirrors the parent command's flag; both trip the
// same isForcedMigrate check in main.go's PersistentPreRunE.
migrateSchemaCmd.Flags().Bool("force", false, "Bypass the remote-migrate gate as the single designated migrator (equivalent to BD_ALLOW_REMOTE_MIGRATE=1)")
migrateCmd.AddCommand(migrateSchemaCmd)
migrateToProxiedServerCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateToProxiedServerCmd.Flags().Duration("idle-timeout", 0, "Proxy idle timeout; omit for the 30s default, 0 for indefinite uptime")
migrateCmd.AddCommand(migrateToProxiedServerCmd)
migrateSharedToProxiedServerCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateSharedToProxiedServerCmd.Flags().Duration("idle-timeout", 0, "Proxy idle timeout; omit for the 30s default, 0 for indefinite uptime")
migrateCmd.AddCommand(migrateSharedToProxiedServerCmd)
migrateToServerCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateCmd.AddCommand(migrateToServerCmd)
migrateToSharedServerCmd.Flags().Bool("dry-run", false, "Show what would be done without making changes")
migrateCmd.AddCommand(migrateToSharedServerCmd)
rootCmd.AddCommand(migrateCmd)
}