feat(sync): add per-field merge strategies for conflict resolution

Implements configurable per-field merge strategies (hq-ew1mbr.11):

- Add FieldStrategy type with strategies: newest, max, union, manual
- Add conflict.fields config section for per-field overrides
- compaction_level defaults to "max" (highest value wins)
- estimated_minutes defaults to "manual" (flags for user resolution)
- labels defaults to "union" (set merge)

Manual conflicts are displayed during sync with resolution options:
  bd sync --ours / --theirs, or bd resolve <id> <field> <value>

Config example:
  conflict:
    strategy: newest
    fields:
      compaction_level: max
      estimated_minutes: manual
      labels: union

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
beads/crew/lydia
2026-01-21 19:39:20 -08:00
committed by Steve Yegge
parent e0dc3a37c3
commit 9a9704b451
9 changed files with 698 additions and 91 deletions

View File

@@ -572,6 +572,11 @@ func doPullFirstSync(ctx context.Context, jsonlPath string, renameOnImport, noGi
fmt.Printf(" Local wins: %d, Remote wins: %d, Same: %d, Conflicts (LWW): %d\n",
localCount, remoteCount, sameCount, mergeResult.Conflicts)
// Display manual conflicts that need user resolution
if len(mergeResult.ManualConflicts) > 0 {
displayManualConflicts(mergeResult.ManualConflicts)
}
// Step 6: Import merged state to DB
// First, write merged result to JSONL so import can read it
fmt.Println("→ Writing merged state to JSONL...")
@@ -1071,6 +1076,11 @@ func resolveSyncConflicts(ctx context.Context, jsonlPath string, strategy config
// Re-run merge with the resolved conflicts
mergeResult := MergeIssues(baseIssues, localIssues, remoteIssues)
// Display any remaining manual conflicts
if len(mergeResult.ManualConflicts) > 0 {
displayManualConflicts(mergeResult.ManualConflicts)
}
// Write merged state
if err := writeMergedStateToJSONL(jsonlPath, mergeResult.Merged); err != nil {
return fmt.Errorf("writing merged state: %w", err)
@@ -1177,7 +1187,7 @@ func resolveSyncConflictsManually(ctx context.Context, jsonlPath, beadsDir strin
local := localMap[id]
remote := remoteMap[id]
base := baseMap[id]
merged, _ := MergeIssue(base, local, remote)
merged, _, _ := MergeIssue(base, local, remote)
if merged != nil {
mergedIssues = append(mergedIssues, merged)
}

View File

@@ -69,7 +69,7 @@ func resolveConflictsInteractively(conflicts []InteractiveConflict) ([]*beads.Is
for j := i; j < len(conflicts); j++ {
c := conflicts[j]
if c.Local != nil && c.Remote != nil {
merged := mergeFieldLevel(c.Base, c.Local, c.Remote)
merged, _ := mergeFieldLevel(c.Base, c.Local, c.Remote)
resolved = append(resolved, merged)
} else if c.Local != nil {
resolved = append(resolved, c.Local)
@@ -293,7 +293,7 @@ func promptConflictResolution(reader *bufio.Reader, conflict InteractiveConflict
case "merged":
// Do field-level merge (same as automatic LWW merge)
merged := mergeFieldLevel(conflict.Base, local, remote)
merged, _ := mergeFieldLevel(conflict.Base, local, remote)
return InteractiveResolution{Choice: "merged", Issue: merged}, nil
case "skip":

View File

@@ -285,7 +285,7 @@ func TestInteractiveResolutionMerge(t *testing.T) {
// mergeFieldLevel should pick local values (newer) for scalars
// and union for labels
merged := mergeFieldLevel(nil, local, remote)
merged, _ := mergeFieldLevel(nil, local, remote)
if merged.Title != "Local title" {
t.Errorf("Expected title 'Local title', got %q", merged.Title)

View File

@@ -10,13 +10,27 @@ import (
"time"
"github.com/steveyegge/beads/internal/beads"
"github.com/steveyegge/beads/internal/config"
)
// MergeResult contains the outcome of a 3-way merge
type MergeResult struct {
Merged []*beads.Issue // Final merged state
Conflicts int // Number of true conflicts resolved
Strategy map[string]string // Per-issue: "local", "remote", "merged", "same"
Merged []*beads.Issue // Final merged state
Conflicts int // Number of true conflicts resolved
Strategy map[string]string // Per-issue: "local", "remote", "merged", "same"
ManualConflicts []ManualConflict // Fields requiring manual resolution
}
// ManualConflict represents a field conflict that requires manual user resolution.
// When a field's strategy is "manual", the conflict is flagged here instead of
// being auto-resolved.
type ManualConflict struct {
IssueID string // Issue ID with conflict
Field string // Field name (e.g., "estimated_minutes")
LocalValue interface{} // Local (ours) value
RemoteValue interface{} // Remote (theirs) value
LocalTime time.Time // When local value was set
RemoteTime time.Time // When remote value was set
}
// MergeStrategy constants for describing how each issue was merged
@@ -27,43 +41,19 @@ const (
StrategySame = "same" // Both made identical change (or no change)
)
// FieldMergeRule defines how a specific field is merged in conflicts
type FieldMergeRule string
const (
RuleLWW FieldMergeRule = "lww" // Last-Write-Wins by updated_at
RuleUnion FieldMergeRule = "union" // Set union (OR-Set)
RuleAppend FieldMergeRule = "append" // Append-only merge
)
// FieldRules maps field names to merge rules
// Scalar fields use LWW, collection fields use union/append
var FieldRules = map[string]FieldMergeRule{
// Scalar fields - LWW by updated_at
"status": RuleLWW,
"priority": RuleLWW,
"assignee": RuleLWW,
"title": RuleLWW,
"description": RuleLWW,
"design": RuleLWW,
"issue_type": RuleLWW,
"notes": RuleLWW,
// Set fields - union (no data loss)
"labels": RuleUnion,
"dependencies": RuleUnion,
// Append-only fields
"comments": RuleAppend,
}
// mergeFieldLevel performs field-by-field merge for true conflicts.
// Returns a new issue with:
// - Scalar fields: from the newer issue (LWW by updated_at, remote wins on tie)
// - Labels: union of both
// - Dependencies: union of both (by DependsOnID+Type)
// - Comments: append from both (deduplicated by ID or content)
func mergeFieldLevel(_base, local, remote *beads.Issue) *beads.Issue {
// - compaction_level: max strategy (highest value wins)
// - estimated_minutes: manual strategy if configured (flags for user resolution)
//
// Also returns any manual conflicts that require user resolution.
func mergeFieldLevel(_base, local, remote *beads.Issue) (*beads.Issue, []ManualConflict) {
var manualConflicts []ManualConflict
// Determine which is newer for LWW scalars
localNewer := local.UpdatedAt.After(remote.UpdatedAt)
@@ -85,8 +75,66 @@ func mergeFieldLevel(_base, local, remote *beads.Issue) *beads.Issue {
merged = *remote
}
// Union merge: Labels
merged.Labels = mergeLabels(local.Labels, remote.Labels)
// Get per-field strategies from config
fieldStrategies := config.GetFieldStrategies()
// Handle compaction_level with configurable strategy (default: max)
compactionStrategy := fieldStrategies["compaction_level"]
if compactionStrategy == "" {
compactionStrategy = config.FieldStrategyMax // Default for compaction_level
}
switch compactionStrategy {
case config.FieldStrategyMax:
merged.CompactionLevel = maxInt(local.CompactionLevel, remote.CompactionLevel)
case config.FieldStrategyNewest:
// Already handled by default LWW merge above
case config.FieldStrategyManual:
if local.CompactionLevel != remote.CompactionLevel {
manualConflicts = append(manualConflicts, ManualConflict{
IssueID: local.ID,
Field: "compaction_level",
LocalValue: local.CompactionLevel,
RemoteValue: remote.CompactionLevel,
LocalTime: local.UpdatedAt,
RemoteTime: remote.UpdatedAt,
})
// Keep local value as tentative (can be overridden by resolve command)
merged.CompactionLevel = local.CompactionLevel
}
}
// Handle estimated_minutes with configurable strategy (default: manual per spec)
estimatedStrategy := fieldStrategies["estimated_minutes"]
if estimatedStrategy == "" {
estimatedStrategy = config.FieldStrategyManual // Default for estimated_minutes (human judgment needed)
}
switch estimatedStrategy {
case config.FieldStrategyMax:
merged.EstimatedMinutes = maxIntPtr(local.EstimatedMinutes, remote.EstimatedMinutes)
case config.FieldStrategyNewest:
// Already handled by default LWW merge above
case config.FieldStrategyManual:
if !intPtrEqual(local.EstimatedMinutes, remote.EstimatedMinutes) {
manualConflicts = append(manualConflicts, ManualConflict{
IssueID: local.ID,
Field: "estimated_minutes",
LocalValue: derefIntPtr(local.EstimatedMinutes),
RemoteValue: derefIntPtr(remote.EstimatedMinutes),
LocalTime: local.UpdatedAt,
RemoteTime: remote.UpdatedAt,
})
// Keep local value as tentative
merged.EstimatedMinutes = local.EstimatedMinutes
}
}
// Union merge: Labels (always union unless configured otherwise)
labelsStrategy := fieldStrategies["labels"]
if labelsStrategy == "" || labelsStrategy == config.FieldStrategyUnion {
merged.Labels = mergeLabels(local.Labels, remote.Labels)
} else if labelsStrategy == config.FieldStrategyNewest {
// Use LWW for labels (already set from initial merge)
}
// Union merge: Dependencies (by DependsOnID+Type key)
merged.Dependencies = mergeDependencies(local.Dependencies, remote.Dependencies)
@@ -94,7 +142,65 @@ func mergeFieldLevel(_base, local, remote *beads.Issue) *beads.Issue {
// Append merge: Comments (deduplicated)
merged.Comments = mergeComments(local.Comments, remote.Comments)
return &merged
return &merged, manualConflicts
}
// maxInt returns the larger of two integers
func maxInt(a, b int) int {
if a > b {
return a
}
return b
}
// maxIntPtr returns a pointer to the larger of two *int values
// Treats nil as 0 for comparison purposes
func maxIntPtr(a, b *int) *int {
aVal := 0
bVal := 0
if a != nil {
aVal = *a
}
if b != nil {
bVal = *b
}
if aVal >= bVal {
return a
}
return b
}
// derefIntPtr safely dereferences an int pointer, returning nil representation for display
func derefIntPtr(p *int) interface{} {
if p == nil {
return nil
}
return *p
}
// displayManualConflicts prints manual conflicts that need user resolution.
// These are fields where the configured strategy is "manual" and values differ.
func displayManualConflicts(conflicts []ManualConflict) {
fmt.Fprintf(os.Stderr, "\n⚠ %d field conflict(s) require manual resolution:\n", len(conflicts))
for _, c := range conflicts {
fmt.Fprintf(os.Stderr, "\n %s.%s:\n", c.IssueID, c.Field)
fmt.Fprintf(os.Stderr, " Local: %v (set %s)\n", formatConflictValue(c.LocalValue), c.LocalTime.Format("2006-01-02"))
fmt.Fprintf(os.Stderr, " Remote: %v (set %s)\n", formatConflictValue(c.RemoteValue), c.RemoteTime.Format("2006-01-02"))
}
fmt.Fprintf(os.Stderr, "\n To resolve, use one of:\n")
fmt.Fprintf(os.Stderr, " bd sync --ours # Keep all local values\n")
fmt.Fprintf(os.Stderr, " bd sync --theirs # Keep all remote values\n")
fmt.Fprintf(os.Stderr, " bd resolve <issue-id> <field> <value> # Set specific value\n\n")
}
// formatConflictValue formats a conflict value for display
func formatConflictValue(v interface{}) string {
if v == nil {
return "(not set)"
}
return fmt.Sprintf("%v", v)
}
// mergeLabels performs set union on labels
@@ -244,8 +350,9 @@ func MergeIssues(base, local, remote []*beads.Issue) *MergeResult {
allIDs := collectUniqueIDs(baseMap, localMap, remoteMap)
result := &MergeResult{
Merged: make([]*beads.Issue, 0, len(allIDs)),
Strategy: make(map[string]string),
Merged: make([]*beads.Issue, 0, len(allIDs)),
Strategy: make(map[string]string),
ManualConflicts: make([]ManualConflict, 0),
}
for _, id := range allIDs {
@@ -253,11 +360,16 @@ func MergeIssues(base, local, remote []*beads.Issue) *MergeResult {
localIssue := localMap[id]
remoteIssue := remoteMap[id]
merged, strategy := MergeIssue(baseIssue, localIssue, remoteIssue)
merged, strategy, manualConflicts := MergeIssue(baseIssue, localIssue, remoteIssue)
// Always record strategy (even for deletions, for logging/debugging)
result.Strategy[id] = strategy
// Collect manual conflicts for fields that need user resolution
if len(manualConflicts) > 0 {
result.ManualConflicts = append(result.ManualConflicts, manualConflicts...)
}
if merged != nil {
result.Merged = append(result.Merged, merged)
if strategy == StrategyMerged {
@@ -289,63 +401,64 @@ func MergeIssues(base, local, remote []*beads.Issue) *MergeResult {
// - Deletion handling:
// - local=nil (deleted locally): if remote unchanged from base, delete; else keep remote
// - remote=nil (deleted remotely): if local unchanged from base, delete; else keep local
func MergeIssue(base, local, remote *beads.Issue) (*beads.Issue, string) {
func MergeIssue(base, local, remote *beads.Issue) (*beads.Issue, string, []ManualConflict) {
// Case: no base state (first sync)
if base == nil {
if local == nil && remote == nil {
// Should not happen (would not be in allIDs)
return nil, StrategySame
return nil, StrategySame, nil
}
if local == nil {
return remote, StrategyRemote
return remote, StrategyRemote, nil
}
if remote == nil {
return local, StrategyLocal
return local, StrategyLocal, nil
}
// Both exist with no base: treat as conflict, use field-level merge
// This allows labels/comments to be union-merged even in first sync
return mergeFieldLevel(nil, local, remote), StrategyMerged
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
return merged, StrategyMerged, manualConflicts
}
// Case: local deleted
if local == nil {
// If remote unchanged from base, honor the local deletion
if issueEqual(base, remote) {
return nil, StrategyLocal
return nil, StrategyLocal, nil
}
// Remote changed after local deleted: keep remote (remote wins conflict)
return remote, StrategyMerged
return remote, StrategyMerged, nil
}
// Case: remote deleted
if remote == nil {
// If local unchanged from base, honor the remote deletion
if issueEqual(base, local) {
return nil, StrategyRemote
return nil, StrategyRemote, nil
}
// Local changed after remote deleted: keep local (local wins conflict)
return local, StrategyMerged
return local, StrategyMerged, nil
}
// Standard 3-way cases (all three exist)
if issueEqual(base, local) && issueEqual(base, remote) {
// No changes anywhere
return local, StrategySame
return local, StrategySame, nil
}
if issueEqual(base, local) {
// Only remote changed
return remote, StrategyRemote
return remote, StrategyRemote, nil
}
if issueEqual(base, remote) {
// Only local changed
return local, StrategyLocal
return local, StrategyLocal, nil
}
if issueEqual(local, remote) {
// Both made identical change
return local, StrategySame
return local, StrategySame, nil
}
// True conflict: use field-level merge
@@ -353,7 +466,10 @@ func MergeIssue(base, local, remote *beads.Issue) (*beads.Issue, string) {
// - Labels use union (no data loss)
// - Dependencies use union (no data loss)
// - Comments use append (deduplicated)
return mergeFieldLevel(base, local, remote), StrategyMerged
// - compaction_level uses max (or configured strategy)
// - estimated_minutes uses configured strategy (may flag for manual resolution)
merged, manualConflicts := mergeFieldLevel(base, local, remote)
return merged, StrategyMerged, manualConflicts
}
// issueEqual compares two issues for equality (content-level, not pointer)

View File

@@ -242,7 +242,7 @@ func makeTestIssue(id, title string, status types.Status, priority int, updatedA
func TestMergeIssue_NoBase_LocalOnly(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Issue", types.StatusOpen, 1, time.Now())
merged, strategy := MergeIssue(nil, local, nil)
merged, strategy, _ := MergeIssue(nil, local, nil)
if strategy != StrategyLocal {
t.Errorf("Expected strategy=%s, got %s", StrategyLocal, strategy)
@@ -259,7 +259,7 @@ func TestMergeIssue_NoBase_LocalOnly(t *testing.T) {
func TestMergeIssue_NoBase_RemoteOnly(t *testing.T) {
remote := makeTestIssue("bd-5678", "Remote Issue", types.StatusOpen, 2, time.Now())
merged, strategy := MergeIssue(nil, nil, remote)
merged, strategy, _ := MergeIssue(nil, nil, remote)
if strategy != StrategyRemote {
t.Errorf("Expected strategy=%s, got %s", StrategyRemote, strategy)
@@ -278,7 +278,7 @@ func TestMergeIssue_NoBase_BothExist_LocalNewer(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Title", types.StatusOpen, 1, now.Add(time.Hour))
remote := makeTestIssue("bd-1234", "Remote Title", types.StatusOpen, 2, now)
merged, strategy := MergeIssue(nil, local, remote)
merged, strategy, _ := MergeIssue(nil, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -297,7 +297,7 @@ func TestMergeIssue_NoBase_BothExist_RemoteNewer(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Title", types.StatusOpen, 1, now)
remote := makeTestIssue("bd-1234", "Remote Title", types.StatusOpen, 2, now.Add(time.Hour))
merged, strategy := MergeIssue(nil, local, remote)
merged, strategy, _ := MergeIssue(nil, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -316,7 +316,7 @@ func TestMergeIssue_NoBase_BothExist_SameTime(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Title", types.StatusOpen, 1, now)
remote := makeTestIssue("bd-1234", "Remote Title", types.StatusOpen, 2, now)
merged, strategy := MergeIssue(nil, local, remote)
merged, strategy, _ := MergeIssue(nil, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -337,7 +337,7 @@ func TestMergeIssue_NoChanges(t *testing.T) {
local := makeTestIssue("bd-1234", "Same Title", types.StatusOpen, 1, now)
remote := makeTestIssue("bd-1234", "Same Title", types.StatusOpen, 1, now)
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategySame {
t.Errorf("Expected strategy=%s, got %s", StrategySame, strategy)
@@ -354,7 +354,7 @@ func TestMergeIssue_OnlyLocalChanged(t *testing.T) {
local := makeTestIssue("bd-1234", "Updated Title", types.StatusOpen, 1, now.Add(time.Hour))
remote := makeTestIssue("bd-1234", "Original Title", types.StatusOpen, 1, now)
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyLocal {
t.Errorf("Expected strategy=%s, got %s", StrategyLocal, strategy)
@@ -374,7 +374,7 @@ func TestMergeIssue_OnlyRemoteChanged(t *testing.T) {
local := makeTestIssue("bd-1234", "Original Title", types.StatusOpen, 1, now)
remote := makeTestIssue("bd-1234", "Updated Title", types.StatusOpen, 1, now.Add(time.Hour))
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyRemote {
t.Errorf("Expected strategy=%s, got %s", StrategyRemote, strategy)
@@ -394,7 +394,7 @@ func TestMergeIssue_BothMadeSameChange(t *testing.T) {
local := makeTestIssue("bd-1234", "Same Update", types.StatusClosed, 2, now.Add(time.Hour))
remote := makeTestIssue("bd-1234", "Same Update", types.StatusClosed, 2, now.Add(time.Hour))
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategySame {
t.Errorf("Expected strategy=%s, got %s", StrategySame, strategy)
@@ -414,7 +414,7 @@ func TestMergeIssue_TrueConflict_LocalNewer(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Update", types.StatusInProgress, 1, now.Add(2*time.Hour))
remote := makeTestIssue("bd-1234", "Remote Update", types.StatusClosed, 2, now.Add(time.Hour))
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -438,7 +438,7 @@ func TestMergeIssue_TrueConflict_RemoteNewer(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Update", types.StatusInProgress, 1, now.Add(time.Hour))
remote := makeTestIssue("bd-1234", "Remote Update", types.StatusClosed, 2, now.Add(2*time.Hour))
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -461,7 +461,7 @@ func TestMergeIssue_LocalDeleted_RemoteUnchanged(t *testing.T) {
base := makeTestIssue("bd-1234", "To Delete", types.StatusOpen, 1, now)
remote := makeTestIssue("bd-1234", "To Delete", types.StatusOpen, 1, now)
merged, strategy := MergeIssue(base, nil, remote)
merged, strategy, _ := MergeIssue(base, nil, remote)
if strategy != StrategyLocal {
t.Errorf("Expected strategy=%s (honor local deletion), got %s", StrategyLocal, strategy)
@@ -477,7 +477,7 @@ func TestMergeIssue_LocalDeleted_RemoteChanged(t *testing.T) {
base := makeTestIssue("bd-1234", "Original", types.StatusOpen, 1, now)
remote := makeTestIssue("bd-1234", "Remote Updated", types.StatusClosed, 2, now.Add(time.Hour))
merged, strategy := MergeIssue(base, nil, remote)
merged, strategy, _ := MergeIssue(base, nil, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s (conflict: deleted vs updated), got %s", StrategyMerged, strategy)
@@ -496,7 +496,7 @@ func TestMergeIssue_RemoteDeleted_LocalUnchanged(t *testing.T) {
base := makeTestIssue("bd-1234", "To Delete", types.StatusOpen, 1, now)
local := makeTestIssue("bd-1234", "To Delete", types.StatusOpen, 1, now)
merged, strategy := MergeIssue(base, local, nil)
merged, strategy, _ := MergeIssue(base, local, nil)
if strategy != StrategyRemote {
t.Errorf("Expected strategy=%s (honor remote deletion), got %s", StrategyRemote, strategy)
@@ -512,7 +512,7 @@ func TestMergeIssue_RemoteDeleted_LocalChanged(t *testing.T) {
base := makeTestIssue("bd-1234", "Original", types.StatusOpen, 1, now)
local := makeTestIssue("bd-1234", "Local Updated", types.StatusClosed, 2, now.Add(time.Hour))
merged, strategy := MergeIssue(base, local, nil)
merged, strategy, _ := MergeIssue(base, local, nil)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s (conflict: updated vs deleted), got %s", StrategyMerged, strategy)
@@ -826,7 +826,7 @@ func TestFieldMerge_LWW_LocalNewer(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Update", types.StatusInProgress, 2, now.Add(2*time.Hour))
remote := makeTestIssue("bd-1234", "Remote Update", types.StatusClosed, 3, now.Add(time.Hour))
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -853,7 +853,7 @@ func TestFieldMerge_LWW_RemoteNewer(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Update", types.StatusInProgress, 2, now.Add(time.Hour))
remote := makeTestIssue("bd-1234", "Remote Update", types.StatusClosed, 3, now.Add(2*time.Hour))
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -880,7 +880,7 @@ func TestFieldMerge_LWW_SameTimestamp(t *testing.T) {
local := makeTestIssue("bd-1234", "Local Update", types.StatusInProgress, 2, now)
remote := makeTestIssue("bd-1234", "Remote Update", types.StatusClosed, 3, now)
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -904,7 +904,7 @@ func TestLabelUnion_BothAdd(t *testing.T) {
local := makeTestIssueWithLabels("bd-1234", "Test Local", types.StatusOpen, 1, now.Add(time.Hour), []string{"original", "local-added"})
remote := makeTestIssueWithLabels("bd-1234", "Test Remote", types.StatusOpen, 1, now.Add(2*time.Hour), []string{"original", "remote-added"})
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -939,7 +939,7 @@ func TestLabelUnion_LocalOnly(t *testing.T) {
local := makeTestIssueWithLabels("bd-1234", "Test Local", types.StatusOpen, 1, now.Add(time.Hour), []string{"original", "local-added"})
remote := makeTestIssueWithLabels("bd-1234", "Test Remote", types.StatusOpen, 1, now.Add(2*time.Hour), []string{"original"})
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -962,7 +962,7 @@ func TestLabelUnion_RemoteOnly(t *testing.T) {
local := makeTestIssueWithLabels("bd-1234", "Test Local", types.StatusOpen, 1, now.Add(2*time.Hour), []string{"original"})
remote := makeTestIssueWithLabels("bd-1234", "Test Remote", types.StatusOpen, 1, now.Add(time.Hour), []string{"original", "remote-added"})
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -1001,7 +1001,7 @@ func TestDependencyUnion(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Dependencies = []*types.Dependency{remoteDep}
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -1070,7 +1070,7 @@ func TestCommentAppend(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Comments = []*types.Comment{commonComment, remoteComment}
merged, strategy := MergeIssue(base, local, remote)
merged, strategy, _ := MergeIssue(base, local, remote)
if strategy != StrategyMerged {
t.Errorf("Expected strategy=%s, got %s", StrategyMerged, strategy)
@@ -1103,7 +1103,7 @@ func TestFieldMerge_EdgeCases(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Labels = []string{"remote-label"}
merged, _ := MergeIssue(base, local, remote)
merged, _, _ := MergeIssue(base, local, remote)
if merged == nil {
t.Fatal("Expected merged issue, got nil")
}
@@ -1122,7 +1122,7 @@ func TestFieldMerge_EdgeCases(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Labels = []string{"remote-label"}
merged, _ := MergeIssue(base, local, remote)
merged, _, _ := MergeIssue(base, local, remote)
if merged == nil {
t.Fatal("Expected merged issue, got nil")
}
@@ -1148,7 +1148,7 @@ func TestFieldMerge_EdgeCases(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Dependencies = nil
merged, _ := MergeIssue(base, local, remote)
merged, _, _ := MergeIssue(base, local, remote)
if merged == nil {
t.Fatal("Expected merged issue, got nil")
}
@@ -1175,7 +1175,7 @@ func TestFieldMerge_EdgeCases(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Comments = []*types.Comment{comment}
merged, _ := MergeIssue(base, local, remote)
merged, _, _ := MergeIssue(base, local, remote)
if merged == nil {
t.Fatal("Expected merged issue, got nil")
}
@@ -1211,7 +1211,7 @@ func TestFieldMerge_EdgeCases(t *testing.T) {
remote := makeTestIssue("bd-1234", "Test Remote", types.StatusClosed, 1, now.Add(2*time.Hour))
remote.Dependencies = []*types.Dependency{remoteDep}
merged, _ := MergeIssue(base, local, remote)
merged, _, _ := MergeIssue(base, local, remote)
if merged == nil {
t.Fatal("Expected merged issue, got nil")
}
@@ -1244,7 +1244,7 @@ func TestMergeClockSkewWarning(t *testing.T) {
r, w, _ := os.Pipe()
os.Stderr = w
_, _ = MergeIssue(base, local, remote)
_, _, _ = MergeIssue(base, local, remote)
w.Close()
os.Stderr = oldStderr
@@ -1268,7 +1268,7 @@ func TestMergeClockSkewWarning(t *testing.T) {
r, w, _ := os.Pipe()
os.Stderr = w
_, _ = MergeIssue(base, local, remote)
_, _, _ = MergeIssue(base, local, remote)
w.Close()
os.Stderr = oldStderr
@@ -1295,7 +1295,7 @@ func TestMergeClockSkewWarning(t *testing.T) {
r, w, _ := os.Pipe()
os.Stderr = w
_, _ = MergeIssue(base, local, remote)
_, _, _ = MergeIssue(base, local, remote)
w.Close()
os.Stderr = oldStderr
@@ -1322,7 +1322,7 @@ func TestMergeClockSkewWarning(t *testing.T) {
r, w, _ := os.Pipe()
os.Stderr = w
_, _ = MergeIssue(base, local, remote)
_, _, _ = MergeIssue(base, local, remote)
w.Close()
os.Stderr = oldStderr
@@ -1409,3 +1409,199 @@ func TestMergeLabels(t *testing.T) {
})
}
}
// TestMergeFieldLevel_CompactionLevel tests compaction_level uses max strategy by default
func TestMergeFieldLevel_CompactionLevel(t *testing.T) {
now := time.Now()
t.Run("max_strategy_takes_higher_value", func(t *testing.T) {
// Local has higher compaction_level
local := makeTestIssue("bd-1234", "Local", types.StatusOpen, 1, now.Add(time.Hour))
local.CompactionLevel = 5
remote := makeTestIssue("bd-1234", "Remote", types.StatusOpen, 1, now)
remote.CompactionLevel = 3
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
if merged.CompactionLevel != 5 {
t.Errorf("Expected compaction_level=5 (max), got %d", merged.CompactionLevel)
}
if len(manualConflicts) != 0 {
t.Errorf("Expected no manual conflicts, got %d", len(manualConflicts))
}
})
t.Run("max_strategy_takes_higher_from_remote", func(t *testing.T) {
// Remote has higher compaction_level
local := makeTestIssue("bd-1234", "Local", types.StatusOpen, 1, now.Add(time.Hour))
local.CompactionLevel = 2
remote := makeTestIssue("bd-1234", "Remote", types.StatusOpen, 1, now)
remote.CompactionLevel = 7
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
if merged.CompactionLevel != 7 {
t.Errorf("Expected compaction_level=7 (max), got %d", merged.CompactionLevel)
}
if len(manualConflicts) != 0 {
t.Errorf("Expected no manual conflicts, got %d", len(manualConflicts))
}
})
}
// TestMergeFieldLevel_EstimatedMinutes tests estimated_minutes uses manual strategy by default
func TestMergeFieldLevel_EstimatedMinutes(t *testing.T) {
now := time.Now()
t.Run("manual_strategy_flags_conflict_when_different", func(t *testing.T) {
// Default is manual strategy - should flag conflict when values differ
localMins := 120
remoteMins := 60
local := makeTestIssue("bd-1234", "Local", types.StatusOpen, 1, now.Add(time.Hour))
local.EstimatedMinutes = &localMins
remote := makeTestIssue("bd-1234", "Remote", types.StatusOpen, 1, now)
remote.EstimatedMinutes = &remoteMins
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
// Should keep local value as tentative
if merged.EstimatedMinutes == nil || *merged.EstimatedMinutes != 120 {
t.Errorf("Expected estimated_minutes=120 (local as tentative), got %v", merged.EstimatedMinutes)
}
// Should flag for manual resolution
if len(manualConflicts) != 1 {
t.Errorf("Expected 1 manual conflict, got %d", len(manualConflicts))
} else {
mc := manualConflicts[0]
if mc.Field != "estimated_minutes" {
t.Errorf("Expected field=estimated_minutes, got %s", mc.Field)
}
if mc.LocalValue != 120 {
t.Errorf("Expected LocalValue=120, got %v", mc.LocalValue)
}
if mc.RemoteValue != 60 {
t.Errorf("Expected RemoteValue=60, got %v", mc.RemoteValue)
}
}
})
t.Run("manual_strategy_no_conflict_when_same", func(t *testing.T) {
// No conflict when values are the same
mins := 120
local := makeTestIssue("bd-1234", "Local", types.StatusOpen, 1, now.Add(time.Hour))
local.EstimatedMinutes = &mins
remote := makeTestIssue("bd-1234", "Remote", types.StatusOpen, 1, now)
remoteMins := 120
remote.EstimatedMinutes = &remoteMins
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
if merged.EstimatedMinutes == nil || *merged.EstimatedMinutes != 120 {
t.Errorf("Expected estimated_minutes=120, got %v", merged.EstimatedMinutes)
}
if len(manualConflicts) != 0 {
t.Errorf("Expected no manual conflicts when values match, got %d", len(manualConflicts))
}
})
t.Run("manual_strategy_nil_vs_value_flags_conflict", func(t *testing.T) {
// Conflict when one is nil and other has value
remoteMins := 60
local := makeTestIssue("bd-1234", "Local", types.StatusOpen, 1, now.Add(time.Hour))
local.EstimatedMinutes = nil
remote := makeTestIssue("bd-1234", "Remote", types.StatusOpen, 1, now)
remote.EstimatedMinutes = &remoteMins
merged, manualConflicts := mergeFieldLevel(nil, local, remote)
// Should keep local value (nil) as tentative
if merged.EstimatedMinutes != nil {
t.Errorf("Expected estimated_minutes=nil (local as tentative), got %v", *merged.EstimatedMinutes)
}
// Should flag for manual resolution
if len(manualConflicts) != 1 {
t.Errorf("Expected 1 manual conflict, got %d", len(manualConflicts))
}
})
}
// TestMaxInt tests the maxInt helper function
func TestMaxInt(t *testing.T) {
tests := []struct {
a, b, expected int
}{
{0, 0, 0},
{1, 0, 1},
{0, 1, 1},
{5, 3, 5},
{3, 5, 5},
{-1, -2, -1},
{-2, -1, -1},
}
for _, tc := range tests {
result := maxInt(tc.a, tc.b)
if result != tc.expected {
t.Errorf("maxInt(%d, %d) = %d, expected %d", tc.a, tc.b, result, tc.expected)
}
}
}
// TestMaxIntPtr tests the maxIntPtr helper function
func TestMaxIntPtr(t *testing.T) {
five := 5
three := 3
t.Run("both_nil_returns_nil", func(t *testing.T) {
result := maxIntPtr(nil, nil)
if result != nil {
t.Errorf("Expected nil, got %v", result)
}
})
t.Run("left_nil_returns_right", func(t *testing.T) {
result := maxIntPtr(nil, &three)
if result == nil || *result != 3 {
t.Errorf("Expected 3, got %v", result)
}
})
t.Run("right_nil_returns_left", func(t *testing.T) {
result := maxIntPtr(&five, nil)
if result == nil || *result != 5 {
t.Errorf("Expected 5, got %v", result)
}
})
t.Run("returns_larger_value", func(t *testing.T) {
result := maxIntPtr(&three, &five)
if result == nil || *result != 5 {
t.Errorf("Expected 5, got %v", result)
}
result = maxIntPtr(&five, &three)
if result == nil || *result != 5 {
t.Errorf("Expected 5, got %v", result)
}
})
}
// TestMergeResult_ManualConflicts tests that ManualConflicts is properly initialized
func TestMergeResult_ManualConflicts(t *testing.T) {
now := time.Now()
base := []*types.Issue{
makeTestIssue("bd-1234", "Base", types.StatusOpen, 1, now),
}
local := []*types.Issue{
makeTestIssue("bd-1234", "Local", types.StatusOpen, 1, now.Add(time.Hour)),
}
remote := []*types.Issue{
makeTestIssue("bd-1234", "Remote", types.StatusOpen, 1, now.Add(2*time.Hour)),
}
result := MergeIssues(base, local, remote)
if result.ManualConflicts == nil {
t.Error("ManualConflicts should be initialized, got nil")
}
}