beads/cmd/bd/mol_stale.go
Vishnu J b0c3c8f497
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>
2026-10-01 05:19:33 -07:00

222 lines
6.4 KiB
Go

package main
import (
"context"
"fmt"
"github.com/spf13/cobra"
"github.com/steveyegge/beads/internal/metrics"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
)
var molStaleCmd = &cobra.Command{
Use: "stale",
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. 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)
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
bd mol stale --json # Machine-readable output
bd mol stale --blocking # Only show those blocking other work
bd mol stale --unassigned # Only show unassigned molecules
bd mol stale --all # Include molecules with 0 children`,
SilenceUsage: true,
SilenceErrors: true,
RunE: runMolStale,
}
// StaleMolecule holds info about a stale molecule
type StaleMolecule struct {
ID string `json:"id"`
Title string `json:"title"`
TotalChildren int `json:"total_children"`
ClosedChildren int `json:"closed_children"`
Assignee string `json:"assignee,omitempty"`
BlockingIssues []string `json:"blocking_issues,omitempty"`
BlockingCount int `json:"blocking_count"`
}
// StaleResult holds the result of the stale check
type StaleResult struct {
StaleMolecules []*StaleMolecule `json:"stale_molecules"`
TotalCount int `json:"total_count"`
BlockingCount int `json:"blocking_count"`
}
func runMolStale(cmd *cobra.Command, args []string) error {
evt := metrics.NewCommandEvent("mol-stale")
defer func() {
if c := metrics.Global(); c != nil {
c.CloseEventAndAdd(evt)
}
}()
blockingOnly, _ := cmd.Flags().GetBool("blocking")
unassignedOnly, _ := cmd.Flags().GetBool("unassigned")
showAll, _ := cmd.Flags().GetBool("all")
if usesProxiedServer() {
return runMolStaleProxiedServer(rootCtx, blockingOnly, unassignedOnly, showAll)
}
ctx := rootCtx
var result *StaleResult
var err error
if store == nil {
return HandleErrorRespectJSON("no database connection")
}
result, err = findStaleMolecules(ctx, store, blockingOnly, unassignedOnly, showAll)
if err != nil {
return HandleErrorRespectJSON("%v", err)
}
if jsonOutput {
return outputJSON(result)
}
renderStaleResult(result, blockingOnly)
return nil
}
func renderStaleResult(result *StaleResult, blockingOnly bool) {
if len(result.StaleMolecules) == 0 {
fmt.Println("No stale molecules found.")
return
}
if blockingOnly {
fmt.Printf("%s Molecules with all children closed (review scope; blocking work):\n\n",
ui.RenderWarnIcon())
} else {
fmt.Printf("%s Molecules with all children closed (review scope before closing):\n\n",
ui.RenderInfoIcon())
}
for _, mol := range result.StaleMolecules {
progress := fmt.Sprintf("%d/%d", mol.ClosedChildren, mol.TotalChildren)
if mol.BlockingCount > 0 {
fmt.Printf(" %s %s (%s) [blocking %d]\n",
ui.RenderID(mol.ID), mol.Title, progress, mol.BlockingCount)
fmt.Printf(" → Close with: bd close %s\n", mol.ID)
if mol.BlockingCount <= 3 {
fmt.Printf(" → Blocking: %v\n", mol.BlockingIssues)
}
} else {
fmt.Printf(" %s %s (%s)\n",
ui.RenderID(mol.ID), mol.Title, progress)
fmt.Printf(" → Close with: bd close %s\n", mol.ID)
}
fmt.Println()
}
fmt.Printf("Total: %d stale", result.TotalCount)
if result.BlockingCount > 0 {
fmt.Printf(", %d blocking other work", result.BlockingCount)
}
fmt.Println()
}
// findStaleMolecules queries the database for stale molecules
func findStaleMolecules(ctx context.Context, s molReader, blockingOnly, unassignedOnly, showAll bool) (*StaleResult, error) {
// Get all epics eligible for closure (complete but unclosed)
epicStatuses, err := s.GetEpicsEligibleForClosure(ctx)
if err != nil {
return nil, fmt.Errorf("querying epics: %w", err)
}
// Get blocked issues to find what each stale molecule is blocking
blockedIssues, err := s.GetBlockedIssues(ctx, types.WorkFilter{})
if err != nil {
return nil, fmt.Errorf("querying blocked issues: %w", err)
}
// Build map of issue ID -> what issues it's blocking
blockingMap := buildBlockingMap(blockedIssues)
var staleMolecules []*StaleMolecule
blockingCount := 0
for _, es := range epicStatuses {
// Skip if not eligible for close (not all children closed)
if !es.EligibleForClose {
continue
}
// Skip if no children and not showing all
if es.TotalChildren == 0 && !showAll {
continue
}
// Filter by unassigned if requested
if unassignedOnly && es.Epic.Assignee != "" {
continue
}
// Find what this molecule is blocking
blocking := blockingMap[es.Epic.ID]
blockingIssueCount := len(blocking)
// Filter by blocking if requested
if blockingOnly && blockingIssueCount == 0 {
continue
}
mol := &StaleMolecule{
ID: es.Epic.ID,
Title: es.Epic.Title,
TotalChildren: es.TotalChildren,
ClosedChildren: es.ClosedChildren,
Assignee: es.Epic.Assignee,
BlockingIssues: blocking,
BlockingCount: blockingIssueCount,
}
staleMolecules = append(staleMolecules, mol)
if blockingIssueCount > 0 {
blockingCount++
}
}
return &StaleResult{
StaleMolecules: staleMolecules,
TotalCount: len(staleMolecules),
BlockingCount: blockingCount,
}, nil
}
// buildBlockingMap creates a map of issue ID -> list of issues it's blocking
func buildBlockingMap(blockedIssues []*types.BlockedIssue) map[string][]string {
result := make(map[string][]string)
for _, blocked := range blockedIssues {
// Each blocked issue has a list of what's blocking it
for _, blockerID := range blocked.BlockedBy {
result[blockerID] = append(result[blockerID], blocked.ID)
}
}
return result
}
func init() {
molStaleCmd.Flags().Bool("blocking", false, "Only show molecules blocking other work")
molStaleCmd.Flags().Bool("unassigned", false, "Only show unassigned molecules")
molStaleCmd.Flags().Bool("all", false, "Include molecules with 0 children")
molCmd.AddCommand(molStaleCmd)
}