* fix(cli): stop eleven subcommands shadowing the root --json flag
--json is a persistent flag on rootCmd bound to jsonOutput. Ten
subcommands (restore, admin compact, repo add/remove/list/sync,
migrate, migrate sync/hooks/schema) also registered a local --json bound
to the same variable. pflag's AddFlagSet keeps the local flag and drops
the inherited one, so rootCmd.PersistentFlags().Changed("json") stayed
false for those commands; PersistentPreRunE and
refreshBoundCommandConfig then treated the flag as unset and reset
jsonOutput from config. `bd restore <id> --json` and friends printed text
unless config said json: true. restore_embedded_test.go recorded the
symptom as a "known issue" and skipped its JSON assertion.
bd preflight registered an unbound local Bool("json") instead; it read
its own flag and was not affected by the reset, but it shadowed the root
flag the same way and ignored a configured json default. It now inherits
the root flag like status, update and the proxied close/reopen routes.
Remove the eleven local registrations. Add
TestNoSubcommandShadowsRootJSONFlag, which walks the command tree and
fails on any command that registers its own --json (local or
persistent). Restore the restore_json assertion (parse the output, check
ID and description). Flip the compact and migrate schema registration
tests to assert the flag is inherited, matching stale_test.go.
Visible change: --json moves from each command's Flags section to Global
Flags in --help, with the root description. docs/cli-reference is pinned
to the release tag and regenerates at release time.
* fix(cli): make the --json shadow guard side-effect free
TestNoSubcommandShadowsRootJSONFlag walked every command through
LocalNonPersistentFlags(), and the --json assertions in compact_test.go and
migrate_test.go used InheritedFlags(). Both call cobra's
mergePersistentFlags(), which copies every root persistent flag into the
command's Flags() for the rest of the test process. TestServeFlags pins the
exact flag set of `bd serve`, so `go test ./cmd/bd` failed whenever it ran
after the guard; CI only stayed green because the two tests land in
different name-hash shards.
Compare the command's Flags().Lookup("json") against the root flag pointer
instead. A local registration is a different *pflag.Flag; an inherited one
is the same pointer, and a command that has not merged yet returns nil.
Verified: the four tests pass together, and re-adding a local --json to
`bd restore` still fails the guard.
bd preflight also drops its `jsonOutput, _ := cmd.Flags().GetBool("json")`
shadow of the package-level variable. The root flag is bound to that
variable and PersistentPreRun already resolves the flag/config precedence,
so the local copy was redundant and swallowed the lookup error.
* review: re-key the preflight --json test to the root flag
Base #6293 added TestPreflightJSONFlagBindsGlobal, which opens by requiring
preflightCmd to own a local --json. This PR's guard forbids exactly that, so
the two tests were mutually exclusive and the adopted head was red. The base
test arrived with a base advance after this PR was written, so nothing in the
contributed work is wrong.
Adapt the test rather than restore the local flag: every property it pins
survives re-keyed to the root persistent flag, which is BoolVar'd to the same
package global. The opening assertion becomes the shadow-aware compare this PR
already introduced in compact_test.go, the Changed==true branch is driven
through rootCmd.PersistentFlags().Set (flag.Value.Set never sets Changed), and
the config half is unchanged. Renamed to TestPreflightJSONInheritsRootFlag so
the name stops asserting the very thing the PR removes.
Also correct three CHANGELOG clauses that were true against the contributor's
older base and false at this one: #6293's commandJSONFlagChanged already
consults a subcommand's own Changed bit before the root's, preflight's local
flag was bound rather than unbound, and #6293 already announced that preflight
honors the json config default. The bullet now claims what this PR delivers
here -- deleting the shadowing registrations instead of compensating for them.
Compile the new guard into the Bazel test target. cmd/bd/json_flag_shadow_test.go
was absent from the explicit srcs of go_test(name = "bd_test"), so the invariant
this PR exists to create never ran in the BAZEL* lanes -- and those lanes are
required for merge: CI_GATE_REQUIRED on origin/main lists BAZEL, BAZEL_TEST,
BAZEL_PURE, BAZEL_EMBEDDED, BAZEL_DOLTSERVER, BAZEL_PROXIED and
BAZEL_SERVER_STORAGE. Added in sorted position between jira_test.go and
kv_embedded_test.go; the file is untagged package main, so bd_test is the right
target under the root gazelle:build_tags gms_pure_go. make bazel-sync-check
cannot catch this -- it maintains only the go_srcs filegroup globs, not go_test
srcs.
Finally, reconcile the neighbouring #6293 bullet, which this PR invalidates. It
still described preflight's --json as "bound to the same global every sibling
command binds" and closed on "because an unbound flag reports as unset" -- both
describing the local registration deleted here, fourteen lines from the bullet
announcing the deletion and shipping in the same [Unreleased] section. Trimmed
to the user-visible outcome #6293 still owns; the new bullet carries the
registration story.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
952 lines
31 KiB
Go
952 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.
|
|
|
|
Schema migrations also run automatically on store open, so this subcommand
|
|
is typically a no-op. It exists to make migration explicit and observable
|
|
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)
|
|
}
|