fix(epic): do not treat duplicate/wontfix closes as complete (#5138)

* fix(epic): do not treat duplicate/wontfix closes as complete

GetEpicsEligibleForClosure counted any closed child as complete work.
An epic whose only child was closed as duplicate (or wontfix/superseded)
was flagged "complete-but-unclosed" and doctor suggested bd close — even
when the epic still had unfinished scope (GH#5026).

- Fetch close_reason with status; only completing closes count for eligibility
- IsNonCompletingClose for duplicate/wontfix/superseded/obsolete keywords
- Soften doctor/mol stale copy: review scope before closing

Fixes #5026

* fix(epic): word-boundary close-reason matching + conformance coverage (GH#5026)

Review follow-ups from maphew on #5138:

- IsNonCompletingClose now matches close_reason on word boundaries via a
  precompiled regexp instead of raw strings.Contains. Bare "dup" is dropped
  (redundant with duplicate/dupe, only added false positives on "dedup").
  Bare "obsolete" is dropped in favor of "obsoleted" — "removed obsolete
  migration shim" is completing work, not a redirect, and was silently
  making such epics ineligible forever with no explanation.
- testAuditEpicsEligiblePartial (conformance, runs on every backend) gains
  an ee-4 epic whose only child closes with reason "duplicate of ee-1",
  asserting {Total:1 Closed:1 Eligible:false} — the dcr-tf2 regression from
  #5026 end to end. Its doc comment now states the invariant this PR
  actually enforces (Total == completing-closed), not the one it broke.
- cmd/bd/info.go and cmd/bd/doctor/maintenance.go no longer advertise the
  retired "complete-but-unclosed" framing.

Generated CLI docs (docs/CLI_REFERENCE.md, docs/cli-reference/) are left
untouched: docs/cli-docs.pin freezes them to the released v1.1.0 tag, so
regenerating with the pinned build (matching CI's check-doc-flags job) is
a no-op regardless of source changes on this branch, and overriding the
pin pulls in ~100 files of unrelated accumulated drift. Verified via
scripts/check-doc-flags.sh against a CI-equivalent CGO_ENABLED=0 build.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015AfaSMkMRF5BTzuPNFnqHY

* fix(epic): match hyphenated wont-fix and curly-apostrophe won't fix (GH#5138)

Maintainer review on GH#5138 found the close-reason regexp missed two
forms of the already-handled wontfix keyword: a hyphen between "wont"
and "fix" (the ` ?` quantifier only tolerates a space, not a hyphen),
and "won't fix" written with the U+2019 typographic right single
quote instead of the ASCII apostrophe.

Extend the regex directly rather than normalizing the whole
close-reason string: `wont[- ]?fix` accepts a hyphen, a space, or
neither, and `won['\x{2019}]t fix` accepts either apostrophe form.
Scoping the hyphen tolerance to just this keyword pair (rather than
folding all hyphens to spaces) avoids the risk of turning unrelated
hyphenated prose into a false match.

Adds table cases for both forms plus a negative case confirming
ordinary hyphenated prose ("not-yet-planned") still doesn't match.

* style: gofmt maintenance.go after comment split the struct alignment

The GH#5026 wording comment inside the DoctorCheck literal splits gofmt's
alignment group, so Name/Status align independently of Message. CI's
"Check gofmt" caught this on the rebase; main's copy is clean, so the
violation is ours.

Whitespace only: `git diff -w` is empty.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(epic): compose wont-fix separators, sync epic_closeable classifier (GH#5138 review)

bee-ghosttrack's desk review on PR #5138 raised two asks:

1. The hyphen and curly-apostrophe fixes didn't compose: "won't-fix" and
   "won't-fix" (curly quote) still matched as completing. The apostrophe
   alternative in nonCompletingCloseRegexp required a literal space after
   "fix"; give it the same [- ]? hyphen tolerance the plain "wont[- ]?fix"
   alternative already had.

2. epic_closeable (internal/workapi/detail.go) computed closeable as raw
   total==closed, disagreeing with issueops.GetEpicsEligibleForClosureInTx's
   real classifier — an epic whose only child closed "duplicate of X" read
   epic_closeable=true in `bd show --json`. Moved IsNonCompletingClose from
   issueops into the leaf internal/types package (issueops already imports
   workapi, so workapi importing issueops back would cycle) and had
   applyEpicProgress apply the same classifier. That also surfaced a second
   bug on the way: shallowDep, which every dependent row passes through
   before applyEpicProgress ever sees it, was dropping CloseReason along
   with the other free-form text fields — so the classifier was reading an
   always-empty string. Fixed by keeping CloseReason (short, not a hub-scale
   blob) in the shallow copy.

Regression test in workapi added and verified to fail without the
shallowDep fix and pass with it (both outputs recorded in review).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(epic): apply the eligibility classifier to bd show and doctor --deep (#5138 review)

Review iteration 1 (synthesis: request_changes, 1 major + 1 nit).

Major (Change Impact / Blast Radius) — two surfaces still computed epic
closeability from their own raw closed counts, so after this PR they
contradicted the eight sites that read the shared EpicStatus.EligibleForClose:

- cmd/bd/show_format.go: printEpicChildProgress gates only the
  "— eligible for close" suffix on types.IsNonCompletingClose. The
  closed/total figure stays raw, matching the deliberate raw ClosedChildren
  convention pinned by the conformance test.
- cmd/bd/doctor/deep.go: checkEpicCompleteness routes through
  issueops.GetEpicsEligibleForClosureInTx instead of its own SQL, so one
  classifier remains and `bd doctor --deep` agrees with `bd doctor`'s Stale
  Molecules check by construction. Side effects, both improvements: the local
  LIMIT 20 is gone (the reported count is now exact), and the shared query's
  isTableNotExistError tolerance replaces a LEFT JOIN that required the
  optional wisps/wisp_dependencies tables unconditionally.
- cmd/bd/doctor.go: the --deep help text no longer says "all children closed".

Nit (Behavioral Correctness) — internal/types/non_completing_close.go spells
the keyword "not[- ]?planned", giving it the same per-keyword separator
tolerance the "wont fix" pair already had. The comment no longer rests the
space-only spelling on the "not-yet-planned" counterexample, which an
intervening word blocks under either spelling.

Bazel: gazelle had never been run for this PR's new files, so //internal/types
omitted non_completing_close.go and the Bazel build failed with
"internal/workapi/detail.go:275: undefined: types.IsNonCompletingClose".
`bazel run //:gazelle` adds those rows and the new cmd/bd test src.

Tests (each new pin mutation-proved: reverting the fix reds exactly the
intended case and nothing else):
- cmd/bd/show_format_test.go (new): first coverage for printEpicChildProgress;
  asserts both halves — raw progress preserved, suffix gated.
- cmd/bd/doctor/deep_test.go: a duplicate-closed-child epic is not reported
  ready to close and ships no `bd close` Fix line; the three pre-existing
  cases pass unchanged.
- internal/types/non_completing_close_test.go: "not-planned"/"notplanned"
  classify as non-completing; "not-yet-planned" still does not.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Gas City Adopt-PR <adopt-pr@gascity.local>
This commit is contained in:
Vishnu J 2026-10-01 05:19:33 -07:00 • committed by GitHub
commit b0c3c8f497
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 422 additions and 72 deletions

View file

@ -653,7 +653,9 @@ func testAuditStaleStatusOverride(t *testing.T, f Factory) {
}
// Epics with ZERO children are silently skipped; epics WITH children are returned
// with Total/Closed counts and EligibleForClose = (Total>0 && Total==Closed).
// with Total/Closed counts and EligibleForClose = (Total == completing-closed).
// A child closed for a non-completing reason (duplicate/wontfix/superseded/…)
// counts toward Closed but not toward eligibility (GH#5026).
func testAuditEpicsEligiblePartial(t *testing.T, f Factory) {
s := f(t)
c := ctx()
@ -663,9 +665,12 @@ func testAuditEpicsEligiblePartial(t *testing.T, f Factory) {
must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "ee-2", Title: "E2", IssueType: types.TypeEpic, Status: types.StatusOpen}), "a"))
must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "ee-2a", Title: "c", Status: types.StatusClosed}), "a"))
must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "ee-3", Title: "E3", IssueType: types.TypeEpic, Status: types.StatusOpen}), "a"))
must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "ee-4", Title: "E4", IssueType: types.TypeEpic, Status: types.StatusOpen}), "a"))
must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "ee-4a", Title: "c", Status: types.StatusClosed, CloseReason: "duplicate of ee-1"}), "a"))
must(t, s.AddDependency(c, &types.Dependency{IssueID: "ee-1a", DependsOnID: "ee-1", Type: types.DepParentChild}, "a"))
must(t, s.AddDependency(c, &types.Dependency{IssueID: "ee-1b", DependsOnID: "ee-1", Type: types.DepParentChild}, "a"))
must(t, s.AddDependency(c, &types.Dependency{IssueID: "ee-2a", DependsOnID: "ee-2", Type: types.DepParentChild}, "a"))
must(t, s.AddDependency(c, &types.Dependency{IssueID: "ee-4a", DependsOnID: "ee-4", Type: types.DepParentChild}, "a"))
epics, err := s.GetEpicsEligibleForClosure(c)
must(t, err)
@ -695,6 +700,17 @@ func testAuditEpicsEligiblePartial(t *testing.T, f Factory) {
if _, present := byID["ee-3"]; present {
t.Error("ee-3 (zero children) must be ABSENT (silent skip)")
}
// dcr-tf2 / GH#5026: a single child closed as a duplicate still counts as
// Closed (raw close count), but must NOT count toward EligibleForClose —
// the epic's real scope is unfinished, not done.
e4 := byID["ee-4"]
if e4 == nil {
t.Fatal("ee-4 missing (has children, must be returned)")
}
if e4.TotalChildren != 1 || e4.ClosedChildren != 1 || e4.EligibleForClose {
t.Errorf("ee-4 = {Total:%d Closed:%d Eligible:%v}, want {1 1 false} (duplicate close is non-completing)", e4.TotalChildren, e4.ClosedChildren, e4.EligibleForClose)
}
}
// GetIssuesByLabel unions wisp_labels: an ephemeral (wisp) issue sharing the label

