fix(cli): stop eleven subcommands shadowing the root --json flag (#6245)

* 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>
This commit is contained in:
Bùi Phan Viết Cường 2026-10-01 14:53:08 +07:00 • committed by GitHub
commit 39aa86fec5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12 changed files with 114 additions and 64 deletions

View file

@ -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 <add|remove|list|sync>`,
`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

View file

@ -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",

View file

@ -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")

View file

@ -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")
}
}

View file

@ -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 <cmd> --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)
}
}

View file

@ -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)")

View file

@ -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")

View file

@ -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)

View file

@ -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

View file

@ -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)

View file

@ -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)
}

View file

@ -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)
}
})
}