diff --git a/cmd/bd/restore.go b/cmd/bd/restore.go index b6cc67060..dc268bef8 100644 --- a/cmd/bd/restore.go +++ b/cmd/bd/restore.go @@ -12,17 +12,25 @@ import ( "github.com/steveyegge/beads/internal/ui" ) +var restoreApply bool + var restoreCmd = &cobra.Command{ Use: "restore ", GroupID: "sync", - Short: "Restore full history of a compacted issue from Dolt history", - Long: `Restore full history of a compacted issue from Dolt version history. + 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 and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database.`, +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), Run: func(cmd *cobra.Command, args []string) { issueID := args[0] @@ -46,6 +54,58 @@ This is read-only and does not modify the database.`, os.Exit(1) } + // 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 { + fmt.Fprintf(os.Stderr, "Error: failed to read compaction snapshot: %v\n", err) + os.Exit(1) + } + + 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") + os.Exit(1) + } + applied, err := store.RestoreFromSnapshot(ctx, issueID) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: failed to restore issue: %v\n", err) + os.Exit(1) + } + if applied == nil { + fmt.Fprintf(os.Stderr, "Error: no archived snapshot for %s\n", issueID) + os.Exit(1) + } + restored, err := store.GetIssue(ctx, issueID) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: restored, but failed to re-read issue: %v\n", err) + os.Exit(1) + } + if jsonOutput { + outputJSON(restored) + return + } + fmt.Printf("%s Restored %s from archived snapshot (compaction level %d → %d)\n", + ui.RenderPass("✓"), issueID, issue.CompactionLevel, restored.CompactionLevel) + return + } + + // 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 { + outputJSON(view) + } else { + displayRestoredIssue(view, "archived snapshot") + fmt.Printf("%s\n", ui.RenderMuted("Run 'bd restore "+issueID+" --apply' to write this content back.")) + } + return + } + // Query Dolt history for the pre-compaction version history, err := store.History(ctx, issueID) if err != nil { @@ -80,11 +140,29 @@ This is read-only and does not modify the database.`, if jsonOutput { outputJSON(best.Issue) } else { - displayRestoredIssue(best.Issue, best.CommitHash) + hashDisplay := best.CommitHash + if len(hashDisplay) > 8 { + hashDisplay = hashDisplay[:8] + } + displayRestoredIssue(best.Issue, "Dolt commit "+hashDisplay) } }, } +// 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) @@ -92,16 +170,15 @@ 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) } -// displayRestoredIssue displays the restored issue in a readable format -func displayRestoredIssue(issue *types.Issue, commitHash string) { - hashDisplay := commitHash - if len(hashDisplay) > 8 { - hashDisplay = hashDisplay[:8] - } - fmt.Printf("\n%s %s (restored from Dolt commit %s)\n", ui.RenderAccent("📜"), ui.RenderBold(issue.ID), ui.RenderWarn(hashDisplay)) +// 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 != "" { diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md index def234d8e..e55df0c4b 100644 --- a/docs/CLI_REFERENCE.md +++ b/docs/CLI_REFERENCE.md @@ -104,7 +104,7 @@ Reference for bd Latest. Generated from `bd help --all`. - [bd export](#bd-export) — Export issues to JSONL format - [bd federation](#bd-federation) — Manage peer-to-peer federation (requires CGO) - [bd import](#bd-import) — Import issues from a JSONL file or stdin into the database -- [bd restore](#bd-restore) — Restore full history of a compacted issue from Dolt history +- [bd restore](#bd-restore) — Restore the pre-compaction content of a compacted issue - [bd vc](#bd-vc) — Version control operations - [bd vc commit](#bd-vc-commit) — Create a commit with all staged changes - [bd vc merge](#bd-vc-merge) — Merge a branch into the current branch @@ -2476,13 +2476,19 @@ bd import [file|-] [flags] ### bd restore -Restore full history of a compacted issue from Dolt version history. +Restore the pre-compaction content of a compacted issue. -When an issue is compacted, its description and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database. +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. ``` bd restore [flags] @@ -2491,7 +2497,8 @@ bd restore [flags] **Flags:** ``` - --json Output restore results in JSON format + --apply Write the restored content back into the issue (default: display only) + --json Output restore results in JSON format ``` ### bd vc diff --git a/internal/compact/compactor.go b/internal/compact/compactor.go index 5d42f1cc7..e091630fc 100644 --- a/internal/compact/compactor.go +++ b/internal/compact/compactor.go @@ -35,6 +35,7 @@ type Compactor struct { type compactableStore interface { CheckEligibility(ctx context.Context, issueID string, tier int) (bool, string, error) GetIssue(ctx context.Context, issueID string) (*types.Issue, error) + SnapshotIssue(ctx context.Context, issueID string, tier int) error UpdateIssue(ctx context.Context, issueID string, updates map[string]interface{}, actor string) error ApplyCompaction(ctx context.Context, issueID string, tier int, originalSize int, compactedSize int, commitHash string) error AddComment(ctx context.Context, issueID, actor, comment string) error @@ -129,6 +130,13 @@ func (c *Compactor) CompactTier1(ctx context.Context, issueID string) error { return fmt.Errorf("compaction would increase size (%d → %d bytes), keeping original", originalSize, compactedSize) } + // Archive the original content BEFORE the destructive overwrite, so the + // compaction is reversible (bd restore reads this snapshot). If archiving + // fails we abort with the original content intact rather than lose it. + if err := c.store.SnapshotIssue(ctx, issueID, 1); err != nil { + return fmt.Errorf("failed to archive pre-compaction snapshot: %w", err) + } + // Update issue with summarized content updates := map[string]interface{}{ "description": summary, diff --git a/internal/compact/compactor_unit_test.go b/internal/compact/compactor_unit_test.go index 979c21db2..8ba5d3ece 100644 --- a/internal/compact/compactor_unit_test.go +++ b/internal/compact/compactor_unit_test.go @@ -14,6 +14,7 @@ import ( type stubStore struct { checkEligibilityFn func(context.Context, string, int) (bool, string, error) getIssueFn func(context.Context, string) (*types.Issue, error) + snapshotIssueFn func(context.Context, string, int) error updateIssueFn func(context.Context, string, map[string]interface{}, string) error applyCompactionFn func(context.Context, string, int, int, int, string) error addCommentFn func(context.Context, string, string, string) error @@ -33,6 +34,13 @@ func (s *stubStore) GetIssue(ctx context.Context, issueID string) (*types.Issue, return nil, fmt.Errorf("GetIssue not stubbed") } +func (s *stubStore) SnapshotIssue(ctx context.Context, issueID string, tier int) error { + if s.snapshotIssueFn != nil { + return s.snapshotIssueFn(ctx, issueID, tier) + } + return nil +} + func (s *stubStore) UpdateIssue(ctx context.Context, issueID string, updates map[string]interface{}, actor string) error { if s.updateIssueFn != nil { return s.updateIssueFn(ctx, issueID, updates, actor) @@ -141,6 +149,65 @@ func TestCompactTier1_Success(t *testing.T) { } } +// TestCompactTier1_SnapshotBeforeOverwrite is the data-safety guard: the +// pre-compaction snapshot must be taken BEFORE the destructive UpdateIssue, so +// compaction is always reversible. +func TestCompactTier1_SnapshotBeforeOverwrite(t *testing.T) { + cleanup := withGitHash(t, "deadbeef\n") + t.Cleanup(cleanup) + + var order []string + store := &stubStore{ + checkEligibilityFn: func(context.Context, string, int) (bool, string, error) { return true, "", nil }, + getIssueFn: func(context.Context, string) (*types.Issue, error) { return stubIssue(), nil }, + snapshotIssueFn: func(ctx context.Context, id string, tier int) error { + if tier != 1 { + t.Fatalf("expected snapshot tier 1, got %d", tier) + } + order = append(order, "snapshot") + return nil + }, + updateIssueFn: func(context.Context, string, map[string]interface{}, string) error { + order = append(order, "update") + return nil + }, + } + summary := &stubSummarizer{summary: "short"} + c := &Compactor{store: store, summarizer: summary, config: &Config{}} + + if err := c.CompactTier1(context.Background(), "bd-123"); err != nil { + t.Fatalf("CompactTier1 unexpected error: %v", err) + } + if len(order) != 2 || order[0] != "snapshot" || order[1] != "update" { + t.Fatalf("expected snapshot before update, got %v", order) + } +} + +// TestCompactTier1_SnapshotError verifies that a failed archive aborts the +// compaction so the original content is never overwritten without a snapshot. +func TestCompactTier1_SnapshotError(t *testing.T) { + updateCalled := false + store := &stubStore{ + checkEligibilityFn: func(context.Context, string, int) (bool, string, error) { return true, "", nil }, + getIssueFn: func(context.Context, string) (*types.Issue, error) { return stubIssue(), nil }, + snapshotIssueFn: func(context.Context, string, int) error { return errors.New("disk full") }, + updateIssueFn: func(context.Context, string, map[string]interface{}, string) error { + updateCalled = true + return nil + }, + } + summary := &stubSummarizer{summary: "short"} + c := &Compactor{store: store, summarizer: summary, config: &Config{}} + + err := c.CompactTier1(context.Background(), "bd-123") + if err == nil || !strings.Contains(err.Error(), "archive pre-compaction snapshot") { + t.Fatalf("expected snapshot error, got %v", err) + } + if updateCalled { + t.Fatalf("issue was overwritten despite snapshot failure") + } +} + func TestCompactTier1_Ineligible(t *testing.T) { store := &stubStore{ checkEligibilityFn: func(context.Context, string, int) (bool, string, error) { return false, "recently compacted", nil }, diff --git a/internal/storage/compaction.go b/internal/storage/compaction.go index 1ce6c409b..cea35bb4b 100644 --- a/internal/storage/compaction.go +++ b/internal/storage/compaction.go @@ -12,4 +12,16 @@ type CompactionStore interface { ApplyCompaction(ctx context.Context, issueID string, tier int, originalSize int, compactedSize int, commitHash string) error GetTier1Candidates(ctx context.Context) ([]*types.CompactionCandidate, error) GetTier2Candidates(ctx context.Context) ([]*types.CompactionCandidate, error) + + // SnapshotIssue archives an issue's current text content before a + // destructive compaction overwrites it. tier is the level being compacted + // to. Must be called before the overwrite. + SnapshotIssue(ctx context.Context, issueID string, tier int) error + // GetCompactionSnapshot returns the most recent archived snapshot for an + // issue, or (nil, nil) when none exists. + GetCompactionSnapshot(ctx context.Context, issueID string) (*types.IssueSnapshot, error) + // RestoreFromSnapshot restores an issue's content from its most recent + // snapshot and steps its compaction level back down. Returns the applied + // snapshot, or (nil, nil) when none exists. + RestoreFromSnapshot(ctx context.Context, issueID string) (*types.IssueSnapshot, error) } diff --git a/internal/storage/dolt/compact.go b/internal/storage/dolt/compact.go index e6a0006ee..d47e76cb3 100644 --- a/internal/storage/dolt/compact.go +++ b/internal/storage/dolt/compact.go @@ -53,6 +53,38 @@ func (s *DoltStore) ApplyCompaction(ctx context.Context, issueID string, tier in }) } +// SnapshotIssue archives an issue's current text content before a destructive +// compaction overwrites it. See issueops.SnapshotIssueInTx. +func (s *DoltStore) SnapshotIssue(ctx context.Context, issueID string, tier int) error { + return s.withRetryTx(ctx, func(tx *sql.Tx) error { + return issueops.SnapshotIssueInTx(ctx, tx, issueID, tier) + }) +} + +// GetCompactionSnapshot returns the most recent archived snapshot for an issue, +// or (nil, nil) when none exists. +func (s *DoltStore) GetCompactionSnapshot(ctx context.Context, issueID string) (*types.IssueSnapshot, error) { + var snap *types.IssueSnapshot + err := s.withReadTx(ctx, func(tx *sql.Tx) error { + var err error + snap, err = issueops.GetLatestSnapshotInTx(ctx, tx, issueID) + return err + }) + return snap, err +} + +// RestoreFromSnapshot restores an issue's content from its most recent snapshot +// and steps its compaction level back down. See issueops.RestoreFromSnapshotInTx. +func (s *DoltStore) RestoreFromSnapshot(ctx context.Context, issueID string) (*types.IssueSnapshot, error) { + var snap *types.IssueSnapshot + err := s.withRetryTx(ctx, func(tx *sql.Tx) error { + var err error + snap, err = issueops.RestoreFromSnapshotInTx(ctx, tx, issueID) + return err + }) + return snap, err +} + // GetTier1Candidates returns issues eligible for tier 1 compaction. func (s *DoltStore) GetTier1Candidates(ctx context.Context) ([]*types.CompactionCandidate, error) { var result []*types.CompactionCandidate diff --git a/internal/storage/dolt/compact_test.go b/internal/storage/dolt/compact_test.go index 77b7c96d7..3b606f45f 100644 --- a/internal/storage/dolt/compact_test.go +++ b/internal/storage/dolt/compact_test.go @@ -788,3 +788,81 @@ func TestGetTier1Candidates_DependentCount(t *testing.T) { t.Errorf("expected dependent_count 1, got %d", candidates[0].DependentCount) } } + +func TestSnapshotRestoreRoundTrip(t *testing.T) { + store, cleanup := setupTestStore(t) + defer cleanup() + + ctx, cancel := testContext(t) + defer cancel() + + issue := &types.Issue{ + ID: "snap-rt", + Title: "Round Trip", + Description: "the original description", + Design: "the original design", + Notes: "the original notes", + AcceptanceCriteria: "the original acceptance criteria", + Status: types.StatusOpen, + Priority: 2, + IssueType: types.TypeTask, + } + if err := store.CreateIssue(ctx, issue, "tester"); err != nil { + t.Fatalf("create issue: %v", err) + } + + // No snapshot yet. + if snap, err := store.GetCompactionSnapshot(ctx, issue.ID); err != nil || snap != nil { + t.Fatalf("expected no snapshot, got snap=%v err=%v", snap, err) + } + + // Archive, then simulate the destructive compaction overwrite. + if err := store.SnapshotIssue(ctx, issue.ID, 1); err != nil { + t.Fatalf("snapshot: %v", err) + } + updates := map[string]interface{}{ + "description": "summary", "design": "", "notes": "", "acceptance_criteria": "", + } + if err := store.UpdateIssue(ctx, issue.ID, updates, "compactor"); err != nil { + t.Fatalf("overwrite: %v", err) + } + if err := store.ApplyCompaction(ctx, issue.ID, 1, 100, 7, "deadbeef"); err != nil { + t.Fatalf("apply compaction: %v", err) + } + + // Snapshot preserves the originals. + snap, err := store.GetCompactionSnapshot(ctx, issue.ID) + if err != nil { + t.Fatalf("get snapshot: %v", err) + } + if snap == nil { + t.Fatalf("expected snapshot after archiving") + } + if snap.Description != "the original description" || snap.Design != "the original design" || + snap.Notes != "the original notes" || snap.AcceptanceCriteria != "the original acceptance criteria" { + t.Fatalf("snapshot content mismatch: %+v", snap) + } + if snap.CompactionLevel != 1 { + t.Fatalf("expected snapshot level 1, got %d", snap.CompactionLevel) + } + + // Restore writes the originals back and clears compaction bookkeeping. + applied, err := store.RestoreFromSnapshot(ctx, issue.ID) + if err != nil { + t.Fatalf("restore: %v", err) + } + if applied == nil { + t.Fatalf("expected restore to apply a snapshot") + } + got, err := store.GetIssue(ctx, issue.ID) + if err != nil { + t.Fatalf("get restored issue: %v", err) + } + if got.Description != "the original description" || got.Design != "the original design" || + got.Notes != "the original notes" || got.AcceptanceCriteria != "the original acceptance criteria" { + t.Fatalf("restored content mismatch: %+v", got) + } + if got.CompactionLevel != 0 { + t.Fatalf("expected compaction_level reset to 0, got %d", got.CompactionLevel) + } +} diff --git a/internal/storage/embeddeddolt/store.go b/internal/storage/embeddeddolt/store.go index 8f87a19a8..2b6521d91 100644 --- a/internal/storage/embeddeddolt/store.go +++ b/internal/storage/embeddeddolt/store.go @@ -850,6 +850,32 @@ func (s *EmbeddedDoltStore) ApplyCompaction(ctx context.Context, issueID string, }) } +func (s *EmbeddedDoltStore) SnapshotIssue(ctx context.Context, issueID string, tier int) error { + return s.withConn(ctx, true, func(tx *sql.Tx) error { + return issueops.SnapshotIssueInTx(ctx, tx, issueID, tier) + }) +} + +func (s *EmbeddedDoltStore) GetCompactionSnapshot(ctx context.Context, issueID string) (*types.IssueSnapshot, error) { + var snap *types.IssueSnapshot + err := s.withConn(ctx, false, func(tx *sql.Tx) error { + var err error + snap, err = issueops.GetLatestSnapshotInTx(ctx, tx, issueID) + return err + }) + return snap, err +} + +func (s *EmbeddedDoltStore) RestoreFromSnapshot(ctx context.Context, issueID string) (*types.IssueSnapshot, error) { + var snap *types.IssueSnapshot + err := s.withConn(ctx, true, func(tx *sql.Tx) error { + var err error + snap, err = issueops.RestoreFromSnapshotInTx(ctx, tx, issueID) + return err + }) + return snap, err +} + func (s *EmbeddedDoltStore) GetTier1Candidates(ctx context.Context) ([]*types.CompactionCandidate, error) { var result []*types.CompactionCandidate err := s.withConn(ctx, false, func(tx *sql.Tx) error { diff --git a/internal/storage/issueops/compaction.go b/internal/storage/issueops/compaction.go index f0daee749..f5ba84ed3 100644 --- a/internal/storage/issueops/compaction.go +++ b/internal/storage/issueops/compaction.go @@ -3,6 +3,7 @@ package issueops import ( "context" "database/sql" + "encoding/json" "fmt" "strconv" "time" @@ -97,6 +98,102 @@ func ApplyCompactionInTx(ctx context.Context, tx *sql.Tx, issueID string, tier i return nil } +// SnapshotIssueInTx archives an issue's current text content into +// compaction_snapshots before a destructive compaction overwrites it. The row +// is tagged with the tier the issue is being compacted *to* (so a later restore +// of a tier-N issue finds the pre-N content) and is the source of truth for +// bd restore. Callers MUST invoke this before clearing/overwriting the fields +// so the archive captures the originals. +func SnapshotIssueInTx(ctx context.Context, tx *sql.Tx, issueID string, tier int) error { + snap := types.IssueSnapshot{CompactionLevel: tier} + err := tx.QueryRowContext(ctx, + `SELECT title, description, design, notes, acceptance_criteria FROM issues WHERE id = ?`, issueID, + ).Scan(&snap.Title, &snap.Description, &snap.Design, &snap.Notes, &snap.AcceptanceCriteria) + if err == sql.ErrNoRows { + return fmt.Errorf("snapshot issue %s: not found", issueID) + } + if err != nil { + return fmt.Errorf("snapshot issue %s: read content: %w", issueID, err) + } + + payload, err := json.Marshal(&snap) + if err != nil { + return fmt.Errorf("snapshot issue %s: marshal: %w", issueID, err) + } + + now := time.Now().UTC() + if _, err := tx.ExecContext(ctx, + `INSERT INTO compaction_snapshots (id, issue_id, compaction_level, snapshot_json, created_at) VALUES (?, ?, ?, ?, ?)`, + NewEventID(), issueID, tier, payload, now, + ); err != nil { + return fmt.Errorf("snapshot issue %s: insert: %w", issueID, err) + } + return nil +} + +// GetLatestSnapshotInTx returns the most recent compaction snapshot for an +// issue, or (nil, nil) when none exists. +func GetLatestSnapshotInTx(ctx context.Context, tx *sql.Tx, issueID string) (*types.IssueSnapshot, error) { + var payload []byte + var level int + err := tx.QueryRowContext(ctx, + `SELECT compaction_level, snapshot_json FROM compaction_snapshots WHERE issue_id = ? ORDER BY created_at DESC LIMIT 1`, + issueID, + ).Scan(&level, &payload) + if err == sql.ErrNoRows { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("get snapshot for %s: %w", issueID, err) + } + snap := &types.IssueSnapshot{} + if err := json.Unmarshal(payload, snap); err != nil { + return nil, fmt.Errorf("get snapshot for %s: unmarshal: %w", issueID, err) + } + snap.CompactionLevel = level + return snap, nil +} + +// RestoreFromSnapshotInTx restores an issue's text content from its most recent +// compaction snapshot and steps its compaction level back down by one. It +// returns the snapshot that was applied, or (nil, nil) when no snapshot exists. +// The snapshot row is left in place as an audit trail. +func RestoreFromSnapshotInTx(ctx context.Context, tx *sql.Tx, issueID string) (*types.IssueSnapshot, error) { + snap, err := GetLatestSnapshotInTx(ctx, tx, issueID) + if err != nil { + return nil, err + } + if snap == nil { + return nil, nil + } + + now := time.Now().UTC() + newLevel := max(snap.CompactionLevel-1, 0) + + if newLevel == 0 { + // Fully restored: clear the compaction bookkeeping so the issue looks + // uncompacted again. + _, err = tx.ExecContext(ctx, ` + UPDATE issues + SET description = ?, design = ?, notes = ?, acceptance_criteria = ?, + compaction_level = 0, compacted_at = NULL, compacted_at_commit = '', original_size = 0, + updated_at = ? + WHERE id = ?`, + snap.Description, snap.Design, snap.Notes, snap.AcceptanceCriteria, now, issueID) + } else { + _, err = tx.ExecContext(ctx, ` + UPDATE issues + SET description = ?, design = ?, notes = ?, acceptance_criteria = ?, + compaction_level = ?, updated_at = ? + WHERE id = ?`, + snap.Description, snap.Design, snap.Notes, snap.AcceptanceCriteria, newLevel, now, issueID) + } + if err != nil { + return nil, fmt.Errorf("restore issue %s: %w", issueID, err) + } + return snap, nil +} + // GetTier1CandidatesInTx returns issues eligible for tier 1 compaction. func GetTier1CandidatesInTx(ctx context.Context, tx *sql.Tx) ([]*types.CompactionCandidate, error) { days := getCompactDaysInTx(ctx, tx, 1) diff --git a/internal/types/storage_ext.go b/internal/types/storage_ext.go index 46cf8da3b..4362a5586 100644 --- a/internal/types/storage_ext.go +++ b/internal/types/storage_ext.go @@ -14,6 +14,23 @@ type CompactionCandidate struct { DependentCount int } +// IssueSnapshot is a pre-compaction copy of an issue's mutable text content, +// archived (into compaction_snapshots) before compaction destructively +// overwrites it. It is the source of truth for `bd restore`. The JSON tags are +// the on-disk snapshot_json wire format and must not be renamed: older archived +// rows are decoded with these names. +type IssueSnapshot struct { + // CompactionLevel is the tier the issue was being compacted *to* when this + // snapshot was taken, i.e. the level whose pre-compaction content this row + // preserves. It is stored in its own column, not in snapshot_json. + CompactionLevel int `json:"-"` + Title string `json:"title"` + Description string `json:"description"` + Design string `json:"design"` + Notes string `json:"notes"` + AcceptanceCriteria string `json:"acceptance_criteria"` +} + // DeleteIssuesResult contains statistics from a batch delete operation. // Used when deleting multiple issues with cascade/force options. type DeleteIssuesResult struct { diff --git a/website/docs/cli-reference/restore.md b/website/docs/cli-reference/restore.md index 3d658fd0c..f0514aa17 100644 --- a/website/docs/cli-reference/restore.md +++ b/website/docs/cli-reference/restore.md @@ -10,13 +10,19 @@ Generated from `bd help --doc restore` ## bd restore -Restore full history of a compacted issue from Dolt version history. +Restore the pre-compaction content of a compacted issue. -When an issue is compacted, its description and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database. +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. ``` bd restore [flags] @@ -25,5 +31,6 @@ bd restore [flags] **Flags:** ``` - --json Output restore results in JSON format + --apply Write the restored content back into the issue (default: display only) + --json Output restore results in JSON format ``` diff --git a/website/static/llms-full.txt b/website/static/llms-full.txt index 55a50b919..0d93d82cf 100644 --- a/website/static/llms-full.txt +++ b/website/static/llms-full.txt @@ -9063,13 +9063,19 @@ Generated from `bd help --doc restore` ## bd restore -Restore full history of a compacted issue from Dolt version history. +Restore the pre-compaction content of a compacted issue. -When an issue is compacted, its description and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database. +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. ``` bd restore [flags] @@ -9078,7 +9084,8 @@ bd restore [flags] **Flags:** ``` - --json Output restore results in JSON format + --apply Write the restored content back into the issue (default: display only) + --json Output restore results in JSON format ``` diff --git a/website/versioned_docs/version-1.0.0/cli-reference/restore.md b/website/versioned_docs/version-1.0.0/cli-reference/restore.md index 3d658fd0c..f0514aa17 100644 --- a/website/versioned_docs/version-1.0.0/cli-reference/restore.md +++ b/website/versioned_docs/version-1.0.0/cli-reference/restore.md @@ -10,13 +10,19 @@ Generated from `bd help --doc restore` ## bd restore -Restore full history of a compacted issue from Dolt version history. +Restore the pre-compaction content of a compacted issue. -When an issue is compacted, its description and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database. +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. ``` bd restore [flags] @@ -25,5 +31,6 @@ bd restore [flags] **Flags:** ``` - --json Output restore results in JSON format + --apply Write the restored content back into the issue (default: display only) + --json Output restore results in JSON format ``` diff --git a/website/versioned_docs/version-1.0.4/cli-reference/restore.md b/website/versioned_docs/version-1.0.4/cli-reference/restore.md index 3d658fd0c..f0514aa17 100644 --- a/website/versioned_docs/version-1.0.4/cli-reference/restore.md +++ b/website/versioned_docs/version-1.0.4/cli-reference/restore.md @@ -10,13 +10,19 @@ Generated from `bd help --doc restore` ## bd restore -Restore full history of a compacted issue from Dolt version history. +Restore the pre-compaction content of a compacted issue. -When an issue is compacted, its description and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database. +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. ``` bd restore [flags] @@ -25,5 +31,6 @@ bd restore [flags] **Flags:** ``` - --json Output restore results in JSON format + --apply Write the restored content back into the issue (default: display only) + --json Output restore results in JSON format ``` diff --git a/website/versioned_docs/version-1.0.5/cli-reference/restore.md b/website/versioned_docs/version-1.0.5/cli-reference/restore.md index 3d658fd0c..f0514aa17 100644 --- a/website/versioned_docs/version-1.0.5/cli-reference/restore.md +++ b/website/versioned_docs/version-1.0.5/cli-reference/restore.md @@ -10,13 +10,19 @@ Generated from `bd help --doc restore` ## bd restore -Restore full history of a compacted issue from Dolt version history. +Restore the pre-compaction content of a compacted issue. -When an issue is compacted, its description and notes are truncated. -This command queries Dolt's history tables to find the pre-compaction -version and displays the full issue content. +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. -This is read-only and does not modify the database. +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. ``` bd restore [flags] @@ -25,5 +31,6 @@ bd restore [flags] **Flags:** ``` - --json Output restore results in JSON format + --apply Write the restored content back into the issue (default: display only) + --json Output restore results in JSON format ```