diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e64aadd8..8c41de849 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,6 +26,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 (already "bug"); pass a single value`. Single-flag and comma-form spellings behave exactly as before. +- **`bd restore`, `bd admin compact`, `bd repo `, + `bd migrate [sync|hooks|schema]` and `bd preflight` no longer register a + local `--json` that shadows the root persistent flag.** pflag keeps a + command's own flag and drops the inherited one, so + `rootCmd.PersistentFlags().Changed("json")` stays false for that command; + [#6293](https://github.com/gastownhall/beads/pull/6293) compensated for that + per command by making the pre-run consult the subcommand's own `Changed` bit + before the root's. Deleting the eleven local registrations removes the + shadowing itself rather than working around it: `--json` moves to the Global + Flags section of those commands' `--help`, and a guard test now fails the + build if a command shadows the root flag again — closing the class before an + *unbound* local copy can reappear and invert the output mode it was meant to + select. + - **`bd init --force` can no longer silently recreate a missing server-side database as empty** (be-5up5). `--force` is an alias for `--reinit-local`, which skips the existing-data guard entirely, and the reinit path's own typed @@ -880,12 +894,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 stdout is unlimited, agent mode on a terminal gets 20, and a terminal gets 50. - **`bd preflight` honors the `json` config default** - ([#6293](https://github.com/gastownhall/beads/pull/6293)). Its `--json` flag - is bound to the same global every sibling command binds, so `json: true` in - the config file now selects JSON output for `bd preflight` as it already did - elsewhere. Previously only the explicit flag was honored — and, because an - unbound flag reports as unset, `bd preflight --json` did not reach every - JSON-aware renderer. + ([#6293](https://github.com/gastownhall/beads/pull/6293)). `json: true` in the + config file selects JSON output for `bd preflight`, as it already did + elsewhere; previously only the explicit flag was honored. - **`bd gate check` resolves bead gates whose target lives in a prefix-routed rig** ([#5859](https://github.com/gastownhall/beads/pull/5859)). After a local miss, the evaluator follows the target bead ID through `routes.jsonl` and diff --git a/cmd/bd/BUILD.bazel b/cmd/bd/BUILD.bazel index e48c4113f..76f738ea5 100644 --- a/cmd/bd/BUILD.bazel +++ b/cmd/bd/BUILD.bazel @@ -833,6 +833,7 @@ go_test( "init_worktree_test.go", "jira_max_rows_gate_test.go", "jira_test.go", + "json_flag_shadow_test.go", "kv_embedded_test.go", "kv_proxied_integration_test.go", "kv_test.go", diff --git a/cmd/bd/compact.go b/cmd/bd/compact.go index d81026537..6d655d93b 100644 --- a/cmd/bd/compact.go +++ b/cmd/bd/compact.go @@ -986,7 +986,6 @@ func init() { compactCmd.Flags().IntVar(&compactBatch, "batch-size", 10, "Issues per batch") compactCmd.Flags().IntVar(&compactWorkers, "workers", 5, "Parallel workers") compactCmd.Flags().BoolVar(&compactStats, "stats", false, "Show compaction statistics") - compactCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output JSON format") // New mode flags compactCmd.Flags().BoolVar(&compactAnalyze, "analyze", false, "Analyze mode: export candidates for agent review") diff --git a/cmd/bd/compact_test.go b/cmd/bd/compact_test.go index 9ed745687..b760e42cd 100644 --- a/cmd/bd/compact_test.go +++ b/cmd/bd/compact_test.go @@ -345,9 +345,9 @@ func TestCompactInitCommand(t *testing.T) { t.Error("compactCmd should have Long description") } - // Verify --json flag exists - jsonFlag := compactCmd.Flags().Lookup("json") - if jsonFlag == nil { - t.Error("compact command should have --json flag") + // --json is inherited from rootCmd as a persistent flag; a local copy + // would shadow it (see TestNoSubcommandShadowsRootJSONFlag). + if f := compactCmd.Flags().Lookup("json"); f != nil && f != rootCmd.PersistentFlags().Lookup("json") { + t.Error("compact command must not register a local --json; it inherits the root flag") } } diff --git a/cmd/bd/json_flag_shadow_test.go b/cmd/bd/json_flag_shadow_test.go new file mode 100644 index 000000000..c7f2a5bca --- /dev/null +++ b/cmd/bd/json_flag_shadow_test.go @@ -0,0 +1,45 @@ +package main + +import ( + "testing" + + "github.com/spf13/cobra" +) + +// TestNoSubcommandShadowsRootJSONFlag guards the root --json contract. +// +// --json is a persistent flag on rootCmd. When a subcommand registers its own +// --json (local or persistent), pflag keeps that one and drops the inherited +// one, so rootCmd.PersistentFlags().Changed("json") stays false for that +// command. The PersistentPreRun then treats the flag as unset and overwrites +// jsonOutput with the configured default, and `bd --json` prints text +// unless the config also says json. Every command must inherit the root flag +// instead. +// +// The check reads Flags() and PersistentFlags() only. LocalNonPersistentFlags() +// and InheritedFlags() call mergePersistentFlags, which copies every root +// persistent flag into the command's Flags() for the rest of the process and +// breaks tests that pin a command's exact flag set (TestServeFlags). +func TestNoSubcommandShadowsRootJSONFlag(t *testing.T) { + rootJSON := rootCmd.PersistentFlags().Lookup("json") + if rootJSON == nil { + t.Fatal("root command must register persistent --json") + } + + var offenders []string + var walk func(cmd *cobra.Command) + walk = func(cmd *cobra.Command) { + for _, sub := range cmd.Commands() { + local := sub.Flags().Lookup("json") + if (local != nil && local != rootJSON) || sub.PersistentFlags().Lookup("json") != nil { + offenders = append(offenders, sub.CommandPath()) + } + walk(sub) + } + } + walk(rootCmd) + + for _, path := range offenders { + t.Errorf("%q registers a local --json flag that shadows the root persistent flag", path) + } +} diff --git a/cmd/bd/migrate.go b/cmd/bd/migrate.go index d611852f7..db9596c7d 100644 --- a/cmd/bd/migrate.go +++ b/cmd/bd/migrate.go @@ -917,22 +917,18 @@ func init() { 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") - migrateCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output migration statistics in JSON format") // --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") - migrateSyncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format") 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") - migrateHooksCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format") migrateCmd.AddCommand(migrateHooksCmd) - migrateSchemaCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format") // --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)") diff --git a/cmd/bd/migrate_test.go b/cmd/bd/migrate_test.go index f7577f0c3..80c62f781 100644 --- a/cmd/bd/migrate_test.go +++ b/cmd/bd/migrate_test.go @@ -17,18 +17,19 @@ import ( // TestFormatDBList removed: formatDBList and dbInfo types were removed. func TestMigrateSchemaFlagBoundaries(t *testing.T) { - // Registration only: strict subprocess tests use the unique root persistent - // --format=json alias because duplicate local --json registration can shadow - // whether PersistentPreRunE sees the root flag as explicitly set. + // Registration only. --json must come from the root persistent flag: a + // local duplicate shadows it, so PersistentPreRunE never sees the root + // flag as explicitly set and resets jsonOutput from config. for _, name := range []string{"inspect", "dry-run"} { if flag := migrateSchemaCmd.Flags().Lookup(name); flag != nil { t.Errorf("migrate schema unexpectedly registers local --%s", name) } } - for _, name := range []string{"json", "force"} { - if flag := migrateSchemaCmd.Flags().Lookup(name); flag == nil { - t.Errorf("migrate schema must register local --%s", name) - } + if f := migrateSchemaCmd.Flags().Lookup("json"); f != nil && f != rootCmd.PersistentFlags().Lookup("json") { + t.Error("migrate schema must not register a local --json; it inherits the root flag") + } + if flag := migrateSchemaCmd.Flags().Lookup("force"); flag == nil { + t.Error("migrate schema must register local --force") } if flag := rootCmd.PersistentFlags().Lookup("json"); flag == nil { t.Error("root command must register persistent --json") diff --git a/cmd/bd/preflight.go b/cmd/bd/preflight.go index e7b59a39a..719404ad9 100644 --- a/cmd/bd/preflight.go +++ b/cmd/bd/preflight.go @@ -79,13 +79,6 @@ const lintCancellationGrace = 10 * time.Second func init() { preflightCmd.Flags().Bool("check", false, "Run checks automatically") preflightCmd.Flags().Bool("fix", false, "Auto-fix issues where possible (vendorHash, version sync)") - // Bound to the package global like every other command's local --json. - // commandJSONFlagChanged suppresses the config-driven default whenever a - // local --json is set, so a flag that does not write the global would - // leave `bd preflight --json` with jsonOutput=false — inverting JSON mode - // for everything that reads the global, including the front-door error - // renderers. - preflightCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output results as JSON") preflightCmd.Flags().Bool("skip-lint", false, "Skip lint check explicitly") rootCmd.AddCommand(preflightCmd) diff --git a/cmd/bd/preflight_test.go b/cmd/bd/preflight_test.go index 230cf3b41..5be1f4b59 100644 --- a/cmd/bd/preflight_test.go +++ b/cmd/bd/preflight_test.go @@ -544,30 +544,38 @@ func TestIsBeadsRepo(t *testing.T) { } } -// TestPreflightJSONFlagBindsGlobal pins both halves of preflight's --json -// binding, which is one flag serving two masters. Setting it must write the -// package global, or every jsonOutput reader (including the front-door refusal +// TestPreflightJSONInheritsRootFlag pins preflight's --json contract now that +// the command inherits the root persistent flag instead of registering a local +// copy. A local copy would shadow the inherited one and is what +// TestNoSubcommandShadowsRootJSONFlag forbids, so the first check rejects a +// local flag rather than requiring one. +// +// The binding this pins is unchanged, only re-keyed: the root flag is +// BoolVar'd to the same package global (main.go), so setting it must write +// jsonOutput, or every jsonOutput reader (including the front-door refusal // renderers) stays in text mode while the user asked for JSON. Leaving it // unset must report unchanged to commandJSONFlagChanged, which is what lets a -// config-file `json: true` reach preflight the way it reaches its siblings — -// a deliberate behavior change from the unbound shadow this replaced, and the -// reason the CHANGELOG calls it out. +// config-file `json: true` reach preflight the way it reaches its siblings. // // The last two subtests drive that config half rather than only asserting the // negative direction. flag.Value.Set never sets Changed (only FlagSet.Set // does), so the Changed==true branch of commandJSONFlagChanged needs its own -// case, and the behavior the CHANGELOG announces — configured `json: true` -// with no flag flipping jsonOutput — only happens inside -// refreshBoundCommandConfig, so it has to be driven through that function. -func TestPreflightJSONFlagBindsGlobal(t *testing.T) { - flag := preflightCmd.Flags().Lookup("json") - if flag == nil { - t.Fatal("preflight has no --json flag") - } +// case — driven through the root flag, which is the one an inheriting command +// now has — and the configured `json: true` with no flag flipping jsonOutput +// only happens inside refreshBoundCommandConfig, so it has to be driven +// through that function. +func TestPreflightJSONInheritsRootFlag(t *testing.T) { rootJSON := preflightCmd.Root().PersistentFlags().Lookup("json") if rootJSON == nil { t.Fatal("root has no persistent --json flag") } + // --json is inherited from rootCmd as a persistent flag; a local copy + // would shadow it (see TestNoSubcommandShadowsRootJSONFlag). Comparing + // against the root flag rather than requiring nil tolerates a sibling test + // having already merged the root persistent flags into this command's set. + if f := preflightCmd.Flags().Lookup("json"); f != nil && f != rootJSON { + t.Error("preflight must not register a local --json; it inherits the root flag") + } // refreshBoundCommandConfig consults config only when neither --json nor // its hidden --format alias was given, so this test owns that flag's // Changed bit too. @@ -577,15 +585,13 @@ func TestPreflightJSONFlagBindsGlobal(t *testing.T) { } oldGlobal := jsonOutput - oldValue, oldChanged := flag.Value.String(), flag.Changed - oldRootChanged := rootJSON.Changed + oldValue, oldRootChanged := rootJSON.Value.String(), rootJSON.Changed oldFormatChanged := rootFormat.Changed // refreshBoundCommandConfig reapplies every config-backed default, not // just json; restore the rest so this test cannot leak into siblings. oldReadonly, oldActor, oldAutoCommit := readonlyMode, actor, doltAutoCommit t.Cleanup(func() { - _ = flag.Value.Set(oldValue) - flag.Changed = oldChanged + _ = rootJSON.Value.Set(oldValue) rootJSON.Changed = oldRootChanged rootFormat.Changed = oldFormatChanged jsonOutput = oldGlobal @@ -593,9 +599,9 @@ func TestPreflightJSONFlagBindsGlobal(t *testing.T) { config.ResetForTesting() }) - t.Run("flag writes the package global", func(t *testing.T) { + t.Run("inherited flag writes the package global", func(t *testing.T) { jsonOutput = false - if err := flag.Value.Set("true"); err != nil { + if err := rootJSON.Value.Set("true"); err != nil { t.Fatal(err) } if !jsonOutput { @@ -604,7 +610,6 @@ func TestPreflightJSONFlagBindsGlobal(t *testing.T) { }) t.Run("neither flag set reports unchanged", func(t *testing.T) { - flag.Changed = false rootJSON.Changed = false if commandJSONFlagChanged(preflightCmd) { t.Fatal("preflight reported an explicit --json with neither flag set; the config-file json default would never apply") @@ -612,9 +617,8 @@ func TestPreflightJSONFlagBindsGlobal(t *testing.T) { }) t.Run("explicit --json reports changed", func(t *testing.T) { - flag.Changed = false rootJSON.Changed = false - if err := preflightCmd.Flags().Set("json", "true"); err != nil { + if err := preflightCmd.Root().PersistentFlags().Set("json", "true"); err != nil { t.Fatal(err) } if !commandJSONFlagChanged(preflightCmd) { @@ -629,7 +633,6 @@ func TestPreflightJSONFlagBindsGlobal(t *testing.T) { } config.Set("json", true) - flag.Changed = false rootJSON.Changed = false rootFormat.Changed = false jsonOutput = false diff --git a/cmd/bd/repo.go b/cmd/bd/repo.go index 2b8a1adb8..aadcc0564 100644 --- a/cmd/bd/repo.go +++ b/cmd/bd/repo.go @@ -476,10 +476,6 @@ func init() { repoCmd.AddCommand(repoListCmd) repoCmd.AddCommand(repoSyncCmd) - repoAddCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output JSON") - repoRemoveCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output JSON") - repoListCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output JSON") - repoSyncCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output JSON") repoSyncCmd.Flags().Bool("verbose", false, "Show detailed sync progress") rootCmd.AddCommand(repoCmd) diff --git a/cmd/bd/restore.go b/cmd/bd/restore.go index 6a4121817..2d0cd523f 100644 --- a/cmd/bd/restore.go +++ b/cmd/bd/restore.go @@ -176,7 +176,6 @@ func issueContentSize(issue *types.Issue) int { } func init() { - restoreCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output restore results in JSON format") restoreCmd.Flags().BoolVar(&restoreApply, "apply", false, "Write the restored content back into the issue (default: display only)") rootCmd.AddCommand(restoreCmd) } diff --git a/cmd/bd/restore_embedded_test.go b/cmd/bd/restore_embedded_test.go index 45a709e8d..7d00c2dbc 100644 --- a/cmd/bd/restore_embedded_test.go +++ b/cmd/bd/restore_embedded_test.go @@ -4,6 +4,7 @@ package main import ( "context" + "encoding/json" "fmt" "os" "os/exec" @@ -13,6 +14,7 @@ import ( "time" "github.com/steveyegge/beads/internal/storage/embeddeddolt" + "github.com/steveyegge/beads/internal/types" ) // bdRestore runs "bd restore" with extra args. Returns combined output. @@ -145,12 +147,16 @@ func TestEmbeddedRestore(t *testing.T) { dir, beadsDir, _ := bdInit(t, bd, "--prefix", "rstjs") id := simulateCompaction(t, bd, dir, beadsDir, "rstjs") - // NOTE: bd restore has a known issue where its local --json flag - // conflicts with the root command's --json persistent flag. - // Just verify the command runs successfully. - out := bdRestore(t, bd, dir, id) - if !strings.Contains(out, "long description") { - t.Errorf("expected restored description in output, got: %s", out) + out := bdRestore(t, bd, dir, id, "--json") + var restored types.Issue + if err := json.Unmarshal([]byte(out), &restored); err != nil { + t.Fatalf("bd restore --json must print a JSON issue, got error %v:\n%s", err, out) + } + if restored.ID != id { + t.Errorf("expected restored issue %s, got %q", id, restored.ID) + } + if !strings.Contains(restored.Description, "long description") { + t.Errorf("expected restored description in JSON, got: %q", restored.Description) } }) }