View file

@ -1090,6 +1090,7 @@ go_test(
"show_details_json_test.go",
"show_embedded_test.go",
"show_format_metadata_test.go",
"show_format_test.go",
"show_not_found_hint_test.go",
"show_proxied_integration_test.go",
"show_proxied_reader_test.go",

View file

@ -122,7 +122,8 @@ Deep Validation Mode (--deep):
Additional checks:
- Parent consistency: All parent-child deps point to existing issues
- Dependency integrity: All deps reference valid issues
- Epic completeness: Find epics ready to close (all children closed)
- Epic completeness: Find epics ready to close (all children closed as
completed work; duplicate/wontfix/superseded closes do not count)
- Agent bead integrity: Agent beads have valid state values
- Mail thread integrity: Thread IDs reference existing issues
- Molecule integrity: Molecules have valid parent-child structures

View file

@ -2,6 +2,7 @@
package doctor
import (
"context"
"database/sql"
"encoding/json"
"fmt"
@ -9,6 +10,7 @@ import (
"strings"
"github.com/steveyegge/beads/internal/configfile"
"github.com/steveyegge/beads/internal/storage/issueops"
)
// DeepValidationResult holds all deep validation check results
@ -240,52 +242,38 @@ func checkDependencyIntegrity(db *sql.DB) DoctorCheck {
return check
}
// checkEpicCompleteness finds epics that could be closed (all children closed)
// checkEpicCompleteness finds epics that could be closed (all children closed
// as completed work).
//
// This routes through the shared eligibility query rather than re-deriving
// "all children closed" from raw counts in local SQL. A child closed as
// duplicate/wontfix/superseded redirects the work rather than finishing it and
// must not make its epic look closeable (GH#5026); a second local classifier
// here would let `bd doctor --deep` report an epic "ready to close" — with a
// Fix line prescribing `bd close` — while `bd doctor`'s own Stale Molecules
// check, which reads EpicStatus.EligibleForClose, reports the same epic on the
// same repository as not stale.
func checkEpicCompleteness(db *sql.DB) DoctorCheck {
check := DoctorCheck{
Name: "Epic Completeness",
Category: CategoryMetadata,
}
// Find epics where all children are closed but epic is still open
//nolint:gosec // G202: doctorDependencyUnionSQL returns a fixed internal SELECT fragment.
query := `
SELECT e.id, e.title,
COUNT(COALESCE(c.id, cw.id)) as total_children,
SUM(CASE WHEN COALESCE(c.status, cw.status) = 'closed' THEN 1 ELSE 0 END) as closed_children
FROM issues e
JOIN (` + doctorDependencyUnionSQL() + `) d ON d.depends_on_id = e.id AND d.type = 'parent-child'
LEFT JOIN issues c ON c.id = d.issue_id
LEFT JOIN wisps cw ON cw.id = d.issue_id
WHERE e.issue_type = 'epic'
AND e.status != 'closed'
AND COALESCE(c.id, cw.id) IS NOT NULL
GROUP BY e.id
HAVING total_children > 0 AND total_children = closed_children
LIMIT 20`
rows, err := db.Query(query)
epicStatuses, err := issueops.GetEpicsEligibleForClosureInTx(context.Background(), db)
if err != nil {
check.Status = StatusWarning
check.Message = "Unable to check epic completeness"
check.Detail = err.Error()
return check
}
defer rows.Close()
var completedEpics []string
for rows.Next() {
var id, title string
var total, closed int
if err := rows.Scan(&id, &title, &total, &closed); err == nil {
completedEpics = append(completedEpics, fmt.Sprintf("%s (%d/%d)", id, closed, total))
for _, es := range epicStatuses {
if !es.EligibleForClose || es.Epic == nil {
continue
}
}
if err := rows.Err(); err != nil {
check.Status = StatusWarning
check.Message = "Row iteration error checking epic completeness"
check.Detail = err.Error()
return check
completedEpics = append(completedEpics,
fmt.Sprintf("%s (%d/%d)", es.Epic.ID, es.ClosedChildren, es.TotalChildren))
}
if len(completedEpics) == 0 {

View file

@ -247,6 +247,63 @@ func TestCheckEpicCompleteness_OpenWispChildPreventsCompletedEpic(t *testing.T)
}
}
// TestCheckEpicCompleteness_DuplicateClosedChildIsNotReady pins GH#5026 on the
// deep check. The child is closed, so the three cases above (which all close
// their children with an empty reason) still pass unchanged — but a close that
// redirects the work rather than finishing it leaves the epic's real scope
// undone, so the epic must not be reported ready to close and the check must
// not ship its `bd close <epic-id>` Fix line for it. Before this, `bd doctor
// --deep` said "ready to close" while `bd doctor`'s Stale Molecules check,
// reading the shared EpicStatus.EligibleForClose, said the same epic on the
// same repository was not stale.
func TestCheckEpicCompleteness_DuplicateClosedChildIsNotReady(t *testing.T) {
store := newTestDoltStore(t, "epic")
ctx := context.Background()
epic := &types.Issue{
ID: "epic-dup",
Title: "Epic",
Status: types.StatusOpen,
IssueType: types.TypeEpic,
CreatedAt: time.Now(),
}
if err := store.CreateIssue(ctx, epic, "test"); err != nil {
t.Fatal(err)
}
child := &types.Issue{
ID: "epic-dup.1",
Title: "Duplicate-closed child",
Status: types.StatusClosed,
IssueType: types.TypeTask,
ClosedAt: ptrTime(time.Now()),
CloseReason: "duplicate of epic-1.1",
CreatedAt: time.Now(),
}
if err := store.CreateIssue(ctx, child, "test"); err != nil {
t.Fatal(err)
}
dep := &types.Dependency{
IssueID: child.ID,
DependsOnID: epic.ID,
Type: types.DepParentChild,
CreatedAt: time.Now(),
CreatedBy: "test",
}
if err := store.AddDependency(ctx, dep, "test"); err != nil {
t.Fatal(err)
}
check := checkEpicCompleteness(store.UnderlyingDB())
if check.Status != StatusOK {
t.Errorf("Status = %q, want %q; message=%q detail=%q", check.Status, StatusOK, check.Message, check.Detail)
}
if strings.Contains(check.Fix, "bd close") {
t.Errorf("Fix = %q, want no 'bd close' instruction for a duplicate-closed epic", check.Fix)
}
}
// TestCheckMailThreadIntegrity_ValidThreads verifies valid thread references pass
func TestCheckMailThreadIntegrity_ValidThreads(t *testing.T) {
store := newTestDoltStore(t, "thread")

View file

@ -126,8 +126,10 @@ func checkStaleClosedIssuesDB(db *sql.DB, thresholdDays int) DoctorCheck {
}
}
// CheckStaleMolecules detects complete-but-unclosed molecules.
// A molecule is stale if all children are closed but the root is still open.
// CheckStaleMolecules detects molecules whose children are all closed but
// whose root issue is still open. Closes on children that redirect or
// abandon the work (duplicate/wontfix/superseded/…) do not count as
// completing, so a molecule with such a close is not reported here (GH#5026).
func CheckStaleMolecules(path string) DoctorCheck {
_, beadsDir := getBackendAndBeadsDir(path)
@ -183,11 +185,13 @@ func CheckStaleMolecules(path string) DoctorCheck {
}
return DoctorCheck{
Name: "Stale Molecules",
Status: StatusWarning,
Message: fmt.Sprintf("%d complete-but-unclosed molecule(s)", staleCount),
Name: "Stale Molecules",
Status: StatusWarning,
// Wording: all children closed with completing reasons — still review
// before close (scope may exceed the child set). GH#5026.
Message: fmt.Sprintf("%d molecule(s) with all children closed (review scope before closing)", staleCount),
Detail: detail,
Fix: "Run 'bd mol stale' to review, then 'bd close <id>' for each",
Fix: "Run 'bd mol stale' to review whether epic scope is actually done, then 'bd close <id>' if so",
Category: CategoryMaintenance,
}
}

View file

@ -1117,7 +1117,7 @@ var versionChanges = []VersionChange{
"NEW: Aspect composition - Cross-cutting concerns via aspects field in formulas",
"NEW: Runtime expansion - on_complete and for-each dynamic step generation",
"NEW: bd formula list/show - Discover and inspect available formulas",
"NEW: bd mol stale - Detect complete-but-unclosed molecules",
"NEW: bd mol stale - Detect molecules with all children closed but root still open",
"NEW: Stale molecules check in bd doctor - Proactive detection",
"NEW: Distinct ID prefixes - bd-proto-xxx, bd-mol-xxx, bd-wisp-xxx",
"NEW: no-git-ops config - bd config set no-git-ops true for manual git control",

View file

@ -12,16 +12,18 @@ import (
var molStaleCmd = &cobra.Command{
Use: "stale",
Short: "Detect complete-but-unclosed molecules",
Long: `Detect molecules (epics with children) that are complete but still open.
Short: "Detect molecules with all children closed but root still open",
Long: `Detect molecules (epics with children) whose children are all closed
with completing reasons, but the root is still open.
A molecule is considered stale if:
1. All children are closed (Completed == Total)
1. Every child is closed with a completing reason (not duplicate/wontfix/superseded)
2. Root issue is still open
3. Not assigned to anyone (optional, use --unassigned)
4. Is blocking other work (optional, use --blocking)
By default, shows all complete-but-unclosed molecules.
Review whether epic scope is actually finished before closing — child
closure alone does not prove the epic's stated work is done (GH#5026).
Examples:
bd mol stale # List all stale molecules
@ -96,10 +98,10 @@ func renderStaleResult(result *StaleResult, blockingOnly bool) {
}
if blockingOnly {
fmt.Printf("%s Stale molecules (complete but unclosed, blocking work):\n\n",
fmt.Printf("%s Molecules with all children closed (review scope; blocking work):\n\n",
ui.RenderWarnIcon())
} else {
fmt.Printf("%s Stale molecules (complete but unclosed):\n\n",
fmt.Printf("%s Molecules with all children closed (review scope before closing):\n\n",
ui.RenderInfoIcon())
}

View file

@ -278,22 +278,40 @@ func printRelatedSection(relatedSeen map[string]*types.IssueWithDependencyMetada
// printEpicChildProgress summarizes how much of an epic its children have
// finished, printed under the CHILDREN section.
//
// The closed/total progress figure stays raw, mirroring the deliberate raw
// EpicStatus.ClosedChildren convention, but "eligible for close" is a
// closeability verdict and must apply the same rule the rest of the tool
// applies: a child closed as duplicate/wontfix/superseded redirects the work
// instead of finishing it, so it cannot make an epic closeable (GH#5026).
// Deciding that here from a raw closed count would make `bd show` contradict
// `bd epic`, `bd doctor` and `epic_closeable`, which all read the shared
// EpicStatus.EligibleForClose computed by GetEpicsEligibleForClosureInTx.
func printEpicChildProgress(children []*types.IssueWithDependencyMetadata) {
if len(children) == 0 {
return
}
closed := 0
completing := 0
for _, dep := range children {
if dep.Status == types.StatusClosed {
closed++
if dep.Status != types.StatusClosed {
continue
}
closed++
if !types.IsNonCompletingClose(dep.CloseReason) {
completing++
}
}
pct := closed * 100 / len(children)
icon := ui.RenderMuted("◐")
if closed == len(children) {
fmt.Printf(" %s %d/%d complete (%d%%) — eligible for close\n", ui.RenderPass("✓"), closed, len(children), pct)
} else {
fmt.Printf(" %s %d/%d complete (%d%%)\n", ui.RenderMuted("◐"), closed, len(children), pct)
icon = ui.RenderPass("✓")
}
eligible := ""
if completing == len(children) {
eligible = " — eligible for close"
}
fmt.Printf(" %s %d/%d complete (%d%%)%s\n", icon, closed, len(children), pct, eligible)
}
// formatSimpleDependencyLine formats a dependency without metadata (fallback)

View file

@ -0,0 +1,83 @@
package main
import (
"strings"
"testing"
"github.com/steveyegge/beads/internal/types"
)
// epicChildRow builds one CHILDREN-section row for printEpicChildProgress.
func epicChildRow(id string, status types.Status, closeReason string) *types.IssueWithDependencyMetadata {
return &types.IssueWithDependencyMetadata{
Issue: types.Issue{
ID: id,
Title: id,
Status: status,
CloseReason: closeReason,
},
DependencyType: types.DepParentChild,
}
}
// TestPrintEpicChildProgressEligibility pins GH#5026 on `bd show <epic>`, the
// CHILDREN-section progress line. Two halves are asserted together on purpose:
// the closed/total figure stays RAW (mirroring the deliberate raw
// EpicStatus.ClosedChildren convention that the conformance test pins), while
// the "eligible for close" suffix is a closeability verdict and applies the
// same non-completing-close rule as EpicStatus.EligibleForClose. Gating the
// whole line, or gating nothing, each fails exactly one half.
func TestPrintEpicChildProgressEligibility(t *testing.T) {
tests := []struct {
name string
children []*types.IssueWithDependencyMetadata
wantProgress string
wantEligible bool
}{
{
name: "sole child closed as completed work",
children: []*types.IssueWithDependencyMetadata{epicChildRow("c-1", types.StatusClosed, "")},
wantProgress: "1/1 complete (100%)",
wantEligible: true,
},
{
name: "sole child closed as a duplicate",
children: []*types.IssueWithDependencyMetadata{epicChildRow("c-1", types.StatusClosed, "duplicate of c-9")},
wantProgress: "1/1 complete (100%)",
wantEligible: false,
},
{
name: "one completing close alongside a wont-fix close",
children: []*types.IssueWithDependencyMetadata{
epicChildRow("c-1", types.StatusClosed, "fixed"),
epicChildRow("c-2", types.StatusClosed, "wont-fix"),
},
wantProgress: "2/2 complete (100%)",
wantEligible: false,
},
{
name: "an open child keeps the epic ineligible",
children: []*types.IssueWithDependencyMetadata{
epicChildRow("c-1", types.StatusClosed, ""),
epicChildRow("c-2", types.StatusOpen, ""),
},
wantProgress: "1/2 complete (50%)",
wantEligible: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
out := captureStdout(t, func() error {
printEpicChildProgress(tt.children)
return nil
})
if !strings.Contains(out, tt.wantProgress) {
t.Errorf("output %q does not contain raw progress %q", out, tt.wantProgress)
}
if got := strings.Contains(out, "eligible for close"); got != tt.wantEligible {
t.Errorf("output %q: %q present = %v, want %v", out, "eligible for close", got, tt.wantEligible)
}
})
}
}

View file

@ -7,7 +7,8 @@ import (
"github.com/steveyegge/beads/internal/types"
)
// GetEpicsEligibleForClosureInTx returns epics whose children are all closed.
// GetEpicsEligibleForClosureInTx returns open epics whose children are all closed
// with completing close reasons (not duplicate/wontfix/superseded).
// nolint:gosec // G201: table names are hardcoded, placeholders contain only ? markers
func GetEpicsEligibleForClosureInTx(ctx context.Context, tx DBTX) ([]*types.EpicStatus, error) {
// Step 1: Get open epic IDs (single-table scan)
@ -66,14 +67,19 @@ func GetEpicsEligibleForClosureInTx(ctx context.Context, tx DBTX) ([]*types.Epic
depRows.Close()
}
// Step 3: Batch-fetch statuses for all child issues across all epics
// Step 3: Batch-fetch statuses + close_reason for all child issues (bd-w2w).
// close_reason is required so duplicate/wontfix/superseded closes do not
// count as "complete" for EligibleForClose (GH#5026).
allChildIDs := make([]string, 0)
for _, children := range epicChildMap {
allChildIDs = append(allChildIDs, children...)
}
childStatusMap := make(map[string]string)
type childCloseInfo struct {
status string
closeReason string
}
childInfoMap := make(map[string]childCloseInfo)
if len(allChildIDs) > 0 {
// Check both issues and wisps tables for child statuses (bd-w2w)
for _, table := range []string{"issues", "wisps"} {
for start := 0; start < len(allChildIDs); start += queryBatchSize {
end := start + queryBatchSize
@ -83,7 +89,10 @@ func GetEpicsEligibleForClosureInTx(ctx context.Context, tx DBTX) ([]*types.Epic
batch := allChildIDs[start:end]
placeholders, args := buildSQLInClause(batch)
statusQuery := fmt.Sprintf("SELECT id, status FROM %s WHERE id IN (%s)", table, placeholders)
statusQuery := fmt.Sprintf(
"SELECT id, status, COALESCE(close_reason, '') FROM %s WHERE id IN (%s)",
table, placeholders,
)
statusRows, err := tx.QueryContext(ctx, statusQuery, args...)
if err != nil {
if isTableNotExistError(err) {
@ -92,12 +101,12 @@ func GetEpicsEligibleForClosureInTx(ctx context.Context, tx DBTX) ([]*types.Epic
return nil, fmt.Errorf("failed to batch-fetch child statuses from %s: %w", table, err)
}
for statusRows.Next() {
var id, status string
if err := statusRows.Scan(&id, &status); err != nil {
var id, status, closeReason string
if err := statusRows.Scan(&id, &status, &closeReason); err != nil {
statusRows.Close()
return nil, fmt.Errorf("scan child status: %w", err)
}
childStatusMap[id] = status
childInfoMap[id] = childCloseInfo{status: status, closeReason: closeReason}
}
statusRows.Close()
}
@ -135,17 +144,26 @@ func GetEpicsEligibleForClosureInTx(ctx context.Context, tx DBTX) ([]*types.Epic
totalChildren := len(children)
closedChildren := 0
completingClosed := 0
for _, childID := range children {
if status, ok := childStatusMap[childID]; ok && types.Status(status) == types.StatusClosed {
closedChildren++
info, ok := childInfoMap[childID]
if !ok || types.Status(info.status) != types.StatusClosed {
continue
}
closedChildren++
if !types.IsNonCompletingClose(info.closeReason) {
completingClosed++
}
}
// Eligible only when every child is closed AND every close is a completing
// one (finished work). Duplicate/wontfix/superseded closes leave the
// epic's real scope unfinished (GH#5026).
results = append(results, &types.EpicStatus{
Epic: issue,
TotalChildren: totalChildren,
ClosedChildren: closedChildren,
EligibleForClose: totalChildren > 0 && totalChildren == closedChildren,
EligibleForClose: totalChildren > 0 && totalChildren == completingClosed,
})
}

View file

@ -4,6 +4,7 @@ go_library(
name = "types",
srcs = [
"id_generator.go",
"non_completing_close.go",
"orphans.go",
"storage_ext.go",
"types.go",
@ -18,6 +19,7 @@ go_test(
"explain_test.go",
"id_generator_test.go",
"issue_summary_test.go",
"non_completing_close_test.go",
"storage_class_test.go",
"types_test.go",
],

View file

@ -0,0 +1,56 @@
package types
import (
"regexp"
"strings"
)
// nonCompletingCloseRegexp matches close reasons that redirect or abandon work
// rather than finish a deliverable. Children closed this way must not count
// toward epic/molecule "complete" eligibility (GH#5026).
//
// Matching is word-bounded (\b) rather than raw substring: close_reason is
// free-form prose (Issue.CloseReason is a plain string; cmd/bd/close.go only
// length-validates it), and a bare substring match false-positives on
// ordinary English — "added dedup pass for event ingest" contains "dup", and
// "removed obsolete migration shim" contains "obsolete", yet both describe
// completed work. The bare "dup" keyword is dropped entirely: it was already
// redundant with "duplicate"/"dupe" and only added false positives. Likewise
// the bare adjective "obsolete" is dropped in favor of "obsoleted" — a task
// closed because it was superseded/deprecated typically reads "obsoleted by
// X", while "obsolete" alone is commonly just describing what was removed.
//
// Separator tolerance is written into each multi-word keyword rather than
// applied by a global text normalization pass (GH#5138 review):
// "wont[- ]?fix", "won['\x{2019}]t[- ]?fix" and "not[- ]?planned" each accept
// a hyphen or space (or neither) between their two words. The "wont" and
// "won't" spellings must compose with the separator independently, not just
// each in isolation, or a lone "won't-fix" close still slips through as
// completing; "not-planned" is an equally natural hand-typed spelling and is
// given the same tolerance rather than being the one keyword that demands a
// space. The apostrophe class "['\x{2019}]" accepts both the ASCII apostrophe
// and the U+2019 typographic right single quote ("won't"/"won’t").
//
// A blanket hyphen-to-space fold over the whole reason was deliberately
// avoided: it would rewrite prose these keywords never cover, so the text
// that matched would no longer be the text the operator typed. Per-keyword
// tolerance keeps the reach exact — "not-yet-planned" does not match
// "not[- ]?planned" under any spelling, because the intervening "yet" blocks
// it either way, and that negative stays pinned in the test.
var nonCompletingCloseRegexp = regexp.MustCompile(`(?i)\b(duplicate|dupe|wont[- ]?fix|won['\x{2019}]t[- ]?fix|superseded|obsoleted|not[- ]?planned)\b`)
// IsNonCompletingClose reports whether closeReason is a redirection/abandon
// (duplicate, wontfix, superseded, …) rather than finished work. Empty reason
// is treated as completing for backward compatibility with closes that never
// recorded a reason.
//
// This lives in the leaf types package (not internal/storage/issueops, where
// GH#5026 originally added it) so that internal/workapi can also apply the
// same classifier to epic_closeable (GH#5138 review): issueops already
// imports workapi, so workapi importing issueops back would cycle.
func IsNonCompletingClose(closeReason string) bool {
if strings.TrimSpace(closeReason) == "" {
return false
}
return nonCompletingCloseRegexp.MatchString(closeReason)
}

View file

@ -0,0 +1,64 @@
package types
import "testing"
func TestIsNonCompletingClose(t *testing.T) {
t.Parallel()
cases := []struct {
reason string
want bool
}{
{"", false},
{" ", false},
{"done", false},
{"completed as planned", false},
{"fixed", false},
{"duplicate of bd-1", true},
{"Duplicate", true},
// Bare "dup" was dropped (GH#5026 review): redundant with
// "duplicate"/"dupe" and only added false-positive recall.
{"closed as dup of x", false},
{"wontfix", true},
{"won't fix — out of scope", true},
{"wont fix", true},
{"superseded by bd-9", true},
{"obsoleted by rewrite", true},
// Bare "obsolete" was dropped (GH#5026 review): "removed obsolete
// migration shim" describes completed cleanup work, not a redirect.
{"obsolete", false},
{"not planned", true},
// Failure closes (rejected/canceled) still completed their lifecycle
// for eligibility purposes — only redirect/abandon keywords qualify.
{"failed CI", false},
{"canceled", false},
// GH#5026 review, pinned regressions (word-boundary matching must not
// swallow substrings of ordinary prose in either direction).
{"removed obsolete shim", false},
{"duplicate of ee-1", true},
{"added dedup pass for event ingest", false},
// GH#5138 review: hyphenated separator ("wont-fix") and the U+2019
// typographic right single quote in "won't" must resolve like the
// already-handled ASCII forms above, and the two variants must
// compose (hyphen + curly apostrophe together), not just each alone.
{"wont-fix", true},
{"won’t fix", true}, // "won’t fix": U+2019 is a literal rune here, in the string AND this comment — if a smart-quote pass ever ASCII-folds one but not the other, the mismatch is the tell.
{"won't-fix", true},
{"won’t-fix", true}, // same tamper-evidence: literal U+2019 in both the case above and this comment.
// GH#5138 review: "not planned" carries the same per-keyword separator
// tolerance as the "wont fix" pair, so the hyphenated hand-typed
// spelling is classified identically.
{"not-planned", true},
{"notplanned", true},
// Hyphenated prose must not be swallowed by the hyphen tolerance —
// it reaches only inside a keyword, never across an intervening word,
// so this stays false with "not[- ]?planned" exactly as it did with
// the space-only spelling.
{"not-yet-planned", false},
}
for _, tc := range cases {
got := IsNonCompletingClose(tc.reason)
if got != tc.want {
t.Errorf("IsNonCompletingClose(%q) = %v, want %v", tc.reason, got, tc.want)
}
}
}

View file

@ -213,14 +213,20 @@ func BuildIssueDetails(ctx context.Context, src DetailSource, issue *types.Issue
// shallowDep keeps the identity-and-shape fields callers consume and drops the
// free-form text, which is the shape collectDependents settled on in be-4d36f2.
// CloseReason rides along despite being "text": it is short (a sentence, not
// a hub-scale blob like Description/Design/Notes), and applyEpicProgress
// needs it on every epic dependent to classify a completing vs. a
// duplicate/wontfix/superseded close (GH#5138 review) — dropping it here
// would silently starve that classifier on the very rows it runs against.
func shallowDep(item *types.IssueWithDependencyMetadata) *types.IssueWithDependencyMetadata {
return &types.IssueWithDependencyMetadata{
Issue: types.Issue{
ID: item.Issue.ID,
Status: item.Issue.Status,
IssueType: item.Issue.IssueType,
Priority: item.Issue.Priority,
Title: item.Issue.Title,
ID: item.Issue.ID,
Status: item.Issue.Status,
IssueType: item.Issue.IssueType,
Priority: item.Issue.Priority,
Title: item.Issue.Title,
CloseReason: item.Issue.CloseReason,
},
DependencyType: item.DependencyType,
}
@ -290,7 +296,7 @@ func applyEpicProgress(details *types.IssueDetails, dependents []*types.IssueWit
if details.IssueType != types.TypeEpic || len(dependents) == 0 {
return
}
total, closed := 0, 0
total, closed, completingClosed := 0, 0, 0
for _, dep := range dependents {
if dep.DependencyType != types.DepParentChild {
continue
@ -298,12 +304,20 @@ func applyEpicProgress(details *types.IssueDetails, dependents []*types.IssueWit
total++
if dep.Status == types.StatusClosed {
closed++
// A duplicate/wontfix/superseded close redirects or abandons the
// child rather than finishing it, so it must not make the epic
// closeable (GH#5138 review) — this mirrors the classifier
// GetEpicsEligibleForClosureInTx already applies; the two must
// not disagree on the same close_reason.
if !types.IsNonCompletingClose(dep.CloseReason) {
completingClosed++
}
}
}
if total == 0 {
return
}
closeable := total == closed
closeable := total == completingClosed
details.EpicTotalChildren = &total
details.EpicClosedChildren = &closed
details.EpicCloseable = &closeable

View file

@ -32,9 +32,10 @@ func newDetailFixture() *detailFixture {
return &detailFixture{
issues: map[string]*types.Issue{
"bd-1": {ID: "bd-1", Title: "Durable issue", IssueType: types.TypeTask, Status: types.StatusOpen, Priority: 1},
"bd-epic": {ID: "bd-epic", Title: "Epic", IssueType: types.TypeEpic, Status: types.StatusOpen, Priority: 1},
"bd-chat": {ID: "bd-chat", Title: "Has comments", IssueType: types.TypeTask, Status: types.StatusOpen},
"bd-1": {ID: "bd-1", Title: "Durable issue", IssueType: types.TypeTask, Status: types.StatusOpen, Priority: 1},
"bd-epic": {ID: "bd-epic", Title: "Epic", IssueType: types.TypeEpic, Status: types.StatusOpen, Priority: 1},
"bd-epic-dup": {ID: "bd-epic-dup", Title: "Epic with a duplicate close", IssueType: types.TypeEpic, Status: types.StatusOpen, Priority: 1},
"bd-chat": {ID: "bd-chat", Title: "Has comments", IssueType: types.TypeTask, Status: types.StatusOpen},
},
wisps: map[string]*types.Issue{
"bd-w1": {ID: "bd-w1", Title: "Ephemeral wisp", IssueType: types.TypeTask, Status: types.StatusOpen},
@ -67,6 +68,9 @@ func newDetailFixture() *detailFixture {
{Issue: types.Issue{ID: "bd-kid2", Title: "Kid 2", Status: types.StatusOpen}, DependencyType: types.DepParentChild},
{Issue: types.Issue{ID: "bd-other", Title: "Not a child", Status: types.StatusOpen}, DependencyType: types.DepBlocks},
},
"bd-epic-dup": {
{Issue: types.Issue{ID: "bd-dupkid", Title: "Dup kid", Status: types.StatusClosed, CloseReason: "duplicate of bd-1"}, DependencyType: types.DepParentChild},
},
"bd-w1": {
{Issue: types.Issue{ID: "bd-wkid", Title: "Wisp kid", Status: types.StatusOpen}, DependencyType: types.DepParentChild},
},
@ -676,6 +680,28 @@ func TestBuildIssueDetailsEpicProgress(t *testing.T) {
}
})
t.Run("not closeable when the only child closed as a duplicate (GH#5138 review)", func(t *testing.T) {
// epic_closeable must agree with issueops.GetEpicsEligibleForClosureInTx's
// classifier: a child closed "duplicate of X" redirects the work rather
// than finishing it, so total==closed alone must not make the epic
// closeable. Before the fix this reported epic_closeable=true because
// applyEpicProgress compared raw StatusClosed counts and never looked
// at CloseReason.
details, err := BuildIssueDetails(ctx, store, fx.issues["bd-epic-dup"], false, DetailOptions{IncludeDependents: true})
if err != nil {
t.Fatalf("BuildIssueDetails: %v", err)
}
if details.EpicTotalChildren == nil || *details.EpicTotalChildren != 1 {
t.Errorf("epic_total_children = %v, want 1", details.EpicTotalChildren)
}
if details.EpicClosedChildren == nil || *details.EpicClosedChildren != 1 {
t.Errorf("epic_closed_children = %v, want 1", details.EpicClosedChildren)
}
if details.EpicCloseable == nil || *details.EpicCloseable {
t.Errorf("epic_closeable = %v, want false", details.EpicCloseable)
}
})
t.Run("absent without IncludeDependents", func(t *testing.T) {
details, err := BuildIssueDetails(ctx, store, fx.issues["bd-epic"], false, DetailOptions{})
if err != nil {