beads/cmd/bd/list_test.go
Julian Knutsen 169c5fc499
perf(list): read only the listed issues' dependency edges (#7591)
* perf(list): read only the listed issues' dependency edges

`bd list`'s text renderings (the default tree, --deps, --parent, --format
and --watch) loaded every dependency record in the workspace through
GetAllDependencyRecords to draw one page. On a local store that is one
query. Over a connected HTTP workspace it is a walk of the whole workspace:
every issue id at 200 per request, then every id's edges at 100 per
request. `bd list --limit 20` against the ~3.8k-issue maintainer-city
workspace made 62 sequential requests and took ~5.7 s at ~50 ms a round
trip, where `bd list --json` makes 5.

Every rendering reads only edges a listed issue owns. The tree nests a
child under a parent only when both are listed, and looks the edge up
under the child. Sibling ordering, the --deps annotations and the gate
decoration read the listed node's own edges, and --format prints edges
between listed issues. An unlisted issue's edge onto a listed one, or a
parent off the page, is never read. listDependencyRecords reads exactly
those edges through the EdgeReader role, which every backend serves (the
http store refuses the raw GetDependencyRecordsForIssues batch method).
Over http that is one anchored listDependencies request per 100 listed
ids.

Through a logging proxy in front of the production bd serve, list
--limit 20 goes from 62 requests / 5.7 s to 6 / 0.49 s with
byte-identical output; every changed mode (--deps, --deps=all, --format
digraph/dot, --sort, --status, --ready, --limit 200, --limit 0, --parent)
prints the same bytes as before. On a local store a default page is as
fast or faster; a listing that covers most of a large durable store pays
batched reads instead of one table scan (+0.07 s at 1,000 rows, +0.46 s
at 4,000 on embedded Dolt).

Tests:
- backend/http TestE2E_ListTextRenderingsReadOnlyTheListedIssuesEdges:
  over a served workspace, the tree, --deps=all, a --limit cut, the
  --parent tree and --format digraph each make one listDependencies
  request naming exactly the listed ids, and at most one request more
  than the --json page. Failing first: the old read enumerated every id
  (all=true) and anchored the hidden closed issue too.
- cmd/bd: the page read equals GetAllDependencyRecords restricted to the
  page on Dolt server and embedded stores (both planes, every edge type,
  gates, external refs), and every text rendering prints the same bytes
  from either map; a runListCore spy pins one page read and no
  store-wide read; pure tests over an adversarial fixture (edges unlisted
  issues own pointing at listed ones, parents off the page, dotted
  children, a parent-child cycle) guard the renderers.

Refs: ga-nrnrlr.5

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(http): seed the list page-edges e2e with one graph apply

TestE2E_ListTextRenderingsReadOnlyTheListedIssuesEdges ran 26 s on
http_served_test's round-robin shard in CI, which made that shard the
embedded lane's longest test action (172 s). Most of it was subprocesses:
five creates and a close to seed, plus a --json budget run per case.

