feat: epic close guards, merge re-parenting, and progress display

Prevent closing epics with open children (use --force to override).
Re-parent children to merge target during duplicate merges to prevent
orphaning. Show epic progress (N/M complete) in bd show output.
Normalize related/relates-to dependency types and weight dependents 3×
in merge target selection.

From: https://github.com/steveyegge/beads/pull/2500

Co-Authored-By: matt wilkie <maphew@gmail.com>
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
beads/crew/lizzy 2026-03-10 17:33:00 -07:00 • committed by Steve Yegge
commit 21e23bc571
8 changed files with 219 additions and 22 deletions

View file

@ -113,6 +113,15 @@ create, update, show, or close operation).`,
continue
}
// Epic close guard: prevent closing epics with open children (mw-local-4so.5.2)
if !force && issue != nil && issue.IssueType == types.TypeEpic {
openChildren := countEpicOpenChildren(ctx, id)
if openChildren > 0 {
fmt.Fprintf(os.Stderr, "cannot close epic %s: %d open child issue(s); close children first or use --force to override\n", id, openChildren)
continue
}
}
// Check gate satisfaction for machine-checkable gates (GH#1467)
if !force {
if err := checkGateSatisfaction(issue); err != nil {
@ -396,3 +405,19 @@ func autoCloseCompletedMolecule(ctx context.Context, s *dolt.DoltStore, closedSt
fmt.Printf("%s Auto-closed completed molecule %s\n", ui.RenderPass("✓"), formatFeedbackID(moleculeID, root.Title))
}
}
// countEpicOpenChildren returns the number of open (non-closed) children for an epic.
// Uses GetDependentsWithMetadata to find parent-child relationships.
func countEpicOpenChildren(ctx context.Context, epicID string) int {
dependents, err := store.GetDependentsWithMetadata(ctx, epicID)
if err != nil {
return 0
}
count := 0
for _, dep := range dependents {
if dep.DependencyType == types.DepParentChild && dep.Issue.Status != types.StatusClosed {
count++
}
}
return count
}

View file

@ -112,7 +112,7 @@ Example:
refs := refCounts[issue.ID]
weight := 0
if score, ok := structuralScores[issue.ID]; ok {
weight = score.dependentCount + score.dependsOnCount
weight = score.dependentCount*3 + score.dependsOnCount
}
marker := " "
if issue.ID == target.ID {
@ -246,9 +246,12 @@ func countStructuralRelationships(groups [][]*types.Issue) map[string]*issueScor
// chooseMergeTarget selects the best issue to merge into
// Priority order:
// 1. Highest structural weight (dependents + dependencies) - most connected issue wins
// 2. Highest text reference count (mentions in descriptions/notes)
// 3. Lexicographically smallest ID (stable tiebreaker)
// 1. Highest structural weight - most connected issue wins
// Dependents (children) are weighted 3× more than depends-on references
// because discarding an issue with children orphans them (catastrophic),
// while losing a depends-on link is recoverable.
// 2. Highest text reference count (mentions in descriptions/notes)
// 3. Lexicographically smallest ID (stable tiebreaker)
func chooseMergeTarget(group []*types.Issue, refCounts map[string]int, structuralScores map[string]*issueScore) *types.Issue {
if len(group) == 0 {
return nil
@ -257,9 +260,9 @@ func chooseMergeTarget(group []*types.Issue, refCounts map[string]int, structura
getScore := func(id string) (int, int) {
weight := 0
if score, ok := structuralScores[id]; ok {
// Weight = children/dependents + dependencies
// An issue with ANY structural connections should be preferred over an empty shell
weight = score.dependentCount + score.dependsOnCount
// Dependents (children that would be orphaned) count 3× more than
// depends-on references (which survive closure as links).
weight = score.dependentCount*3 + score.dependsOnCount
}
textRefs := refCounts[id]
return weight, textRefs
@ -321,7 +324,7 @@ func formatDuplicateGroupsJSON(groups [][]*types.Issue, refCounts map[string]int
"references": refCounts[issue.ID],
"dependents": dependents,
"dependencies": dependencies,
"weight": dependents + dependencies,
"weight": dependents*3 + dependencies,
"is_merge_target": issue.ID == target.ID,
}
}
@ -344,24 +347,55 @@ func formatDuplicateGroupsJSON(groups [][]*types.Issue, refCounts map[string]int
}
// performMerge executes the merge operation:
// 1. Closes all source issues with a reason indicating they are duplicates
// 2. Links each source to the target with a "related" dependency
// 1. Re-parents children of source issues to the target (prevents orphaning)
// 2. Closes all source issues with a reason indicating they are duplicates
// 3. Links each source to the target with a "related" dependency
// Returns a map with the merge result for JSON output
func performMerge(targetID string, sourceIDs []string) map[string]interface{} {
ctx := rootCtx
result := map[string]interface{}{
"target": targetID,
"sources": sourceIDs,
"closed": []string{},
"linked": []string{},
"errors": []string{},
"target": targetID,
"sources": sourceIDs,
"closed": []string{},
"linked": []string{},
"reparented": []string{},
"errors": []string{},
}
closedIDs := []string{}
linkedIDs := []string{}
reparentedIDs := []string{}
errors := []string{}
for _, sourceID := range sourceIDs {
// Re-parent children before closing to prevent orphaning.
// Get dependents with metadata to find parent-child relationships.
dependents, err := store.GetDependentsWithMetadata(ctx, sourceID)
if err == nil {
for _, dep := range dependents {
if dep.DependencyType != types.DepParentChild {
continue
}
childID := dep.Issue.ID
// Remove old parent-child link
if err := store.RemoveDependency(ctx, childID, sourceID, getActor()); err != nil {
errors = append(errors, fmt.Sprintf("failed to remove parent link %s→%s: %v", childID, sourceID, err))
continue
}
// Add new parent-child link to target
newDep := &types.Dependency{
IssueID: childID,
DependsOnID: targetID,
Type: types.DepParentChild,
}
if err := store.AddDependency(ctx, newDep, getActor()); err != nil {
errors = append(errors, fmt.Sprintf("failed to reparent %s to %s: %v", childID, targetID, err))
continue
}
reparentedIDs = append(reparentedIDs, childID)
}
}
// Close the duplicate issue
reason := fmt.Sprintf("Duplicate of %s", targetID)
if err := store.CloseIssue(ctx, sourceID, reason, actor, ""); err != nil {
@ -376,7 +410,7 @@ func performMerge(targetID string, sourceIDs []string) map[string]interface{} {
DependsOnID: targetID,
Type: types.DependencyType("related"),
}
if err := store.AddDependency(ctx, dep, actor); err != nil {
if err := store.AddDependency(ctx, dep, getActor()); err != nil {
errors = append(errors, fmt.Sprintf("failed to link %s to %s: %v", sourceID, targetID, err))
continue
}
@ -385,6 +419,7 @@ func performMerge(targetID string, sourceIDs []string) map[string]interface{} {
result["closed"] = closedIDs
result["linked"] = linkedIDs
result["reparented"] = reparentedIDs
result["errors"] = errors
return result

View file

@ -182,20 +182,36 @@ func TestChooseMergeTarget(t *testing.T) {
wantID: "bd-1", // Issue with dependencies should be kept over empty shell
},
{
name: "weight combines dependents and dependencies (GH#1022)",
name: "dependents weighted 3x more than depends-on (anti-orphan)",
group: []*types.Issue{
{ID: "bd-1", Title: "Task"}, // Has only dependents (children)
{ID: "bd-2", Title: "Task"}, // Has both dependents and dependencies
{ID: "bd-2", Title: "Task"}, // Has more depends-on but fewer children
},
refCounts: map[string]int{
"bd-1": 0,
"bd-2": 0,
},
structuralScores: map[string]*issueScore{
"bd-1": {dependentCount: 5, dependsOnCount: 0, textRefs: 0}, // Weight = 5
"bd-2": {dependentCount: 3, dependsOnCount: 4, textRefs: 0}, // Weight = 7
"bd-1": {dependentCount: 5, dependsOnCount: 0, textRefs: 0}, // Weight = 5*3 = 15
"bd-2": {dependentCount: 3, dependsOnCount: 4, textRefs: 0}, // Weight = 3*3+4 = 13
},
wantID: "bd-2", // Higher combined weight wins
wantID: "bd-1", // More children wins (anti-orphan weighting)
},
{
name: "depends-on still contributes when dependents are equal",
group: []*types.Issue{
{ID: "bd-1", Title: "Task"},
{ID: "bd-2", Title: "Task"},
},
refCounts: map[string]int{
"bd-1": 0,
"bd-2": 0,
},
structuralScores: map[string]*issueScore{
"bd-1": {dependentCount: 2, dependsOnCount: 0, textRefs: 0}, // Weight = 2*3 = 6
"bd-2": {dependentCount: 2, dependsOnCount: 3, textRefs: 0}, // Weight = 2*3+3 = 9
},
wantID: "bd-2", // Equal dependents, more deps wins
},
}

View file

@ -153,6 +153,26 @@ var showCmd = &cobra.Command{
details.Dependents, _ = issueStore.GetDependentsWithMetadata(ctx, issue.ID) // Best effort: show issue even if dependents unavailable
details.Comments, _ = issueStore.GetIssueComments(ctx, issue.ID) // Best effort: show issue even if comments unavailable
// Epic progress: count children status for epic issues
if issue.IssueType == types.TypeEpic && details.Dependents != nil {
total, closed := 0, 0
for _, dep := range details.Dependents {
if dep.DependencyType == types.DepParentChild {
total++
if dep.Issue.Status == types.StatusClosed {
closed++
}
}
}
if total > 0 {
details.EpicTotalChildren = &total
details.EpicClosedChildren = &closed
closeable := total == closed
details.EpicCloseable = &closeable
}
}
// Compute parent from dependencies
for _, dep := range details.Dependencies {
if dep.DependencyType == types.DepParentChild {
@ -291,6 +311,24 @@ var showCmd = &cobra.Command{
for _, dep := range children {
fmt.Println(formatDependencyLine("↳", dep))
}
// Epic progress summary
if issue.IssueType == types.TypeEpic {
closedCount := 0
for _, dep := range children {
if dep.Issue.Status == types.StatusClosed {
closedCount++
}
}
pct := 0
if len(children) > 0 {
pct = (closedCount * 100) / len(children)
}
if closedCount == len(children) {
fmt.Printf(" %s %d/%d complete (%d%%) — eligible for close\n", ui.RenderPass("✓"), closedCount, len(children), pct)
} else {
fmt.Printf(" %s %d/%d complete (%d%%)\n", ui.RenderMuted("◐"), closedCount, len(children), pct)
}
}
}
if len(blocks) > 0 {
fmt.Printf("\n%s\n", ui.RenderBold("BLOCKS"))

View file

@ -102,7 +102,12 @@ func (s *DoltStore) SearchIssues(ctx context.Context, query string, filter types
return doltResults, nil
}
// GetReadyWork returns issues that are ready to work on (not blocked)
// GetReadyWork returns issues that are ready to work on (not blocked).
//
// Blocking semantics are unified through computeBlockedIDs, which is the
// canonical source of truth for both GetReadyWork and GetBlockedIssues.
// The molecule subgraph analysis (analyzeMoleculeParallel) uses equivalent
// logic scoped to an in-memory subgraph rather than the full database.
func (s *DoltStore) GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error) {
s.mu.RLock()
defer s.mu.RUnlock()

View file

@ -665,6 +665,11 @@ type IssueDetails struct {
Dependents []*IssueWithDependencyMetadata `json:"dependents,omitempty"`
Comments []*Comment `json:"comments,omitempty"`
Parent *string `json:"parent,omitempty"`
// Epic progress fields (populated only for issue_type=epic with children)
EpicTotalChildren *int `json:"epic_total_children,omitempty"`
EpicClosedChildren *int `json:"epic_closed_children,omitempty"`
EpicCloseable *bool `json:"epic_closeable,omitempty"`
}
// DependencyType categorizes the relationship

View file

@ -117,6 +117,24 @@ func HasType(allowed ...types.IssueType) IssueValidator {
}
}
// EpicHasOpenChildren validates that an epic does not have open children.
// If the issue is an epic with open children, returns an error unless force is true.
// Non-epic issues pass through without validation.
func EpicHasOpenChildren(force bool, openChildCount int) IssueValidator {
return func(id string, issue *types.Issue) error {
if issue == nil || force {
return nil
}
if issue.IssueType != types.TypeEpic {
return nil
}
if openChildCount > 0 {
return fmt.Errorf("epic %s has %d open child issue(s); close children first or use --force to override", id, openChildCount)
}
return nil
}
}
// forUpdate returns a validator chain for update operations.
// Validates: issue exists and is not a template.
func forUpdate() IssueValidator {

View file

@ -284,6 +284,61 @@ func TestHasType(t *testing.T) {
}
}
func TestEpicHasOpenChildren(t *testing.T) {
tests := []struct {
name string
issue *types.Issue
force bool
openChildCount int
wantErr bool
}{
{
name: "nil issue passes",
issue: nil,
force: false,
openChildCount: 5,
wantErr: false,
},
{
name: "non-epic passes regardless of children",
issue: &types.Issue{ID: "bd-test", IssueType: types.TypeTask},
force: false,
openChildCount: 10,
wantErr: false,
},
{
name: "epic with no open children passes",
issue: &types.Issue{ID: "bd-test", IssueType: types.TypeEpic},
force: false,
openChildCount: 0,
wantErr: false,
},
{
name: "epic with open children fails",
issue: &types.Issue{ID: "bd-test", IssueType: types.TypeEpic},
force: false,
openChildCount: 3,
wantErr: true,
},
{
name: "epic with open children passes with force",
issue: &types.Issue{ID: "bd-test", IssueType: types.TypeEpic},
force: true,
openChildCount: 3,
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := EpicHasOpenChildren(tt.force, tt.openChildCount)("bd-test", tt.issue)
if (err != nil) != tt.wantErr {
t.Errorf("EpicHasOpenChildren() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
func TestForUpdate(t *testing.T) {
tests := []struct {
name string