beads/cmd/bd/restore.go
Bùi Phan Viết Cường 39aa86fec5
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>
2026-10-01 00:53:08 -07:00

247 lines
8.3 KiB
Go

package main
import (
"errors"
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
var restoreApply bool
var restoreCmd = &cobra.Command{
Use: "restore <issue-id>",
GroupID: "sync",
SilenceUsage: true,
SilenceErrors: true,
Short: "Restore the pre-compaction content of a compacted issue",
Long: `Restore the pre-compaction content of a compacted issue.
When an issue is compacted, its description/design/notes/acceptance criteria
are summarized and the originals are archived to a compaction snapshot. This
command recovers that original content.
By default it is read-only: it displays the archived content without modifying
the database. Pass --apply to write the original content back into the issue
and step its compaction level back down.
If no archived snapshot exists (e.g. the issue was compacted by an older bd
before snapshot archiving), restore falls back to a best-effort reconstruction
from Dolt version history, which can only be displayed, not applied.`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if usesProxiedServer() {
return HandleErrorRespectJSON("restore is not supported in proxied-server mode")
}
issueID := args[0]
ctx := rootCtx
// Get the issue
issue, err := store.GetIssue(ctx, issueID)
if err != nil {
if errors.Is(err, storage.ErrNotFound) {
fmt.Fprintf(os.Stderr, "Error: issue '%s' not found\n", issueID)
} else {
fmt.Fprintf(os.Stderr, "Error: issue '%s' not found: %v\n", issueID, err)
}
return SilentExit()
}
// Check if issue is compacted
if issue.CompactionLevel == 0 {
fmt.Fprintf(os.Stderr, "Error: issue %s is not compacted\n", issueID)
fmt.Fprintf(os.Stderr, "Hint: only compacted issues need restoration\n")
return SilentExit()
}
// Prefer the archived snapshot: it is the authoritative pre-compaction
// copy and the only source that can be safely written back.
snap, err := store.GetCompactionSnapshot(ctx, issueID)
if err != nil {
return HandleError("failed to read compaction snapshot: %v", err)
}
if restoreApply {
if snap == nil {
fmt.Fprintf(os.Stderr, "Error: no archived snapshot for %s; cannot safely restore content\n", issueID)
fmt.Fprintf(os.Stderr, "Hint: this issue was compacted before snapshot archiving existed.\n")
fmt.Fprintf(os.Stderr, " Run 'bd restore %s' (without --apply) to view the best-effort\n", issueID)
fmt.Fprintf(os.Stderr, " version reconstructed from Dolt history.\n")
return SilentExit()
}
applied, err := store.RestoreFromSnapshot(ctx, issueID)
if err != nil {
return HandleError("failed to restore issue: %v", err)
}
if applied == nil {
return HandleError("no archived snapshot for %s", issueID)
}
restored, err := store.GetIssue(ctx, issueID)
if err != nil {
return HandleError("restored, but failed to re-read issue: %v", err)
}
if jsonOutput {
if err := outputJSON(restored); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
return nil
}
fmt.Printf("%s Restored %s from archived snapshot (compaction level %d → %d)\n",
ui.RenderPass("✓"), issueID, issue.CompactionLevel, restored.CompactionLevel)
return nil
}
// Read-only display path. Prefer the archived snapshot; fall back to the
// Dolt-history heuristic when no snapshot exists.
if snap != nil {
view := snapshotView(issue, snap)
if jsonOutput {
if err := outputJSON(view); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
} else {
displayRestoredIssue(view, "archived snapshot")
fmt.Printf("%s\n", ui.RenderMuted("Run 'bd restore "+issueID+" --apply' to write this content back."))
}
return nil
}
// Query Dolt history for the pre-compaction version
history, err := store.History(ctx, issueID)
if err != nil {
return HandleError("failed to query history: %v", err)
}
if len(history) == 0 {
fmt.Fprintf(os.Stderr, "Error: no history found for issue %s\n", issueID)
fmt.Fprintf(os.Stderr, "Hint: issue may have been compacted before Dolt history was available\n")
return SilentExit()
}
// Find the pre-compaction version: the history entry with the most content.
// History is ordered by commit_date DESC, so we scan all entries.
var best *storage.HistoryEntry
bestSize := 0
for _, entry := range history {
size := issueContentSize(entry.Issue)
if size > bestSize {
bestSize = size
best = entry
}
}
if best == nil || bestSize <= issueContentSize(issue) {
fmt.Fprintf(os.Stderr, "Error: no pre-compaction version found in Dolt history\n")
fmt.Fprintf(os.Stderr, "Hint: issue may have been compacted before Dolt history was available\n")
return SilentExit()
}
if jsonOutput {
if err := outputJSON(best.Issue); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
} else {
hashDisplay := best.CommitHash
if len(hashDisplay) > 8 {
hashDisplay = hashDisplay[:8]
}
displayRestoredIssue(best.Issue, "Dolt commit "+hashDisplay)
}
return nil
},
}
// snapshotView returns a copy of the current issue with its text content
// overlaid by the archived pre-compaction snapshot, for read-only display.
func snapshotView(issue *types.Issue, snap *types.IssueSnapshot) *types.Issue {
view := *issue
if snap.Title != "" {
view.Title = snap.Title
}
view.Description = snap.Description
view.Design = snap.Design
view.Notes = snap.Notes
view.AcceptanceCriteria = snap.AcceptanceCriteria
return &view
}
// issueContentSize returns the total text content size of an issue.
func issueContentSize(issue *types.Issue) int {
return len(issue.Description) + len(issue.Design) + len(issue.AcceptanceCriteria) + len(issue.Notes)
}
func init() {
restoreCmd.Flags().BoolVar(&restoreApply, "apply", false, "Write the restored content back into the issue (default: display only)")
rootCmd.AddCommand(restoreCmd)
}
// displayRestoredIssue displays the restored issue in a readable format.
// provenance describes where the content came from (e.g. "archived snapshot"
// or "Dolt commit abc12345").
func displayRestoredIssue(issue *types.Issue, provenance string) {
fmt.Printf("\n%s %s (restored from %s)\n", ui.RenderAccent("📜"), ui.RenderBold(issue.ID), ui.RenderWarn(provenance))
fmt.Printf("%s\n\n", ui.RenderBold(issue.Title))
if issue.Description != "" {
fmt.Printf("%s\n%s\n\n", ui.RenderBold("Description:"), issue.Description)
}
if issue.Design != "" {
fmt.Printf("%s\n%s\n\n", ui.RenderBold("Design:"), issue.Design)
}
if issue.AcceptanceCriteria != "" {
fmt.Printf("%s\n%s\n\n", ui.RenderBold("Acceptance Criteria:"), issue.AcceptanceCriteria)
}
if issue.Notes != "" {
fmt.Printf("%s\n%s\n\n", ui.RenderBold("Notes:"), issue.Notes)
}
fmt.Printf("%s %s | %s %d | %s %s\n",
ui.RenderBold("Status:"), issue.Status,
ui.RenderBold("Priority:"), issue.Priority,
ui.RenderBold("Type:"), issue.IssueType,
)
if issue.Assignee != "" {
fmt.Printf("%s %s\n", ui.RenderBold("Assignee:"), issue.Assignee)
}
if len(issue.Labels) > 0 {
fmt.Printf("%s %s\n", ui.RenderBold("Labels:"), strings.Join(issue.Labels, ", "))
}
fmt.Printf("\n%s %s\n", ui.RenderBold("Created:"), issue.CreatedAt.Format("2006-01-02 15:04:05"))
fmt.Printf("%s %s\n", ui.RenderBold("Updated:"), issue.UpdatedAt.Format("2006-01-02 15:04:05"))
if issue.ClosedAt != nil {
fmt.Printf("%s %s\n", ui.RenderBold("Closed:"), issue.ClosedAt.Format("2006-01-02 15:04:05"))
}
if len(issue.Dependencies) > 0 {
fmt.Printf("\n%s\n", ui.RenderBold("Dependencies:"))
for _, dep := range issue.Dependencies {
fmt.Printf(" %s %s (%s)\n", ui.RenderPass("→"), dep.DependsOnID, dep.Type)
}
}
if issue.CompactionLevel > 0 {
fmt.Printf("\n%s Level %d", ui.RenderWarn("⚠️ This issue was compacted:"), issue.CompactionLevel)
if issue.CompactedAt != nil {
fmt.Printf(" at %s", issue.CompactedAt.Format("2006-01-02 15:04:05"))
}
if issue.OriginalSize > 0 {
currentSize := len(issue.Description) + len(issue.Design) + len(issue.AcceptanceCriteria) + len(issue.Notes)
reduction := 100 * (1 - float64(currentSize)/float64(issue.OriginalSize))
fmt.Printf(" (%.1f%% size reduction)", reduction)
}
fmt.Println()
}
fmt.Println()
}