The fixture is now one `bd create --graph` plus the close (the batch
create cannot carry a closed row's closed_at over the wire), and one
`bd list --json` run is the budget for every page case, since its request
count does not depend on the page size. 16 subprocesses become 9. All
five cases still fail against the old GetAllDependencyRecords call
sites: each edge read anchors the hidden closed issue, and the four page
cases make 7 requests against the --json page's 5.

Refs: ga-nrnrlr.5

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Julian Knutsen
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 16:05:24 +00:00

1910 lines
56 KiB
Go

//go:build cgo
package main
import (
"context"
"io"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
"github.com/steveyegge/beads/internal/ui"
"github.com/steveyegge/beads/internal/utils"
)
// listTestHelper provides test setup and assertion methods
type listTestHelper struct {
t *testing.T
ctx context.Context
store *dolt.DoltStore
issues []*types.Issue
}
func newListTestHelper(t *testing.T, store *dolt.DoltStore) *listTestHelper {
return &listTestHelper{t: t, ctx: context.Background(), store: store}
}
func (h *listTestHelper) createTestIssues() {
now := time.Now()
h.issues = []*types.Issue{
{
Title: "Bug Issue",
Description: "Test bug",
Priority: 0,
IssueType: types.TypeBug,
Status: types.StatusOpen,
},
{
Title: "Feature Issue",
Description: "Test feature",
Priority: 1,
IssueType: types.TypeFeature,
Status: types.StatusInProgress,
Assignee: testUserAlice,
},
{
Title: "Task Issue",
Description: "Test task",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusClosed,
ClosedAt: &now,
},
}
for _, issue := range h.issues {
if err := h.store.CreateIssue(h.ctx, issue, "test-user"); err != nil {
h.t.Fatalf("Failed to create issue: %v", err)
}
}
}
func (h *listTestHelper) addLabel(id, label string) {
if err := h.store.AddLabel(h.ctx, id, label, "test-user"); err != nil {
h.t.Fatalf("Failed to add label: %v", err)
}
}
func (h *listTestHelper) search(filter types.IssueFilter) []*types.Issue {
results, err := h.store.SearchIssues(h.ctx, "", filter)
if err != nil {
h.t.Fatalf("Failed to search issues: %v", err)
}
return results
}
func (h *listTestHelper) assertCount(count, expected int, desc string) {
if count != expected {
h.t.Errorf("Expected %d %s, got %d", expected, desc, count)
}
}
func (h *listTestHelper) assertEqual(expected, actual interface{}, field string) {
if expected != actual {
h.t.Errorf("Expected %s %v, got %v", field, expected, actual)
}
}
func (h *listTestHelper) assertAtMost(count, maxCount int, desc string) {
if count > maxCount {
h.t.Errorf("Expected at most %d %s, got %d", maxCount, desc, count)
}
}
func TestListCommandSuite(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
s := newTestStore(t, testDB)
t.Run("ListCommand", func(t *testing.T) {
h := newListTestHelper(t, s)
h.createTestIssues()
h.addLabel(h.issues[0].ID, "critical")
t.Run("list all issues", func(t *testing.T) {
results := h.search(types.IssueFilter{})
h.assertCount(len(results), 3, "issues")
})
t.Run("filter by status", func(t *testing.T) {
status := types.StatusOpen
results := h.search(types.IssueFilter{Status: &status})
h.assertCount(len(results), 1, "open issues")
h.assertEqual(types.StatusOpen, results[0].Status, "status")
})
t.Run("filter by priority", func(t *testing.T) {
priority := 0
results := h.search(types.IssueFilter{Priority: &priority})
h.assertCount(len(results), 1, "P0 issues")
h.assertEqual(0, results[0].Priority, "priority")
})
t.Run("filter by assignee", func(t *testing.T) {
assignee := testUserAlice
results := h.search(types.IssueFilter{Assignee: &assignee})
h.assertCount(len(results), 1, "issues for alice")
h.assertEqual(testUserAlice, results[0].Assignee, "assignee")
})
t.Run("filter by issue type", func(t *testing.T) {
issueType := types.TypeBug
results := h.search(types.IssueFilter{IssueType: &issueType})
h.assertCount(len(results), 1, "bug issues")
h.assertEqual(types.TypeBug, results[0].IssueType, "type")
})
t.Run("filter by label", func(t *testing.T) {
results := h.search(types.IssueFilter{Labels: []string{"critical"}})
h.assertCount(len(results), 1, "issues with critical label")
if len(results) > 0 {
h.assertEqual("Bug Issue", results[0].Title, "label-filtered issue title")
}
})
t.Run("filter by title search", func(t *testing.T) {
results := h.search(types.IssueFilter{TitleSearch: "Bug"})
h.assertCount(len(results), 1, "issues matching 'Bug'")
if len(results) > 0 {
h.assertEqual("Bug Issue", results[0].Title, "title-search result")
}
})
t.Run("limit results", func(t *testing.T) {
results := h.search(types.IssueFilter{Limit: 2})
h.assertAtMost(len(results), 2, "issues")
})
t.Run("normalize labels", func(t *testing.T) {
labels := []string{" bug ", "critical", "", "bug", " feature "}
normalized := utils.NormalizeLabels(labels)
expected := []string{"bug", "critical", "feature"}
h.assertCount(len(normalized), len(expected), "normalized labels")
// Check deduplication and trimming
seen := make(map[string]bool)
for _, label := range normalized {
if label == "" {
t.Error("Found empty label after normalization")
}
if label != strings.TrimSpace(label) {
t.Errorf("Label not trimmed: '%s'", label)
}
if seen[label] {
t.Errorf("Duplicate label found: %s", label)
}
seen[label] = true
}
})
t.Run("output dot format", func(t *testing.T) {
// Add a dependency to make the graph more interesting
dep := &types.Dependency{
IssueID: h.issues[0].ID,
DependsOnID: h.issues[1].ID,
Type: types.DepBlocks,
}
if err := h.store.AddDependency(h.ctx, dep, "test-user"); err != nil {
t.Fatalf("Failed to add dependency: %v", err)
}
deps, derr := h.store.GetAllDependencyRecords(h.ctx)
if derr != nil {
t.Fatalf("GetAllDependencyRecords: %v", derr)
}
err := outputDotFormat(io.Discard, h.issues, deps)
if err != nil {
t.Errorf("outputDotFormat failed: %v", err)
}
})
t.Run("output formatted list dot", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(io.Discard, h.issues, deps, "dot")
if err != nil {
t.Errorf("outputFormattedList with dot format failed: %v", err)
}
})
t.Run("output formatted list digraph preset", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(io.Discard, h.issues, deps, "digraph")
if err != nil {
t.Errorf("outputFormattedList with digraph format failed: %v", err)
}
})
t.Run("output formatted list custom template", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(io.Discard, h.issues, deps, "{{.ID}} {{.Title}}")
if err != nil {
t.Errorf("outputFormattedList with custom template failed: %v", err)
}
})
t.Run("output formatted list invalid template", func(t *testing.T) {
deps, _ := h.store.GetAllDependencyRecords(h.ctx)
err := outputFormattedList(io.Discard, h.issues, deps, "{{.ID")
if err == nil {
t.Error("Expected error for invalid template")
}
})
})
}
func TestListQueryCapabilitiesSuite(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
s := newTestStore(t, testDB)
ctx := context.Background()
now := time.Now()
yesterday := now.Add(-24 * time.Hour)
twoDaysAgo := now.Add(-48 * time.Hour)
// Create test issues with varied attributes
issue1 := &types.Issue{
Title: "Authentication Bug",
Description: "Login fails with special characters",
Notes: "Needs urgent fix",
Priority: 0,
IssueType: types.TypeBug,
Status: types.StatusOpen,
Assignee: "alice",
}
issue2 := &types.Issue{
Title: "Add OAuth Support",
Description: "", // Empty description
Priority: 2,
IssueType: types.TypeFeature,
Status: types.StatusInProgress,
// No assignee
}
issue3 := &types.Issue{
Title: "Update Documentation",
Description: "Update README with new features",
Notes: "Include OAuth setup",
Priority: 3,
IssueType: types.TypeTask,
Status: types.StatusOpen,
Assignee: "bob",
}
for _, issue := range []*types.Issue{issue1, issue2, issue3} {
if err := s.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
}
// Close issue3 to set closed_at timestamp
if err := s.CloseIssue(ctx, issue3.ID, "test-user", "Testing", ""); err != nil {
t.Fatalf("Failed to close issue3: %v", err)
}
// Add labels
s.AddLabel(ctx, issue1.ID, "critical", "test-user")
s.AddLabel(ctx, issue1.ID, "security", "test-user")
s.AddLabel(ctx, issue3.ID, "docs", "test-user")
t.Run("pattern matching - title contains", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
TitleContains: "Auth",
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 2 {
t.Errorf("Expected 2 results with 'Auth' in title, got %d", len(results))
}
})
t.Run("pattern matching - description contains", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
DescriptionContains: "special characters",
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 result, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue1.ID {
t.Errorf("Expected issue1, got %s", results[0].ID)
}
})
t.Run("pattern matching - notes contains", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
NotesContains: "OAuth",
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 result, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue3.ID {
t.Errorf("Expected issue3, got %s", results[0].ID)
}
})
t.Run("empty description check", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
EmptyDescription: true,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue with empty description, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue2.ID {
t.Errorf("Expected issue2, got %s", results[0].ID)
}
})
t.Run("no assignee check", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
NoAssignee: true,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue with no assignee, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue2.ID {
t.Errorf("Expected issue2, got %s", results[0].ID)
}
})
t.Run("no labels check", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
NoLabels: true,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue with no labels, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue2.ID {
t.Errorf("Expected issue2, got %s", results[0].ID)
}
})
// AD-02: hydration toggle. SkipLabels=true means SearchIssues skips the
// labels JOIN entirely; rows are returned but Labels stays nil. Distinct
// from NoLabels (filter rows where labels=[]).
t.Run("skip labels hydration", func(t *testing.T) {
// Default hydration: issue1 has labels populated.
hydrated, err := s.SearchIssues(ctx, "", types.IssueFilter{
IDs: []string{issue1.ID},
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(hydrated) != 1 {
t.Fatalf("Expected 1 issue, got %d", len(hydrated))
}
if len(hydrated[0].Labels) == 0 {
t.Fatalf("precondition: issue1 should have labels in default hydration, got none")
}
// SkipLabels=true: same row, but Labels is left nil.
skipped, err := s.SearchIssues(ctx, "", types.IssueFilter{
IDs: []string{issue1.ID},
SkipLabels: true,
})
if err != nil {
t.Fatalf("Search with SkipLabels failed: %v", err)
}
if len(skipped) != 1 {
t.Fatalf("Expected 1 issue with SkipLabels, got %d", len(skipped))
}
if len(skipped[0].Labels) != 0 {
t.Errorf("SkipLabels=true should leave Labels empty, got %v", skipped[0].Labels)
}
if skipped[0].ID != issue1.ID {
t.Errorf("SkipLabels must not change row identity, got %s want %s", skipped[0].ID, issue1.ID)
}
})
t.Run("exclude label - single", func(t *testing.T) {
// issue1 has "critical" and "security"; issue3 has "docs"; issue2 has none.
// Excluding "critical" should return issue2 and issue3.
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
ExcludeLabels: []string{"critical"},
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
ids := make(map[string]bool)
for _, r := range results {
ids[r.ID] = true
}
if ids[issue1.ID] {
t.Errorf("issue1 (has 'critical') should be excluded")
}
if !ids[issue2.ID] {
t.Errorf("issue2 (no labels) should be included")
}
if !ids[issue3.ID] {
t.Errorf("issue3 (has 'docs', not 'critical') should be included")
}
})
t.Run("exclude label - multiple", func(t *testing.T) {
// Excluding "critical" and "docs" leaves only issue2.
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
ExcludeLabels: []string{"critical", "docs"},
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue after excluding critical+docs, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue2.ID {
t.Errorf("Expected issue2, got %s", results[0].ID)
}
})
t.Run("exclude label - combined with include", func(t *testing.T) {
// Include "security" AND exclude "docs": should return issue1 only.
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
Labels: []string{"security"},
ExcludeLabels: []string{"docs"},
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issue1.ID {
t.Errorf("Expected issue1, got %s", results[0].ID)
}
})
t.Run("priority range - min", func(t *testing.T) {
minPrio := 2
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
PriorityMin: &minPrio,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 2 {
t.Errorf("Expected 2 issues with priority >= 2, got %d", len(results))
}
})
t.Run("priority range - max", func(t *testing.T) {
maxPrio := 1
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
PriorityMax: &maxPrio,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue with priority <= 1, got %d", len(results))
}
})
t.Run("priority range - min and max", func(t *testing.T) {
minPrio := 1
maxPrio := 2
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
PriorityMin: &minPrio,
PriorityMax: &maxPrio,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 issue with priority between 1-2, got %d", len(results))
}
})
t.Run("date range - created after", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
CreatedAfter: &twoDaysAgo,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// All issues created recently
if len(results) != 3 {
t.Errorf("Expected 3 issues created after two days ago, got %d", len(results))
}
})
t.Run("date range - updated before", func(t *testing.T) {
futureTime := now.Add(24 * time.Hour)
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
UpdatedBefore: &futureTime,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// All issues updated before tomorrow
if len(results) != 3 {
t.Errorf("Expected 3 issues, got %d", len(results))
}
})
t.Run("date range - closed after", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
ClosedAfter: &yesterday,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 1 {
t.Errorf("Expected 1 closed issue, got %d", len(results))
}
})
t.Run("combined filters", func(t *testing.T) {
minPrio := 0
maxPrio := 2
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
TitleContains: "Auth",
PriorityMin: &minPrio,
PriorityMax: &maxPrio,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
if len(results) != 2 {
t.Errorf("Expected 2 results matching combined filters, got %d", len(results))
}
})
}
// TestListLabelFiltersAcnquj covers the acceptance criteria for be-acnquj
// (label/title-contains filters silently ignored). Before the fix, every
// label filter returned the full open set, breaking factory routing. Each
// subtest fails if the corresponding filter is not actually applied.
func TestListLabelFiltersAcnquj(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
s := newTestStore(t, testDB)
ctx := context.Background()
mk := func(title string, labels ...string) *types.Issue {
issue := &types.Issue{
Title: title,
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
if err := s.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("create %q: %v", title, err)
}
for _, label := range labels {
if err := s.AddLabel(ctx, issue.ID, label, "test-user"); err != nil {
t.Fatalf("addLabel %s/%s: %v", issue.ID, label, err)
}
}
return issue
}
apple := mk("apple pie", "fruit", "dessert")
orange := mk("orange juice", "fruit", "drink")
water := mk("water bottle", "drink")
rock := mk("rock formation")
techDebt := mk("tech debt: refactor cache", "tech-debt")
techLegacy := mk("tech legacy: old API", "tech-legacy")
idsOf := func(issues []*types.Issue) map[string]bool {
out := make(map[string]bool, len(issues))
for _, i := range issues {
out[i.ID] = true
}
return out
}
// AC#1: -l X returns ONLY beads with label X.
t.Run("label_single", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{Labels: []string{"fruit"}})
if err != nil {
t.Fatalf("search: %v", err)
}
got := idsOf(results)
if !got[apple.ID] || !got[orange.ID] {
t.Errorf("expected apple+orange, got %v", got)
}
if got[water.ID] || got[rock.ID] {
t.Errorf("water/rock should not match -l fruit, got %v", got)
}
})
// AC#1 + AC#6: -l X -l Y (AND semantics).
t.Run("label_and_composition", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{Labels: []string{"fruit", "drink"}})
if err != nil {
t.Fatalf("search: %v", err)
}
got := idsOf(results)
if len(got) != 1 || !got[orange.ID] {
t.Errorf("expected only orange (fruit AND drink), got %v", got)
}
})
// AC#2: --label-any A,B (OR semantics).
t.Run("label_any_or_composition", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{LabelsAny: []string{"dessert", "drink"}})
if err != nil {
t.Fatalf("search: %v", err)
}
got := idsOf(results)
if !got[apple.ID] || !got[orange.ID] || !got[water.ID] {
t.Errorf("expected apple+orange+water (dessert OR drink), got %v", got)
}
if got[rock.ID] {
t.Errorf("rock should not match dessert/drink, got %v", got)
}
})
// AC#3: --label-pattern glob matches labels by pattern.
t.Run("label_pattern_glob", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{LabelPattern: "tech-*"})
if err != nil {
t.Fatalf("search: %v", err)
}
got := idsOf(results)
if !got[techDebt.ID] || !got[techLegacy.ID] {
t.Errorf("expected tech-* labels to match, got %v", got)
}
if got[apple.ID] || got[water.ID] {
t.Errorf("non-tech labels should not match tech-*, got %v", got)
}
})
// AC#4: --title-contains case-insensitive substring.
t.Run("title_contains_case_insensitive", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{TitleContains: "PIE"})
if err != nil {
t.Fatalf("search: %v", err)
}
got := idsOf(results)
if len(got) != 1 || !got[apple.ID] {
t.Errorf("expected only apple (title contains 'pie'), got %v", got)
}
})
// AC#5: -l NONEXISTENT returns empty.
t.Run("label_nonexistent_empty", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{Labels: []string{"ZZZZZZZZ-no-such-label"}})
if err != nil {
t.Fatalf("search: %v", err)
}
if len(results) != 0 {
t.Errorf("expected empty result for nonexistent label, got %d issues", len(results))
}
})
}
// TestStableTreeOrdering tests that tree display order is stable across multiple invocations
// This test specifically addresses the bug where --tree output was non-deterministic due to
// unstable ordering of root issues and children within the same priority level
func TestStableTreeOrdering(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
store := newTestStore(t, testDB)
ctx := context.Background()
// Helper to create issue with specific priority for testing sort stability
createIssue := func(title string, priority int) *types.Issue {
issue := &types.Issue{
Title: title,
Priority: priority,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue %s: %v", title, err)
}
return issue
}
// Helper to add parent-child dependency
addParentChild := func(child, parent *types.Issue) {
dep := &types.Dependency{
IssueID: child.ID,
DependsOnID: parent.ID,
Type: types.DepParentChild,
CreatedAt: time.Now(),
CreatedBy: "test-user",
}
if err := store.AddDependency(ctx, dep, "test-user"); err != nil {
t.Fatalf("Failed to add dependency %s -> %s: %v", child.ID, parent.ID, err)
}
}
// Create a hierarchy with mixed priorities to test both primary and secondary sort:
// - Multiple root issues with same priority (tests secondary sort by ID)
// - Multiple children with same priority (tests children sorting stability)
// - Mixed priorities (tests primary sort by priority)
// Root issues with different priorities
rootP1A := createIssue("Root P1 A", 1) // Should be first (lowest priority number)
rootP1B := createIssue("Root P1 B", 1) // Should be second (same priority, sorted by ID)
rootP2 := createIssue("Root P2", 2) // Should be third
rootP3 := createIssue("Root P3", 3) // Should be last
// Children with mixed priorities under rootP1A
childP1 := createIssue("Child P1", 1) // Should be first child
childP2A := createIssue("Child P2 A", 2) // Should be second child
childP2B := createIssue("Child P2 B", 2) // Should be third child (same priority, sorted by ID)
childP3 := createIssue("Child P3", 3) // Should be last child
// Add parent-child relationships
addParentChild(childP1, rootP1A)
addParentChild(childP2A, rootP1A)
addParentChild(childP2B, rootP1A)
addParentChild(childP3, rootP1A)
// Test that buildIssueTree produces stable ordering
t.Run("stable_root_ordering", func(t *testing.T) {
// Get only the test issues we created (filter by title pattern)
testIssues := []*types.Issue{rootP1A, rootP1B, rootP2, rootP3}
// Build tree multiple times and verify identical ordering
var rootOrderings [][]string
for i := 0; i < 5; i++ {
roots, _ := buildIssueTree(testIssues)
// Extract root IDs in order
var rootIDs []string
for _, root := range roots {
rootIDs = append(rootIDs, root.ID)
}
rootOrderings = append(rootOrderings, rootIDs)
}
// Verify all runs produce identical root ordering
expectedRootOrder := rootOrderings[0]
for i := 1; i < len(rootOrderings); i++ {
if !slicesEqual(expectedRootOrder, rootOrderings[i]) {
t.Errorf("Root ordering differs between runs:\nRun 1: %v\nRun %d: %v",
expectedRootOrder, i+1, rootOrderings[i])
}
}
// Verify expected sort order (priority first, then ID)
// Since IDs are auto-generated, we'll verify by comparing with sorted slice
expectedRoots := []*types.Issue{rootP1A, rootP1B, rootP2, rootP3}
slices.SortFunc(expectedRoots, compareIssuesByPriority)
var expectedOrder []string
for _, issue := range expectedRoots {
expectedOrder = append(expectedOrder, issue.ID)
}
if !slicesEqual(expectedOrder, expectedRootOrder) {
t.Errorf("Root ordering incorrect:\nExpected: %v\nActual: %v",
expectedOrder, expectedRootOrder)
}
})
t.Run("stable_children_ordering", func(t *testing.T) {
// Get test issues including dependencies
allTestIssues := []*types.Issue{rootP1A, rootP1B, rootP2, rootP3, childP1, childP2A, childP2B, childP3}
// Load dependencies for tree building
allDeps, err := store.GetAllDependencyRecords(ctx)
if err != nil {
t.Fatalf("Failed to get dependencies: %v", err)
}
// Build tree multiple times and verify identical children ordering
var childOrderings [][]string
for i := 0; i < 5; i++ {
_, childrenMap := buildIssueTreeWithDeps(allTestIssues, allDeps)
// Extract children IDs of rootP1A in order
children := childrenMap[rootP1A.ID]
var childIDs []string
for _, child := range children {
childIDs = append(childIDs, child.ID)
}
childOrderings = append(childOrderings, childIDs)
}
// Verify all runs produce identical children ordering
if len(childOrderings) == 0 || len(childOrderings[0]) == 0 {
t.Fatal("No children found for rootP1A")
}
expectedChildOrder := childOrderings[0]
for i := 1; i < len(childOrderings); i++ {
if !slicesEqual(expectedChildOrder, childOrderings[i]) {
t.Errorf("Children ordering differs between runs:\nRun 1: %v\nRun %d: %v",
expectedChildOrder, i+1, childOrderings[i])
}
}
// Verify expected sort order by sorting the expected children and comparing
expectedChildren := []*types.Issue{childP1, childP2A, childP2B, childP3}
slices.SortFunc(expectedChildren, compareIssuesByPriority)
var expectedOrder []string
for _, child := range expectedChildren {
expectedOrder = append(expectedOrder, child.ID)
}
if !slicesEqual(expectedOrder, expectedChildOrder) {
t.Errorf("Children ordering incorrect:\nExpected: %v\nActual: %v",
expectedOrder, expectedChildOrder)
}
})
}
func TestTreeViewUsesWispDependencyRecords(t *testing.T) {
ctx := context.Background()
store := newTestStoreWithPrefix(t, filepath.Join(t.TempDir(), "test.db"), "test")
parent := &types.Issue{
ID: "tree-wisp-parent",
Title: "Parent epic",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeEpic,
}
child := &types.Issue{
ID: "tree-wisp-child",
Title: "Wisp child",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
Ephemeral: true,
}
for _, issue := range []*types.Issue{parent, child} {
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue(%s): %v", issue.ID, err)
}
}
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child.ID,
DependsOnID: parent.ID,
Type: types.DepParentChild,
}, "tester"); err != nil {
t.Fatalf("AddDependency: %v", err)
}
// The tree's own edge read: the listed issues' records, which for a wisp
// live in wisp_dependencies.
allDeps, err := listDependencyRecords(ctx, store, []*types.Issue{parent, child})
if err != nil {
t.Fatalf("listDependencyRecords: %v", err)
}
if ds := allDeps[child.ID]; len(ds) != 1 || ds[0].DependsOnID != parent.ID {
t.Fatalf("wisp dependency records = %+v, want child -> parent", ds)
}
roots, childrenMap := buildIssueTreeWithDeps([]*types.Issue{parent, child}, allDeps)
if len(roots) != 1 || roots[0].ID != parent.ID {
t.Fatalf("roots = %+v, want only parent root", roots)
}
children := childrenMap[parent.ID]
if len(children) != 1 || children[0].ID != child.ID {
t.Fatalf("children[%s] = %+v, want wisp child", parent.ID, children)
}
}
// Helper function to compare string slices for equality
func slicesEqual(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if a[i] != b[i] {
return false
}
}
return true
}
func TestFormatIssueLong(t *testing.T) {
t.Parallel()
tests := []struct {
name string
issue *types.Issue
labels []string
want string // substring to check for
}{
{
name: "open issue",
issue: &types.Issue{
ID: "test-123",
Title: "Test Issue",
Priority: 1,
IssueType: types.TypeBug,
Status: types.StatusOpen,
},
labels: nil,
want: "test-123",
},
{
name: "closed issue",
issue: &types.Issue{
ID: "test-456",
Title: "Closed Issue",
Priority: 0,
IssueType: types.TypeTask,
Status: types.StatusClosed,
},
labels: nil,
want: "test-456",
},
{
name: "issue with assignee",
issue: &types.Issue{
ID: "test-789",
Title: "Assigned Issue",
Priority: 2,
IssueType: types.TypeFeature,
Status: types.StatusInProgress,
Assignee: "alice",
},
labels: nil,
want: "Assignee: alice",
},
{
name: "issue with labels",
issue: &types.Issue{
ID: "test-abc",
Title: "Labeled Issue",
Priority: 1,
IssueType: types.TypeBug,
Status: types.StatusOpen,
},
labels: []string{"critical", "security"},
want: "Labels:",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf strings.Builder
formatIssueLong(&buf, tt.issue, tt.labels, false)
result := buf.String()
if !strings.Contains(result, tt.want) {
t.Errorf("formatIssueLong() = %q, want to contain %q", result, tt.want)
}
})
}
}
func TestFormatIssueCompact(t *testing.T) {
t.Parallel()
tests := []struct {
name string
issue *types.Issue
labels []string
want string
}{
{
name: "basic issue",
issue: &types.Issue{
ID: "test-123",
Title: "Test Issue",
Priority: 1,
IssueType: types.TypeBug,
Status: types.StatusOpen,
},
labels: nil,
want: "Test Issue",
},
{
name: "issue with assignee",
issue: &types.Issue{
ID: "test-456",
Title: "Assigned Issue",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusInProgress,
Assignee: "bob",
},
labels: nil,
want: "@bob",
},
{
name: "issue with labels",
issue: &types.Issue{
ID: "test-789",
Title: "Labeled Issue",
Priority: 0,
IssueType: types.TypeFeature,
Status: types.StatusOpen,
},
labels: []string{"urgent"},
want: "[urgent]",
},
{
name: "closed issue",
issue: &types.Issue{
ID: "test-def",
Title: "Closed Issue",
Priority: 3,
IssueType: types.TypeTask,
Status: types.StatusClosed,
},
labels: nil,
want: "Closed Issue",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf strings.Builder
formatIssueCompact(&buf, tt.issue, tt.labels, nil, nil, "", nil)
result := buf.String()
if !strings.Contains(result, tt.want) {
t.Errorf("formatIssueCompact() = %q, want to contain %q", result, tt.want)
}
})
}
}
func TestBuildBlockingMaps(t *testing.T) {
t.Parallel()
// Create test dependency records
allDeps := map[string][]*types.Dependency{
"issue-A": {
{IssueID: "issue-A", DependsOnID: "issue-B", Type: types.DepBlocks},
},
"issue-C": {
{IssueID: "issue-C", DependsOnID: "issue-A", Type: types.DepBlocks},
{IssueID: "issue-C", DependsOnID: "issue-B", Type: types.DepRelated}, // Should be ignored (not blocking)
},
}
blockedByMap, blocksMap, _ := buildBlockingMaps(allDeps, nil)
// issue-A is blocked by issue-B
if len(blockedByMap["issue-A"]) != 1 || blockedByMap["issue-A"][0] != "issue-B" {
t.Errorf("issue-A blockedBy = %v, want [issue-B]", blockedByMap["issue-A"])
}
// issue-B blocks issue-A
if len(blocksMap["issue-B"]) != 1 || blocksMap["issue-B"][0] != "issue-A" {
t.Errorf("issue-B blocks = %v, want [issue-A]", blocksMap["issue-B"])
}
// issue-C is blocked by issue-A (related dep is ignored)
if len(blockedByMap["issue-C"]) != 1 || blockedByMap["issue-C"][0] != "issue-A" {
t.Errorf("issue-C blockedBy = %v, want [issue-A]", blockedByMap["issue-C"])
}
// issue-A also blocks issue-C
if len(blocksMap["issue-A"]) != 1 || blocksMap["issue-A"][0] != "issue-C" {
t.Errorf("issue-A blocks = %v, want [issue-C]", blocksMap["issue-A"])
}
}
func TestBuildBlockingMaps_ParentChildSeparation(t *testing.T) {
t.Parallel()
allDeps := map[string][]*types.Dependency{
"child-1": {
{IssueID: "child-1", DependsOnID: "parent-1", Type: types.DepParentChild},
},
"child-2": {
{IssueID: "child-2", DependsOnID: "parent-1", Type: types.DepParentChild},
},
"issue-X": {
{IssueID: "issue-X", DependsOnID: "parent-1", Type: types.DepBlocks},
},
}
_, blocksMap, childrenMap := buildBlockingMaps(allDeps, nil)
// parent-1 should have children, not blocks, for parent-child deps
if len(childrenMap["parent-1"]) != 2 {
t.Errorf("parent-1 children = %v, want 2 children", childrenMap["parent-1"])
}
// parent-1 should only block issue-X (not child-1 or child-2)
if len(blocksMap["parent-1"]) != 1 || blocksMap["parent-1"][0] != "issue-X" {
t.Errorf("parent-1 blocks = %v, want [issue-X]", blocksMap["parent-1"])
}
}
func TestBuildBlockingMaps_ClosedBlockersFiltered(t *testing.T) {
t.Parallel()
// issue-A is blocked by issue-B (open) and issue-C (closed)
// issue-D is blocked by issue-C (closed) only
allDeps := map[string][]*types.Dependency{
"issue-A": {
{IssueID: "issue-A", DependsOnID: "issue-B", Type: types.DepBlocks},
{IssueID: "issue-A", DependsOnID: "issue-C", Type: types.DepBlocks},
},
"issue-D": {
{IssueID: "issue-D", DependsOnID: "issue-C", Type: types.DepBlocks},
},
}
closedIDs := map[string]bool{"issue-C": true}
blockedByMap, blocksMap, _ := buildBlockingMaps(allDeps, closedIDs)
// issue-A should only show issue-B as blocker (issue-C is closed)
if len(blockedByMap["issue-A"]) != 1 || blockedByMap["issue-A"][0] != "issue-B" {
t.Errorf("issue-A blockedBy = %v, want [issue-B]", blockedByMap["issue-A"])
}
// issue-D should have no blockers (issue-C is closed)
if len(blockedByMap["issue-D"]) != 0 {
t.Errorf("issue-D blockedBy = %v, want []", blockedByMap["issue-D"])
}
// issue-B should still show as blocking issue-A
if len(blocksMap["issue-B"]) != 1 || blocksMap["issue-B"][0] != "issue-A" {
t.Errorf("issue-B blocks = %v, want [issue-A]", blocksMap["issue-B"])
}
// issue-C should NOT show as blocking anything (it's closed)
if len(blocksMap["issue-C"]) != 0 {
t.Errorf("issue-C blocks = %v, want [] (closed blocker)", blocksMap["issue-C"])
}
}
func TestBuildBlockingMaps_NilClosedIDs(t *testing.T) {
t.Parallel()
// When closedIDs is nil, all blockers should be included (backward compat)
allDeps := map[string][]*types.Dependency{
"issue-A": {
{IssueID: "issue-A", DependsOnID: "issue-B", Type: types.DepBlocks},
},
}
blockedByMap, blocksMap, _ := buildBlockingMaps(allDeps, nil)
if len(blockedByMap["issue-A"]) != 1 || blockedByMap["issue-A"][0] != "issue-B" {
t.Errorf("issue-A blockedBy = %v, want [issue-B]", blockedByMap["issue-A"])
}
if len(blocksMap["issue-B"]) != 1 || blocksMap["issue-B"][0] != "issue-A" {
t.Errorf("issue-B blocks = %v, want [issue-A]", blocksMap["issue-B"])
}
}
func TestFormatIssueCompactWithDependencies(t *testing.T) {
t.Parallel()
tests := []struct {
name string
issue *types.Issue
blockedBy []string
blocks []string
want string
}{
{
name: "issue with blocked by",
issue: &types.Issue{
ID: "test-123",
Title: "Blocked Issue",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
},
blockedBy: []string{"test-100"},
blocks: nil,
want: "(blocked by: test-100)",
},
{
name: "issue with blocks",
issue: &types.Issue{
ID: "test-456",
Title: "Blocking Issue",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
},
blockedBy: nil,
blocks: []string{"test-200", "test-300"},
want: "(blocks: test-200, test-300)",
},
{
name: "issue with both",
issue: &types.Issue{
ID: "test-789",
Title: "Middle Issue",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
},
blockedBy: []string{"test-100"},
blocks: []string{"test-200"},
want: "(blocked by: test-100, blocks: test-200)",
},
{
name: "issue with no dependencies",
issue: &types.Issue{
ID: "test-abc",
Title: "Independent Issue",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
},
blockedBy: nil,
blocks: nil,
want: "Independent Issue",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var buf strings.Builder
formatIssueCompact(&buf, tt.issue, nil, tt.blockedBy, tt.blocks, "", nil)
result := buf.String()
if !strings.Contains(result, tt.want) {
t.Errorf("formatIssueCompact() = %q, want to contain %q", result, tt.want)
}
})
}
}
// TestFormatIssueCompactBlockedIcon verifies that dependency-blocked open issues
// show the blocked icon (●) instead of the open icon (○) in compact list output. (GH#2858)
func TestFormatIssueCompactBlockedIcon(t *testing.T) {
t.Parallel()
t.Run("open issue with blockers shows blocked icon", func(t *testing.T) {
issue := &types.Issue{
ID: "test-blocked",
Title: "Blocked by dependency",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
var buf strings.Builder
formatIssueCompact(&buf, issue, nil, []string{"blocker-1"}, nil, "", nil)
result := buf.String()
// Should show blocked icon ● not open icon ○
if strings.Contains(result, ui.StatusIconOpen) {
t.Errorf("dependency-blocked issue should not show open icon ○, got: %q", result)
}
if !strings.Contains(result, ui.StatusIconBlocked) {
t.Errorf("dependency-blocked issue should show blocked icon ●, got: %q", result)
}
})
t.Run("open issue without blockers shows open icon", func(t *testing.T) {
issue := &types.Issue{
ID: "test-open",
Title: "Normal open issue",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
var buf strings.Builder
formatIssueCompact(&buf, issue, nil, nil, nil, "", nil)
result := buf.String()
if !strings.Contains(result, ui.StatusIconOpen) {
t.Errorf("open issue without blockers should show open icon ○, got: %q", result)
}
})
t.Run("in_progress issue with blockers keeps in_progress icon", func(t *testing.T) {
issue := &types.Issue{
ID: "test-wip",
Title: "In progress with blocker",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusInProgress,
}
var buf strings.Builder
formatIssueCompact(&buf, issue, nil, []string{"blocker-1"}, nil, "", nil)
result := buf.String()
// Should keep in_progress icon, not override to blocked
if !strings.Contains(result, ui.StatusIconInProgress) {
t.Errorf("in_progress issue should keep its icon even with blockers, got: %q", result)
}
})
}
func TestParseTimeFlag(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input string
wantErr bool
}{
// Absolute formats
{"RFC3339", "2023-01-15T10:30:00Z", false},
{"Date only", "2023-01-15", false},
// Compact duration formats (GH#820)
{"Compact hours", "+6h", false},
{"Compact days", "+1d", false},
{"Compact weeks", "+2w", false},
{"Compact negative", "-3d", false},
{"Compact minutes", "+30min", false},
// Natural language (GH#820)
{"Natural tomorrow", "tomorrow", false},
{"Natural next monday", "next monday", false},
// Invalid formats
{"Invalid format", "not-a-date", true},
{"Empty string", "", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := parseTimeFlag(tt.input)
if (err != nil) != tt.wantErr {
t.Errorf("parseTimeFlag(%q) error = %v, wantErr %v", tt.input, err, tt.wantErr)
}
})
}
}
// TestParseTimeFlag_MinutesVsMonths guards GH#6609: "min" is minutes, bare "m" stays months.
func TestParseTimeFlag_MinutesVsMonths(t *testing.T) {
t.Parallel()
minutes, err := parseTimeFlag("+30min")
if err != nil {
t.Fatalf("parseTimeFlag(+30min) error: %v", err)
}
if d := time.Until(minutes); d < 29*time.Minute || d > 31*time.Minute {
t.Errorf("+30min resolved %v from now, want ~30m", d)
}
months, err := parseTimeFlag("+30m")
if err != nil {
t.Fatalf("parseTimeFlag(+30m) error: %v", err)
}
// Bound the months arm on both sides against a computed expectation: a
// one-sided "more than a year out" check stays green if "m" regressed to
// years or decades, which is the exact discrimination this test exists for.
wantMonths := time.Now().AddDate(0, 30, 0)
if d := months.Sub(wantMonths); d < -time.Minute || d > time.Minute {
t.Errorf("+30m resolved %v, want ~%v (30 months out)", months, wantMonths)
}
}
// TestListTimeBasedFilters tests the time-based scheduling filters (GH#820)
func TestListTimeBasedFilters(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
s := newTestStore(t, testDB)
ctx := context.Background()
now := time.Now()
yesterday := now.Add(-24 * time.Hour)
tomorrow := now.Add(24 * time.Hour)
nextWeek := now.Add(7 * 24 * time.Hour)
// Create test issues with varied due_at and defer_until values
issueNoSchedule := &types.Issue{
Title: "Issue without scheduling",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
issueDeferredFuture := &types.Issue{
Title: "Deferred until tomorrow",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
DeferUntil: &tomorrow,
}
issueDeferredPast := &types.Issue{
Title: "Was deferred until yesterday",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
DeferUntil: &yesterday,
}
issueDueNextWeek := &types.Issue{
Title: "Due next week",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
DueAt: &nextWeek,
}
issueOverdue := &types.Issue{
Title: "Overdue issue",
Priority: 0,
IssueType: types.TypeBug,
Status: types.StatusOpen,
DueAt: &yesterday,
}
issueOverdueClosed := &types.Issue{
Title: "Overdue but closed",
Priority: 0,
IssueType: types.TypeBug,
Status: types.StatusClosed,
DueAt: &yesterday,
ClosedAt: &now,
}
for _, issue := range []*types.Issue{
issueNoSchedule, issueDeferredFuture, issueDeferredPast,
issueDueNextWeek, issueOverdue, issueOverdueClosed,
} {
if err := s.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
}
t.Run("filter by deferred flag", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
Deferred: true,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find issues with defer_until set (future and past)
if len(results) != 2 {
t.Errorf("Expected 2 deferred issues, got %d", len(results))
}
})
t.Run("filter by defer-after", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
DeferAfter: &now,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find issues deferred after now (tomorrow)
if len(results) != 1 {
t.Errorf("Expected 1 issue deferred after now, got %d", len(results))
}
})
t.Run("filter by defer-before", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
DeferBefore: &now,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find issues deferred before now (yesterday)
if len(results) != 1 {
t.Errorf("Expected 1 issue deferred before now, got %d", len(results))
}
})
t.Run("filter by due-after", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
DueAfter: &now,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find issues due after now (next week)
if len(results) != 1 {
t.Errorf("Expected 1 issue due after now, got %d", len(results))
}
})
t.Run("filter by due-before", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
DueBefore: &now,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find issues due before now (overdue open + closed = 2)
if len(results) != 2 {
t.Errorf("Expected 2 issues due before now, got %d", len(results))
}
})
t.Run("filter by overdue", func(t *testing.T) {
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
Overdue: true,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find only the open overdue issue (not the closed one)
if len(results) != 1 {
t.Errorf("Expected 1 overdue issue, got %d", len(results))
}
if len(results) > 0 && results[0].ID != issueOverdue.ID {
t.Errorf("Expected issue %s, got %s", issueOverdue.ID, results[0].ID)
}
})
t.Run("combined filters defer and due", func(t *testing.T) {
// Issue with both defer_until and due_at
bothSet := &types.Issue{
Title: "Both deferred and due",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
DeferUntil: &tomorrow,
DueAt: &nextWeek,
}
if err := s.CreateIssue(ctx, bothSet, "test-user"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
results, err := s.SearchIssues(ctx, "", types.IssueFilter{
Deferred: true,
DueAfter: &now,
})
if err != nil {
t.Fatalf("Search failed: %v", err)
}
// Should find the issue with both defer_until set and due_at > now
if len(results) != 1 {
t.Errorf("Expected 1 issue with both filters, got %d", len(results))
}
})
}
// TestHierarchicalChildren tests the --tree --parent functionality for showing all descendants
func TestHierarchicalChildren(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
store := newTestStore(t, testDB)
ctx := context.Background()
// Helper to create issue
createIssue := func(title string, issueType types.IssueType) *types.Issue {
issue := &types.Issue{
Title: title,
Priority: 2,
IssueType: issueType,
Status: types.StatusOpen,
}
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue %s: %v", title, err)
}
return issue
}
// Helper to add dependency
addDep := func(child, parent *types.Issue) {
dep := &types.Dependency{
IssueID: child.ID,
DependsOnID: parent.ID,
Type: types.DepParentChild,
CreatedAt: time.Now(),
CreatedBy: "test-user",
}
if err := store.AddDependency(ctx, dep, "test-user"); err != nil {
t.Fatalf("Failed to add dependency %s -> %s: %v", child.ID, parent.ID, err)
}
}
// Create test hierarchy: Parent -> Child1 (-> Grandchild1.1, Grandchild1.2) + Child2 (-> Grandchild2.1)
parent := createIssue("Parent Epic", types.TypeEpic)
child1 := createIssue("Child 1", types.TypeTask)
child2 := createIssue("Child 2", types.TypeTask)
grandchild11 := createIssue("Grandchild 1.1", types.TypeTask)
grandchild12 := createIssue("Grandchild 1.2", types.TypeTask)
grandchild21 := createIssue("Grandchild 2.1", types.TypeTask)
addDep(child1, parent)
addDep(child2, parent)
addDep(grandchild11, child1)
addDep(grandchild12, child1)
addDep(grandchild21, child2)
// Test full hierarchy (should return all 6 issues)
t.Run("full_hierarchy", func(t *testing.T) {
issues, err := getHierarchicalChildren(ctx, store, "", parent.ID, types.IssueFilter{})
if err != nil {
t.Fatalf("getHierarchicalChildren failed: %v", err)
}
if len(issues) != 6 {
t.Errorf("Expected 6 issues in hierarchy, got %d", len(issues))
}
})
// Test child subset (should return child1 + its 2 grandchildren = 3 total)
t.Run("child_subset", func(t *testing.T) {
issues, err := getHierarchicalChildren(ctx, store, "", child1.ID, types.IssueFilter{})
if err != nil {
t.Fatalf("getHierarchicalChildren for child1 failed: %v", err)
}
if len(issues) != 3 {
t.Errorf("Expected 3 issues in child1 hierarchy, got %d", len(issues))
}
})
// Test leaf node: a childless parent is not echoed (GH#3349), so a leaf
// has no hierarchical children and the result is empty.
t.Run("leaf_node", func(t *testing.T) {
issues, err := getHierarchicalChildren(ctx, store, "", grandchild11.ID, types.IssueFilter{})
if err != nil {
t.Fatalf("getHierarchicalChildren for leaf failed: %v", err)
}
if len(issues) != 0 {
t.Errorf("Expected 0 issues for a leaf node (GH#3349: parent not echoed when childless), got %d", len(issues))
}
})
// Test error case - non-existent parent
t.Run("nonexistent_parent", func(t *testing.T) {
_, err := getHierarchicalChildren(ctx, store, "", "nonexistent-id", types.IssueFilter{})
if err == nil || !strings.Contains(err.Error(), "not found") {
t.Error("Expected 'not found' error for nonexistent parent")
}
})
}
// TestFormatDependencyInfoWithParent tests that parent-child deps render as "parent: X" (bd-hcxu)
func TestFormatDependencyInfoWithParent(t *testing.T) {
t.Parallel()
tests := []struct {
name string
blockedBy []string
blocks []string
parent string
gatedBy []string
want string
}{
{
name: "parent only",
parent: "epic-1",
want: "(parent: epic-1)",
},
{
name: "parent and blocked by",
parent: "epic-1",
blockedBy: []string{"blocker-1"},
want: "(parent: epic-1, blocked by: blocker-1)",
},
{
name: "parent and blocks",
parent: "epic-1",
blocks: []string{"child-1"},
want: "(parent: epic-1, blocks: child-1)",
},
{
name: "parent, blocked by, and blocks",
parent: "epic-1",
blockedBy: []string{"blocker-1"},
blocks: []string{"child-1"},
want: "(parent: epic-1, blocked by: blocker-1, blocks: child-1)",
},
{
name: "no parent, no deps",
want: "",
},
{
name: "blocked by only (no parent)",
blockedBy: []string{"blocker-1"},
want: "(blocked by: blocker-1)",
},
{
// A gate is also a blocker, so it shows up twice on purpose:
// "blocked by" says what to wait on, "gated by" says which of
// those nobody can clear by doing more work (wy-j2upyy).
name: "gate names itself in both clauses",
blockedBy: []string{"bd-gate"},
gatedBy: []string{"bd-gate"},
want: "(blocked by: bd-gate, gated by: bd-gate)",
},
{
name: "gated by alone still renders",
gatedBy: []string{"bd-gate"},
want: "(gated by: bd-gate)",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := formatDependencyInfo(tt.blockedBy, tt.blocks, tt.parent, tt.gatedBy)
if result != tt.want {
t.Errorf("formatDependencyInfo() = %q, want %q", result, tt.want)
}
})
}
}
// TestFormatIssueCompactWithParent tests compact format renders parent correctly (bd-hcxu)
func TestFormatIssueCompactWithParent(t *testing.T) {
t.Parallel()
issue := &types.Issue{
ID: "test-child",
Title: "Child Task",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
t.Run("shows parent annotation", func(t *testing.T) {
var buf strings.Builder
formatIssueCompact(&buf, issue, nil, nil, nil, "test-parent", nil)
result := buf.String()
if !strings.Contains(result, "(parent: test-parent)") {
t.Errorf("Expected '(parent: test-parent)' in output, got %q", result)
}
})
t.Run("does not show blocked by for parent", func(t *testing.T) {
var buf strings.Builder
formatIssueCompact(&buf, issue, nil, nil, nil, "test-parent", nil)
result := buf.String()
if strings.Contains(result, "blocked by") {
t.Errorf("Should not contain 'blocked by' for parent-child dep, got %q", result)
}
})
t.Run("shows parent and blocked by together", func(t *testing.T) {
var buf strings.Builder
formatIssueCompact(&buf, issue, nil, []string{"blocker-1"}, nil, "test-parent", nil)
result := buf.String()
if !strings.Contains(result, "(parent: test-parent, blocked by: blocker-1)") {
t.Errorf("Expected '(parent: test-parent, blocked by: blocker-1)' in output, got %q", result)
}
})
}
// TestGetBlockingInfoForIssues_ParentChildSeparation tests that parent-child deps go to parentMap (bd-hcxu)
func TestGetBlockingInfoForIssues_ParentChildSeparation(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
store := newTestStore(t, testDB)
ctx := context.Background()
// Create parent and child
parent := &types.Issue{
Title: "Parent Epic",
Priority: 2,
IssueType: types.TypeEpic,
Status: types.StatusOpen,
}
child := &types.Issue{
Title: "Child Task",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
blocker := &types.Issue{
Title: "Blocker Task",
Priority: 1,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
for _, issue := range []*types.Issue{parent, child, blocker} {
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
}
// Add parent-child dep
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild,
}, "test-user"); err != nil {
t.Fatalf("Failed to add parent-child dep: %v", err)
}
// Add blocking dep
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child.ID, DependsOnID: blocker.ID, Type: types.DepBlocks,
}, "test-user"); err != nil {
t.Fatalf("Failed to add blocking dep: %v", err)
}
blockedByMap, blocksMap, parentMap, err := store.GetBlockingInfoForIssues(ctx, []string{child.ID, parent.ID, blocker.ID})
if err != nil {
t.Fatalf("GetBlockingInfoForIssues failed: %v", err)
}
// Child should have parent in parentMap, not in blockedByMap
if parentMap[child.ID] != parent.ID {
t.Errorf("parentMap[%s] = %q, want %q", child.ID, parentMap[child.ID], parent.ID)
}
// Child should have blocker in blockedByMap
if len(blockedByMap[child.ID]) != 1 || blockedByMap[child.ID][0] != blocker.ID {
t.Errorf("blockedByMap[%s] = %v, want [%s]", child.ID, blockedByMap[child.ID], blocker.ID)
}
// Parent should NOT appear in blockedByMap for child
for _, id := range blockedByMap[child.ID] {
if id == parent.ID {
t.Errorf("parent %s should NOT be in blockedByMap for child %s", parent.ID, child.ID)
}
}
// Blocker should show in blocksMap
if len(blocksMap[blocker.ID]) != 1 || blocksMap[blocker.ID][0] != child.ID {
t.Errorf("blocksMap[%s] = %v, want [%s]", blocker.ID, blocksMap[blocker.ID], child.ID)
}
}
// TestListJSON_ParentField tests that bd list --json includes computed parent field (bd-ym8c)
func TestListJSON_ParentField(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
store := newTestStore(t, testDB)
ctx := context.Background()
parent := &types.Issue{
Title: "Parent Epic",
Priority: 2,
IssueType: types.TypeEpic,
Status: types.StatusOpen,
}
child := &types.Issue{
Title: "Child Task",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
standalone := &types.Issue{
Title: "Standalone Task",
Priority: 2,
IssueType: types.TypeTask,
Status: types.StatusOpen,
}
for _, issue := range []*types.Issue{parent, child, standalone} {
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
t.Fatalf("Failed to create issue: %v", err)
}
}
// Add parent-child dep
if err := store.AddDependency(ctx, &types.Dependency{
IssueID: child.ID, DependsOnID: parent.ID, Type: types.DepParentChild,
}, "test-user"); err != nil {
t.Fatalf("Failed to add parent-child dep: %v", err)
}
// Simulate what list.go JSON path does: fetch deps and compute parent
issueIDs := []string{parent.ID, child.ID, standalone.ID}
allDeps, err := store.GetDependencyRecordsForIssues(ctx, issueIDs)
if err != nil {
t.Fatalf("GetDependencyRecordsForIssues failed: %v", err)
}
// Build IssueWithCounts with parent computation
for _, issue := range []*types.Issue{parent, child, standalone} {
var computedParent *string
for _, dep := range allDeps[issue.ID] {
if dep.Type == types.DepParentChild {
computedParent = &dep.DependsOnID
break
}
}
iwc := &types.IssueWithCounts{
Issue: issue,
Parent: computedParent,
}
if issue.ID == child.ID {
if iwc.Parent == nil || *iwc.Parent != parent.ID {
t.Errorf("Child %s should have parent %s, got %v", child.ID, parent.ID, iwc.Parent)
}
} else {
if iwc.Parent != nil {
t.Errorf("Issue %s should have nil parent, got %q", issue.ID, *iwc.Parent)
}
}
}
}
func TestListCommandInit(t *testing.T) {
t.Parallel()
if listCmd == nil {
t.Fatal("listCmd should be initialized")
}
// Verify --exclude-label flag exists and defaults to empty slice
excludeLabelFlag := listCmd.Flags().Lookup("exclude-label")
if excludeLabelFlag == nil {
t.Fatal("--exclude-label flag should exist on bd list")
}
if excludeLabelFlag.DefValue != "[]" {
t.Errorf("--exclude-label default should be '[]', got %q", excludeLabelFlag.DefValue)
}
}