diff --git a/cmd/bd/conflicts.go b/cmd/bd/conflicts.go index 332691a91..274a38fe1 100644 --- a/cmd/bd/conflicts.go +++ b/cmd/bd/conflicts.go @@ -480,11 +480,6 @@ func concludeResolvedMerge(ctx context.Context) error { if err != nil { return HandleErrorRespectJSON("failed to read conflicts: %v", err) } - // Short-circuit before the blocker read: with rows still conflicted the - // blockers cannot change the answer, and there is nothing to diagnose yet. - if remaining > 0 { - return HandleErrorRespectJSON("%d conflict(s) are still live; resolve them first (bd conflicts list)", remaining) - } blockers, blockerErr := mergeBlockers(ctx) if blockerErr != nil { // The blocker read is diagnosis, never a gate — but a caller that @@ -637,7 +632,11 @@ func writeMergeBlockers(w io.Writer, b storage.MergeBlockers) { } if len(b.ConstraintViolations) > 0 { fmt.Fprintln(w, " Constraint violations: inspect dolt_constraint_violations_, delete the offending rows,") - fmt.Fprintln(w, " then conclude with: bd conflicts resolve --conclude") + if len(b.SchemaConflictTables) > 0 { + fmt.Fprintln(w, " then re-inspect after aborting and re-merging the schema change") + } else { + fmt.Fprintln(w, " then conclude with: bd conflicts resolve --conclude") + } } } diff --git a/cmd/bd/conflicts_conclude_integration_test.go b/cmd/bd/conflicts_conclude_integration_test.go new file mode 100644 index 000000000..2d27abe7e --- /dev/null +++ b/cmd/bd/conflicts_conclude_integration_test.go @@ -0,0 +1,260 @@ +//go:build cgo + +package main + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" +) + +// concludeProbeStore keeps the real Dolt store underneath the command while +// making two otherwise hard-to-reproduce edges deterministic: a failed +// diagnostic read, and a commit implementation that silently leaves the merge +// open. It deliberately does not implement storage.Unwrapper, so the optional +// MergeBlockerInspector methods below remain visible to mergeBlockers. +type concludeProbeStore struct { + storage.DoltStorage + blockers *storage.MergeBlockers + blockerErr error + noOpCommit bool + commitErr error +} + +func (s *concludeProbeStore) GetMergeBlockers(ctx context.Context) (storage.MergeBlockers, error) { + if s.blockers != nil || s.blockerErr != nil { + if s.blockers == nil { + return storage.MergeBlockers{}, s.blockerErr + } + return *s.blockers, s.blockerErr + } + return s.DoltStorage.(storage.MergeBlockerInspector).GetMergeBlockers(ctx) +} + +func (s *concludeProbeStore) CommitMergeResolution(ctx context.Context, message string) error { + if s.commitErr != nil { + return s.commitErr + } + if s.noOpCommit { + return nil + } + return s.DoltStorage.CommitMergeResolution(ctx, message) +} + +func wedgeResolvedConcludeMerge(t *testing.T) storage.DoltStorage { + t.Helper() + ctx := context.Background() + raw := newTestStore(t, filepath.Join(t.TempDir(), ".beads", "beads.db")) + db := raw.DB() + + const issueID = "conclude-command-1" + if err := raw.CreateIssue(ctx, &types.Issue{ + ID: issueID, Title: "base", Status: types.StatusOpen, + Priority: 2, IssueType: types.TypeTask, + }, "test"); err != nil { + t.Fatalf("create seed issue: %v", err) + } + if err := raw.Commit(ctx, "seed conclude command test"); err != nil { + t.Fatalf("commit seed issue: %v", err) + } + + var currentBranch string + if err := db.QueryRowContext(ctx, "SELECT active_branch()").Scan(¤tBranch); err != nil { + t.Fatalf("read current branch: %v", err) + } + peerBranch := currentBranch + "_conclude_peer" + if err := raw.Branch(ctx, peerBranch); err != nil { + t.Fatalf("create peer branch: %v", err) + } + t.Cleanup(func() { + cleanupCtx := context.Background() + _, _ = db.ExecContext(cleanupCtx, "CALL DOLT_MERGE('--abort')") + _, _ = db.ExecContext(cleanupCtx, "CALL DOLT_CHECKOUT(?)", currentBranch) + _, _ = db.ExecContext(cleanupCtx, "CALL DOLT_BRANCH('-Df', ?)", peerBranch) + }) + + if _, err := db.ExecContext(ctx, "UPDATE issues SET title = 'ours' WHERE id = ?", issueID); err != nil { + t.Fatalf("update ours: %v", err) + } + if err := raw.Commit(ctx, "our conclude title"); err != nil { + t.Fatalf("commit ours: %v", err) + } + if err := raw.Checkout(ctx, peerBranch); err != nil { + t.Fatalf("checkout peer: %v", err) + } + if _, err := db.ExecContext(ctx, "UPDATE issues SET title = 'theirs' WHERE id = ?", issueID); err != nil { + t.Fatalf("update theirs: %v", err) + } + if err := raw.Commit(ctx, "their conclude title"); err != nil { + t.Fatalf("commit theirs: %v", err) + } + if err := raw.Checkout(ctx, currentBranch); err != nil { + t.Fatalf("checkout current: %v", err) + } + for _, stmt := range []string{ + "SET @@dolt_allow_commit_conflicts = 1", + "SET @@dolt_force_transaction_commit = 1", + } { + if _, err := db.ExecContext(ctx, stmt); err != nil { + t.Fatalf("%s: %v", stmt, err) + } + } + if _, err := db.ExecContext(ctx, "CALL DOLT_MERGE(?)", peerBranch); err != nil { + t.Logf("DOLT_MERGE returned: %v", err) + } + rows, err := raw.GetConflictRows(ctx, "issues") + if err != nil || len(rows) != 1 { + t.Fatalf("wedge live conflict: rows=%d err=%v", len(rows), err) + } + return raw +} + +func runConcludeCommand(t *testing.T, commandStore storage.DoltStorage, asJSON bool) (string, string, error) { + t.Helper() + stdioMutex.Lock() + defer stdioMutex.Unlock() + + oldStdout, oldStderr := os.Stdout, os.Stderr + oldStore, oldRootCtx, oldJSON := store, rootCtx, jsonOutput + oldConclude := conflictsConclude + rOut, wOut, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + rErr, wErr, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + os.Stdout, os.Stderr = wOut, wErr + store, rootCtx, jsonOutput = commandStore, context.Background(), asJSON + conflictsConclude = true + + commandErr := conflictsResolveCmd.RunE(conflictsResolveCmd, nil) + + _ = wOut.Close() + _ = wErr.Close() + os.Stdout, os.Stderr = oldStdout, oldStderr + store, rootCtx, jsonOutput = oldStore, oldRootCtx, oldJSON + conflictsConclude = oldConclude + + var stdout, stderr bytes.Buffer + _, _ = stdout.ReadFrom(rOut) + _, _ = stderr.ReadFrom(rErr) + _ = rOut.Close() + _ = rErr.Close() + return stdout.String(), stderr.String(), commandErr +} + +func requireExitOne(t *testing.T, err error) { + t.Helper() + if code, ok := exitCodeFromError(err); !ok || code != 1 { + t.Fatalf("command error = %v, want exit code 1", err) + } +} + +func decodeConcludePayload(t *testing.T, out string) map[string]interface{} { + t.Helper() + var payload map[string]interface{} + if err := json.Unmarshal([]byte(out), &payload); err != nil { + t.Fatalf("decode conclude JSON %q: %v", out, err) + } + return payload +} + +func requireConcludeKeys(t *testing.T, payload map[string]interface{}) { + t.Helper() + got := make([]string, 0, len(payload)) + for key := range payload { + got = append(got, key) + } + sort.Strings(got) + want := []string{"blockers", "committed", "merging", "remaining", "schema_version"} + if strings.Join(got, ",") != strings.Join(want, ",") { + t.Fatalf("conclude JSON keys = %v, want %v", got, want) + } +} + +// TestConcludeResolvedMergeCommand drives the actual resolve command handler +// over a real Dolt merge. It pins every branch that planConclude's unit tests +// cannot: JSON's non-zero error, warning emission, haveStatus dispatch, stable +// success/no-op payloads, the real merge commit, and the post-commit guard. +func TestConcludeResolvedMergeCommand(t *testing.T) { + raw := wedgeResolvedConcludeMerge(t) + ctx := context.Background() + + t.Run("live conflicts fail in JSON mode", func(t *testing.T) { + out, _, err := runConcludeCommand(t, raw, true) + requireExitOne(t, err) + payload := decodeConcludePayload(t, out) + if !strings.Contains(payload["error"].(string), "still live") { + t.Fatalf("live-conflict JSON = %v", payload) + } + }) + + inspector := raw.(storage.ConflictInspector) + if n, err := inspector.ResolveConflictRows(ctx, "issues", []string{"conclude-command-1"}, "ours"); err != nil || n != 1 { + t.Fatalf("resolve conflict without concluding: n=%d err=%v", n, err) + } + + t.Run("blockers fail in JSON mode", func(t *testing.T) { + blocked := storage.MergeBlockers{Merging: true, SchemaConflictTables: []string{"issues"}} + out, _, err := runConcludeCommand(t, &concludeProbeStore{DoltStorage: raw, blockers: &blocked}, true) + requireExitOne(t, err) + payload := decodeConcludePayload(t, out) + if !strings.Contains(payload["error"].(string), "merge not concluded") { + t.Fatalf("blocked JSON = %v", payload) + } + }) + + t.Run("blocker read warning is visible", func(t *testing.T) { + probeErr := errors.New("probe blocker read failed") + _, stderr, err := runConcludeCommand(t, &concludeProbeStore{ + DoltStorage: raw, blockerErr: probeErr, commitErr: errors.New("stop after warning"), + }, false) + requireExitOne(t, err) + if !strings.Contains(stderr, "Warning: could not read") || !strings.Contains(stderr, probeErr.Error()) { + t.Fatalf("stderr missing blocker warning: %q", stderr) + } + }) + + t.Run("silent no-op commit is rejected", func(t *testing.T) { + _, stderr, err := runConcludeCommand(t, &concludeProbeStore{DoltStorage: raw, noOpCommit: true}, false) + requireExitOne(t, err) + if !strings.Contains(stderr, "commit did not conclude the merge") { + t.Fatalf("stderr missing post-commit guard: %q", stderr) + } + }) + + t.Run("real commit has stable JSON payload", func(t *testing.T) { + out, _, err := runConcludeCommand(t, raw, true) + if err != nil { + t.Fatalf("conclude real merge: %v; output=%s", err, out) + } + payload := decodeConcludePayload(t, out) + requireConcludeKeys(t, payload) + if payload["committed"] != true || payload["remaining"] != float64(0) || payload["merging"] != false { + t.Fatalf("committed payload = %v", payload) + } + }) + + t.Run("nothing to conclude uses the same JSON shape", func(t *testing.T) { + out, _, err := runConcludeCommand(t, raw, true) + if err != nil { + t.Fatalf("conclude closed merge: %v; output=%s", err, out) + } + payload := decodeConcludePayload(t, out) + requireConcludeKeys(t, payload) + if payload["committed"] != false || payload["remaining"] != float64(0) || payload["merging"] != false { + t.Fatalf("no-op payload = %v", payload) + } + }) +} diff --git a/cmd/bd/conflicts_conclude_test.go b/cmd/bd/conflicts_conclude_test.go index a97438a70..712a28005 100644 --- a/cmd/bd/conflicts_conclude_test.go +++ b/cmd/bd/conflicts_conclude_test.go @@ -7,14 +7,10 @@ import ( "github.com/steveyegge/beads/internal/storage" ) -// Coverage for `bd conflicts resolve --conclude` and the BLOCKING merge state -// (wy-36ilm F12) — the paths wy-wrq9o F5 found untested. The three decisions -// they turn on are pure functions of the merge state (planConclude, -// shouldCommitResolution, concludeFlagConflict) plus the remedy text -// (writeMergeBlockers), so a Blocked() inversion, a dropped merge-status -// check, or a remedy pointing back at the dolt command that always errors -// (adversarial review F1) is caught with no dolt and no Docker. The real -// system-table column names are guarded separately, dolt-backed, in +// Pure-logic coverage for `bd conflicts resolve --conclude` and the BLOCKING +// merge state (wy-36ilm F12). Command wiring, JSON output and real merge +// transitions are covered, dolt-backed, in conflicts_conclude_integration_test.go. +// The real system-table column names are guarded separately in // internal/storage/dolt/conflicts_integration_test.go. func schemaBlockers(tables ...string) storage.MergeBlockers { @@ -240,6 +236,9 @@ func TestWriteMergeBlockersRemedies(t *testing.T) { if !strings.Contains(out, "Schema conflicts:") || !strings.Contains(out, "Constraint violations:") { t.Errorf("both classes outstanding must show both remedies:\n%s", out) } + if strings.Contains(out, "bd conflicts resolve --conclude") { + t.Errorf("must not recommend --conclude while a schema conflict makes it refuse:\n%s", out) + } }) } diff --git a/internal/storage/dolt/conflicts_integration_test.go b/internal/storage/dolt/conflicts_integration_test.go index c59ea035b..7b54a9f93 100644 --- a/internal/storage/dolt/conflicts_integration_test.go +++ b/internal/storage/dolt/conflicts_integration_test.go @@ -309,10 +309,9 @@ func TestConflictInspectorSurvivesTheStoreDecoratorChain(t *testing.T) { // dolt_constraint_violations.(`table`, num_violations). wy-wrq9o F5: those // reads had no test at all — a column rename, a dropped `WHERE num_violations // > 0`, or a Blocked() inversion would have landed green. These reproduce -// both blocker classes for real and assert the whole gate behaves: blockers -// visible, Blocked() true, and the merge commit held rather than failing with -// a raw dolt error. The pure-logic half of the gate (planConclude, -// shouldCommitResolution, the remedy text) is in cmd/bd/conflicts_conclude_test.go. +// both blocker classes for real and assert the storage half of the gate: +// blockers are visible and Blocked() is true. The command-level commit hold +// and remedies are covered in cmd/bd/conflicts_conclude*_test.go. // wedgeConstraintViolation leaves a real FK constraint violation in the // working set: our branch deleted an issue, the peer added a child row @@ -422,10 +421,11 @@ func TestGetMergeBlockersSeesASchemaConflict(t *testing.T) { if _, err := db.ExecContext(ctx, "CALL DOLT_BRANCH(?, 'HEAD')", peerBranch); err != nil { t.Fatalf("create peer branch: %v", err) } - t.Cleanup(func() { - db.ExecContext(ctx, "CALL DOLT_CHECKOUT(?)", currentBranch) - db.ExecContext(ctx, "CALL DOLT_BRANCH('-Df', ?)", peerBranch) - }) + defer func() { + _, _ = db.ExecContext(context.Background(), "CALL DOLT_MERGE('--abort')") + _, _ = db.ExecContext(context.Background(), "CALL DOLT_CHECKOUT(?)", currentBranch) + _, _ = db.ExecContext(context.Background(), "CALL DOLT_BRANCH('-Df', ?)", peerBranch) + }() // Divergent ALTER TABLE: same column name, incompatible types. if _, err := db.ExecContext(ctx, "ALTER TABLE "+probeTable+" ADD COLUMN note VARCHAR(32)"); err != nil { diff --git a/internal/storage/embeddeddolt/merge_blockers_test.go b/internal/storage/embeddeddolt/merge_blockers_test.go index 299b0a057..7274e94fc 100644 --- a/internal/storage/embeddeddolt/merge_blockers_test.go +++ b/internal/storage/embeddeddolt/merge_blockers_test.go @@ -12,8 +12,9 @@ import ( // and the CLI reaches it through storage.UnwrapStore exactly as it reaches // the server-mode one. The reads run against the embedded engine's own // dolt_merge_status / dolt_schema_conflicts / dolt_constraint_violations, so -// a system table or column the embedded engine names differently (or does not -// expose at all) shows up here and nowhere else. +// a system table or column the embedded engine names differently is caught +// here. Missing optional system tables are intentionally tolerated and appear +// as empty blocker classes. // TestEmbeddedGetMergeBlockersOnAQuietStore is the baseline every other // caller depends on: with no merge open, GetMergeBlockers must report an