From e13bc5638f81a9adaf9a0b82ca34dc5aeedbca66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Fri, 17 Jul 2026 15:29:48 -0700 Subject: [PATCH] more commands --- cmd/bd/count.go | 446 +++++++------ cmd/bd/count_proxied_integration_test.go | 623 ++++++++++++++++++ cmd/bd/count_proxied_server.go | 32 + cmd/bd/create_proxied_server.go | 4 +- cmd/bd/defer.go | 11 +- cmd/bd/defer_proxied_integration_test.go | 155 +++++ cmd/bd/defer_proxied_server.go | 163 +++++ cmd/bd/duplicates.go | 241 +++---- cmd/bd/duplicates_proxied_integration_test.go | 387 +++++++++++ cmd/bd/duplicates_proxied_server.go | 36 + cmd/bd/epic.go | 186 +++--- cmd/bd/epic_proxied_integration_test.go | 181 +++++ cmd/bd/epic_proxied_server.go | 72 ++ cmd/bd/find_duplicates.go | 36 +- cmd/bd/find_duplicates_proxied_server.go | 23 + cmd/bd/graph.go | 276 ++++---- cmd/bd/graph_proxied_integration_test.go | 227 +++++++ cmd/bd/graph_proxied_server.go | 141 ++++ cmd/bd/history.go | 118 ++-- cmd/bd/history_proxied_integration_test.go | 259 ++++++++ cmd/bd/history_proxied_server.go | 15 + cmd/bd/info.go | 191 +++--- cmd/bd/info_proxied_integration_test.go | 221 +++++++ cmd/bd/info_proxied_server.go | 45 ++ cmd/bd/lint.go | 202 +++--- cmd/bd/lint_proxied_server.go | 28 + cmd/bd/lint_stale_proxied_integration_test.go | 356 ++++++++++ cmd/bd/orphans.go | 104 +-- cmd/bd/orphans_proxied_integration_test.go | 125 ++++ cmd/bd/orphans_proxied_server.go | 65 ++ cmd/bd/reclaim.go | 54 +- cmd/bd/set_state_proxied_integration_test.go | 178 +++++ cmd/bd/stale.go | 30 +- cmd/bd/stale_proxied_server.go | 22 + cmd/bd/state.go | 14 +- cmd/bd/state_proxied_server.go | 142 ++++ cmd/bd/status.go | 142 ++-- cmd/bd/status_proxied_integration_test.go | 257 ++++++++ cmd/bd/status_proxied_server.go | 51 ++ cmd/bd/statuses.go | 83 +-- cmd/bd/statuses_proxied_server.go | 22 + ...statuses_types_proxied_integration_test.go | 267 ++++++++ cmd/bd/types.go | 73 +- cmd/bd/types_proxied_server.go | 20 + cmd/bd/unclaim.go | 14 +- cmd/bd/unclaim_proxied_integration_test.go | 220 +++++++ cmd/bd/unclaim_proxied_server.go | 121 ++++ cmd/bd/undefer.go | 11 +- internal/storage/dbproxy/util/dsn.go | 24 +- internal/storage/domain/config.go | 9 + internal/storage/domain/db/config.go | 22 +- internal/storage/domain/db/issue.go | 65 ++ internal/storage/domain/issue.go | 82 +++ internal/storage/issueops/count.go | 13 +- internal/storage/issueops/epic_closure.go | 3 +- internal/storage/issueops/events.go | 2 +- internal/storage/issueops/history.go | 2 +- internal/storage/issueops/stale.go | 3 +- internal/storage/issueops/unclaim.go | 7 +- internal/storage/uow/dolt_sql_provider.go | 13 +- 60 files changed, 5824 insertions(+), 1111 deletions(-) create mode 100644 cmd/bd/count_proxied_integration_test.go create mode 100644 cmd/bd/count_proxied_server.go create mode 100644 cmd/bd/defer_proxied_integration_test.go create mode 100644 cmd/bd/defer_proxied_server.go create mode 100644 cmd/bd/duplicates_proxied_integration_test.go create mode 100644 cmd/bd/duplicates_proxied_server.go create mode 100644 cmd/bd/epic_proxied_integration_test.go create mode 100644 cmd/bd/epic_proxied_server.go create mode 100644 cmd/bd/find_duplicates_proxied_server.go create mode 100644 cmd/bd/graph_proxied_integration_test.go create mode 100644 cmd/bd/graph_proxied_server.go create mode 100644 cmd/bd/history_proxied_integration_test.go create mode 100644 cmd/bd/history_proxied_server.go create mode 100644 cmd/bd/info_proxied_integration_test.go create mode 100644 cmd/bd/info_proxied_server.go create mode 100644 cmd/bd/lint_proxied_server.go create mode 100644 cmd/bd/lint_stale_proxied_integration_test.go create mode 100644 cmd/bd/orphans_proxied_integration_test.go create mode 100644 cmd/bd/orphans_proxied_server.go create mode 100644 cmd/bd/set_state_proxied_integration_test.go create mode 100644 cmd/bd/stale_proxied_server.go create mode 100644 cmd/bd/status_proxied_integration_test.go create mode 100644 cmd/bd/status_proxied_server.go create mode 100644 cmd/bd/statuses_proxied_server.go create mode 100644 cmd/bd/statuses_types_proxied_integration_test.go create mode 100644 cmd/bd/types_proxied_server.go create mode 100644 cmd/bd/unclaim_proxied_integration_test.go create mode 100644 cmd/bd/unclaim_proxied_server.go diff --git a/cmd/bd/count.go b/cmd/bd/count.go index 1083b6117..3e08ac45b 100644 --- a/cmd/bd/count.go +++ b/cmd/bd/count.go @@ -2,6 +2,7 @@ package main import ( "cmp" + "context" "fmt" "slices" "strings" @@ -35,9 +36,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("count is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("count") defer func() { if c := metrics.Global(); c != nil { @@ -45,237 +43,259 @@ Examples: } }() - status, _ := cmd.Flags().GetString("status") - assignee, _ := cmd.Flags().GetString("assignee") - issueType, _ := cmd.Flags().GetString("type") - labels, _ := cmd.Flags().GetStringSlice("label") - labelsAny, _ := cmd.Flags().GetStringSlice("label-any") - titleSearch, _ := cmd.Flags().GetString("title") - idFilter, _ := cmd.Flags().GetString("id") - - // Pattern matching flags - titleContains, _ := cmd.Flags().GetString("title-contains") - descContains, _ := cmd.Flags().GetString("desc-contains") - notesContains, _ := cmd.Flags().GetString("notes-contains") - - // Date range flags - createdAfter, _ := cmd.Flags().GetString("created-after") - createdBefore, _ := cmd.Flags().GetString("created-before") - updatedAfter, _ := cmd.Flags().GetString("updated-after") - updatedBefore, _ := cmd.Flags().GetString("updated-before") - closedAfter, _ := cmd.Flags().GetString("closed-after") - closedBefore, _ := cmd.Flags().GetString("closed-before") - - // Empty/null check flags - emptyDesc, _ := cmd.Flags().GetBool("empty-description") - noAssignee, _ := cmd.Flags().GetBool("no-assignee") - noLabels, _ := cmd.Flags().GetBool("no-labels") - - // Priority range flags - priorityMin, _ := cmd.Flags().GetInt("priority-min") - priorityMax, _ := cmd.Flags().GetInt("priority-max") - - // Group by flags - byStatus, _ := cmd.Flags().GetBool("by-status") - byPriority, _ := cmd.Flags().GetBool("by-priority") - byType, _ := cmd.Flags().GetBool("by-type") - byAssignee, _ := cmd.Flags().GetBool("by-assignee") - byLabel, _ := cmd.Flags().GetBool("by-label") - - // Determine groupBy value - groupBy := "" - groupCount := 0 - if byStatus { - groupBy = "status" - groupCount++ - } - if byPriority { - groupBy = "priority" - groupCount++ - } - if byType { - groupBy = "type" - groupCount++ - } - if byAssignee { - groupBy = "assignee" - groupCount++ - } - if byLabel { - groupBy = "label" - groupCount++ + if usesProxiedServer() { + return runCountProxiedServer(cmd, rootCtx) } - if groupCount > 1 { - return HandleErrorRespectJSON("only one --by-* flag can be specified") + filter, groupBy, issueType, includeInfra, err := parseCountFilter(cmd) + if err != nil { + return err } - // Normalize labels - labels = utils.NormalizeLabels(labels) - labelsAny = utils.NormalizeLabels(labelsAny) - ctx := rootCtx - - // Direct mode - filter := types.IssueFilter{} - if status != "" && status != "all" { - s := types.Status(status) - filter.Status = &s - } - if cmd.Flags().Changed("priority") { - priority, _ := cmd.Flags().GetInt("priority") - filter.Priority = &priority - } - if assignee != "" { - filter.Assignee = &assignee - } - if issueType != "" { - t := types.IssueType(issueType) - filter.IssueType = &t - } - if len(labels) > 0 { - filter.Labels = labels - } - if len(labelsAny) > 0 { - filter.LabelsAny = labelsAny - } - if titleSearch != "" { - filter.TitleSearch = titleSearch - } - if idFilter != "" { - ids := utils.NormalizeLabels(strings.Split(idFilter, ",")) - if len(ids) > 0 { - filter.IDs = ids - } - } - - // Pattern matching - filter.TitleContains = titleContains - filter.DescriptionContains = descContains - filter.NotesContains = notesContains - - // Date ranges - if createdAfter != "" { - t, err := parseTimeFlag(createdAfter) - if err != nil { - return HandleErrorRespectJSON("parsing --created-after: %v", err) - } - filter.CreatedAfter = &t - } - if createdBefore != "" { - t, err := parseTimeFlag(createdBefore) - if err != nil { - return HandleErrorRespectJSON("parsing --created-before: %v", err) - } - filter.CreatedBefore = &t - } - if updatedAfter != "" { - t, err := parseTimeFlag(updatedAfter) - if err != nil { - return HandleErrorRespectJSON("parsing --updated-after: %v", err) - } - filter.UpdatedAfter = &t - } - if updatedBefore != "" { - t, err := parseTimeFlag(updatedBefore) - if err != nil { - return HandleErrorRespectJSON("parsing --updated-before: %v", err) - } - filter.UpdatedBefore = &t - } - if closedAfter != "" { - t, err := parseTimeFlag(closedAfter) - if err != nil { - return HandleErrorRespectJSON("parsing --closed-after: %v", err) - } - filter.ClosedAfter = &t - } - if closedBefore != "" { - t, err := parseTimeFlag(closedBefore) - if err != nil { - return HandleErrorRespectJSON("parsing --closed-before: %v", err) - } - filter.ClosedBefore = &t - } - - // Empty/null checks - filter.EmptyDescription = emptyDesc - filter.NoAssignee = noAssignee - filter.NoLabels = noLabels - - // Priority range - if cmd.Flags().Changed("priority-min") { - filter.PriorityMin = &priorityMin - } - if cmd.Flags().Changed("priority-max") { - filter.PriorityMax = &priorityMax - } - - if includeInfra, _ := cmd.Flags().GetBool("include-infra"); includeInfra { + if includeInfra { cfg, err := loadDirectListFilterConfig(ctx, store) if err != nil { return HandleError("%v", err) } applyCountIncludeInfra(&filter, issueType, cfg) } else { - filter.SkipWisps = true // durable tier only; bd count's historical default + filter.SkipWisps = true } - if groupBy == "" { - count, err := store.CountIssues(ctx, "", filter) - if err != nil { - return HandleErrorRespectJSON("%v", err) - } - if jsonOutput { - return outputJSON(struct { - Count int64 `json:"count"` - }{Count: count}) - } - fmt.Println(count) - return nil - } + return executeCount(ctx, store, filter, groupBy) + }, +} - counts, err := store.CountIssuesByGroup(ctx, filter, groupBy) +func parseCountFilter(cmd *cobra.Command) (types.IssueFilter, string, string, bool, error) { + status, _ := cmd.Flags().GetString("status") + assignee, _ := cmd.Flags().GetString("assignee") + issueType, _ := cmd.Flags().GetString("type") + labels, _ := cmd.Flags().GetStringSlice("label") + labelsAny, _ := cmd.Flags().GetStringSlice("label-any") + titleSearch, _ := cmd.Flags().GetString("title") + idFilter, _ := cmd.Flags().GetString("id") + + // Pattern matching flags + titleContains, _ := cmd.Flags().GetString("title-contains") + descContains, _ := cmd.Flags().GetString("desc-contains") + notesContains, _ := cmd.Flags().GetString("notes-contains") + + // Date range flags + createdAfter, _ := cmd.Flags().GetString("created-after") + createdBefore, _ := cmd.Flags().GetString("created-before") + updatedAfter, _ := cmd.Flags().GetString("updated-after") + updatedBefore, _ := cmd.Flags().GetString("updated-before") + closedAfter, _ := cmd.Flags().GetString("closed-after") + closedBefore, _ := cmd.Flags().GetString("closed-before") + + // Empty/null check flags + emptyDesc, _ := cmd.Flags().GetBool("empty-description") + noAssignee, _ := cmd.Flags().GetBool("no-assignee") + noLabels, _ := cmd.Flags().GetBool("no-labels") + + // Priority range flags + priorityMin, _ := cmd.Flags().GetInt("priority-min") + priorityMax, _ := cmd.Flags().GetInt("priority-max") + + // Group by flags + byStatus, _ := cmd.Flags().GetBool("by-status") + byPriority, _ := cmd.Flags().GetBool("by-priority") + byType, _ := cmd.Flags().GetBool("by-type") + byAssignee, _ := cmd.Flags().GetBool("by-assignee") + byLabel, _ := cmd.Flags().GetBool("by-label") + + // Determine groupBy value + groupBy := "" + groupCount := 0 + if byStatus { + groupBy = "status" + groupCount++ + } + if byPriority { + groupBy = "priority" + groupCount++ + } + if byType { + groupBy = "type" + groupCount++ + } + if byAssignee { + groupBy = "assignee" + groupCount++ + } + if byLabel { + groupBy = "label" + groupCount++ + } + + if groupCount > 1 { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("only one --by-* flag can be specified") + } + + // Normalize labels + labels = utils.NormalizeLabels(labels) + labelsAny = utils.NormalizeLabels(labelsAny) + + filter := types.IssueFilter{} + if status != "" && status != "all" { + s := types.Status(status) + filter.Status = &s + } + if cmd.Flags().Changed("priority") { + priority, _ := cmd.Flags().GetInt("priority") + filter.Priority = &priority + } + if assignee != "" { + filter.Assignee = &assignee + } + if issueType != "" { + t := types.IssueType(issueType) + filter.IssueType = &t + } + if len(labels) > 0 { + filter.Labels = labels + } + if len(labelsAny) > 0 { + filter.LabelsAny = labelsAny + } + if titleSearch != "" { + filter.TitleSearch = titleSearch + } + if idFilter != "" { + ids := utils.NormalizeLabels(strings.Split(idFilter, ",")) + if len(ids) > 0 { + filter.IDs = ids + } + } + + // Pattern matching + filter.TitleContains = titleContains + filter.DescriptionContains = descContains + filter.NotesContains = notesContains + + // Date ranges + if createdAfter != "" { + t, err := parseTimeFlag(createdAfter) + if err != nil { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("parsing --created-after: %v", err) + } + filter.CreatedAfter = &t + } + if createdBefore != "" { + t, err := parseTimeFlag(createdBefore) + if err != nil { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("parsing --created-before: %v", err) + } + filter.CreatedBefore = &t + } + if updatedAfter != "" { + t, err := parseTimeFlag(updatedAfter) + if err != nil { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("parsing --updated-after: %v", err) + } + filter.UpdatedAfter = &t + } + if updatedBefore != "" { + t, err := parseTimeFlag(updatedBefore) + if err != nil { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("parsing --updated-before: %v", err) + } + filter.UpdatedBefore = &t + } + if closedAfter != "" { + t, err := parseTimeFlag(closedAfter) + if err != nil { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("parsing --closed-after: %v", err) + } + filter.ClosedAfter = &t + } + if closedBefore != "" { + t, err := parseTimeFlag(closedBefore) + if err != nil { + return types.IssueFilter{}, "", "", false, HandleErrorRespectJSON("parsing --closed-before: %v", err) + } + filter.ClosedBefore = &t + } + + // Empty/null checks + filter.EmptyDescription = emptyDesc + filter.NoAssignee = noAssignee + filter.NoLabels = noLabels + + // Priority range + if cmd.Flags().Changed("priority-min") { + filter.PriorityMin = &priorityMin + } + if cmd.Flags().Changed("priority-max") { + filter.PriorityMax = &priorityMax + } + + includeInfra, _ := cmd.Flags().GetBool("include-infra") + + return filter, groupBy, issueType, includeInfra, nil +} + +type countBackend interface { + CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) + CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) +} + +func executeCount(ctx context.Context, backend countBackend, filter types.IssueFilter, groupBy string) error { + if groupBy == "" { + count, err := backend.CountIssues(ctx, "", filter) if err != nil { return HandleErrorRespectJSON("%v", err) } - - type GroupCount struct { - Group string `json:"group"` - Count int `json:"count"` - } - - groups := make([]GroupCount, 0, len(counts)) - for group, count := range counts { - groups = append(groups, GroupCount{Group: group, Count: count}) - } - - // --by-label buckets are not mutually exclusive, so use CountIssues for the total - // to avoid double-counting multi-label issues. - total, err := store.CountIssues(ctx, "", filter) - if err != nil { - return HandleErrorRespectJSON("%v", err) - } - - slices.SortFunc(groups, func(a, b GroupCount) int { - return cmp.Compare(a.Group, b.Group) - }) - if jsonOutput { return outputJSON(struct { - Total int64 `json:"total"` - Groups []GroupCount `json:"groups"` - }{ - Total: total, - Groups: groups, - }) - } - fmt.Printf("Total: %d\n\n", total) - for _, g := range groups { - fmt.Printf("%s: %d\n", g.Group, g.Count) + Count int64 `json:"count"` + }{Count: count}) } + fmt.Println(count) return nil - }, + } + + counts, err := backend.CountIssuesByGroup(ctx, filter, groupBy) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + type GroupCount struct { + Group string `json:"group"` + Count int `json:"count"` + } + + groups := make([]GroupCount, 0, len(counts)) + for group, count := range counts { + groups = append(groups, GroupCount{Group: group, Count: count}) + } + + // --by-label buckets are not mutually exclusive, so use CountIssues for the total + // to avoid double-counting multi-label issues. + total, err := backend.CountIssues(ctx, "", filter) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + slices.SortFunc(groups, func(a, b GroupCount) int { + return cmp.Compare(a.Group, b.Group) + }) + + if jsonOutput { + return outputJSON(struct { + Total int64 `json:"total"` + Groups []GroupCount `json:"groups"` + }{ + Total: total, + Groups: groups, + }) + } + fmt.Printf("Total: %d\n\n", total) + for _, g := range groups { + fmt.Printf("%s: %d\n", g.Group, g.Count) + } + return nil } // applyCountIncludeInfra switches the count filter to the wisps-inclusive diff --git a/cmd/bd/count_proxied_integration_test.go b/cmd/bd/count_proxied_integration_test.go new file mode 100644 index 000000000..5acd5bbf0 --- /dev/null +++ b/cmd/bd/count_proxied_integration_test.go @@ -0,0 +1,623 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + "sync" + "testing" +) + +func TestProxiedServerCount(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "cnt") + + // Seed the same fixture set as TestEmbeddedCount so counts line up with the + // proxied list cardinality parity checks below. + bdProxiedCreate(t, bd, p.dir, "Count bug one", "--type", "bug", "--priority", "1", "--assignee", "alice") + bdProxiedCreate(t, bd, p.dir, "Count bug two", "--type", "bug", "--priority", "2", "--assignee", "bob", "--description", "has a description") + bdProxiedCreate(t, bd, p.dir, "Count task one", "--type", "task", "--priority", "3", "--assignee", "alice") + bdProxiedCreate(t, bd, p.dir, "Count feature one", "--type", "feature", "--priority", "1") + closedIssue := bdProxiedCreate(t, bd, p.dir, "Count closed one", "--type", "task", "--priority", "2", "--assignee", "alice") + // --force: closedIssue is assigned to alice, and the close-authority guard + // refuses a cross-actor close (test actor != alice) without it. + if out, err := bdProxiedRun(t, bd, p.dir, "close", closedIssue.ID, "--force"); err != nil { + t.Fatalf("close %s: %v\n%s", closedIssue.ID, err, out) + } + bdProxiedCreate(t, bd, p.dir, "Count labeled", "--type", "task", "--label", "frontend", "--label", "urgent") + bdProxiedCreate(t, bd, p.dir, "Count labeled two", "--type", "task", "--label", "backend") + bdProxiedCreate(t, bd, p.dir, "Count notes issue", "--type", "task", "--description", "notes keyword here") + + // countInt runs "count " and parses the plain integer stdout. + countInt := func(t *testing.T, args ...string) int { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"count"}, args...)...) + if err != nil { + t.Fatalf("count %v: %v\n%s", args, err, out) + } + n, err := strconv.Atoi(strings.TrimSpace(string(out))) + if err != nil { + t.Fatalf("parse count output %q: %v", out, err) + } + return n + } + + // countJSON runs "count --json " and parses the object. + countJSON := func(t *testing.T, args ...string) map[string]interface{} { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"count", "--json"}, args...)...) + if err != nil { + t.Fatalf("count --json %v: %v\n%s", args, err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal count JSON %v: %v\n%s", args, err, out) + } + return m + } + + countJSONInt := func(t *testing.T, args ...string) int { + t.Helper() + m := countJSON(t, args...) + v, ok := m["count"].(float64) + if !ok { + t.Fatalf("count JSON missing numeric 'count': %v", m) + } + return int(v) + } + + // listCount returns the cardinality of "list --all --limit 0 ", + // the durable-only tier that "count" (without --include-infra) counts. + listCount := func(filters ...string) int { + return len(bdProxiedListJSON(t, bd, p, append([]string{"--all", "--limit", "0"}, filters...)...)) + } + + // group names present in a "count --by-* --json" result. + groupNames := func(t *testing.T, byFlag string) map[string]int { + t.Helper() + m := countJSON(t, byFlag) + groups, ok := m["groups"].([]interface{}) + if !ok || len(groups) == 0 { + t.Fatalf("expected groups array for %s: %v", byFlag, m) + } + names := make(map[string]int) + for _, g := range groups { + gm := g.(map[string]interface{}) + names[gm["group"].(string)] = int(gm["count"].(float64)) + } + return names + } + + // ===== Basic count ===== + + t.Run("basic_count_no_filters", func(t *testing.T) { + got := countInt(t) + if want := listCount(); got != want { + t.Errorf("count = %d, want %d (list --all cardinality)", got, want) + } + if got == 0 { + t.Error("expected non-zero count") + } + }) + + // ===== Status filter ===== + + t.Run("filter_by_status_open", func(t *testing.T) { + if got, want := countJSONInt(t, "--status", "open"), listCount("--status", "open"); got != want { + t.Errorf("count --status open = %d, want %d", got, want) + } + }) + + t.Run("filter_by_status_closed", func(t *testing.T) { + got := countJSONInt(t, "--status", "closed") + if want := listCount("--status", "closed"); got != want { + t.Errorf("count --status closed = %d, want %d", got, want) + } + if got < 1 { + t.Errorf("expected at least 1 closed issue, got %d", got) + } + }) + + // ===== Priority filter ===== + + t.Run("filter_by_priority", func(t *testing.T) { + got := countJSONInt(t, "--priority", "1") + if want := listCount("--priority-min", "1", "--priority-max", "1"); got != want { + t.Errorf("count --priority 1 = %d, want %d", got, want) + } + }) + + // ===== Assignee filter ===== + + t.Run("filter_by_assignee", func(t *testing.T) { + got := countJSONInt(t, "--assignee", "alice") + if want := listCount("--assignee", "alice"); got != want { + t.Errorf("count --assignee alice = %d, want %d", got, want) + } + if got < 3 { + t.Errorf("expected at least 3 issues assigned to alice, got %d", got) + } + }) + + // ===== Type filter ===== + + t.Run("filter_by_type", func(t *testing.T) { + got := countJSONInt(t, "--type", "bug") + if want := listCount("--type", "bug"); got != want { + t.Errorf("count --type bug = %d, want %d", got, want) + } + }) + + // ===== Label filter (AND) ===== + + t.Run("filter_by_label_and", func(t *testing.T) { + got := countJSONInt(t, "--label", "frontend", "--label", "urgent") + if want := listCount("--label", "frontend", "--label", "urgent"); got != want { + t.Errorf("count --label frontend --label urgent = %d, want %d", got, want) + } + }) + + // ===== Label filter (OR) ===== + + t.Run("filter_by_label_any", func(t *testing.T) { + got := countJSONInt(t, "--label-any", "frontend", "--label-any", "backend") + if want := listCount("--label-any", "frontend", "--label-any", "backend"); got != want { + t.Errorf("count --label-any frontend backend = %d, want %d", got, want) + } + }) + + // ===== Title filter ===== + + t.Run("filter_by_title", func(t *testing.T) { + got := countJSONInt(t, "--title", "bug") + if want := listCount("--title", "bug"); got != want { + t.Errorf("count --title bug = %d, want %d", got, want) + } + }) + + // ===== Title-contains ===== + + t.Run("filter_by_title_contains", func(t *testing.T) { + got := countJSONInt(t, "--title-contains", "feature") + if want := listCount("--title-contains", "feature"); got != want { + t.Errorf("count --title-contains feature = %d, want %d", got, want) + } + }) + + // ===== Desc-contains ===== + + t.Run("filter_by_desc_contains", func(t *testing.T) { + got := countJSONInt(t, "--desc-contains", "notes keyword") + if want := listCount("--desc-contains", "notes keyword"); got != want { + t.Errorf("count --desc-contains 'notes keyword' = %d, want %d", got, want) + } + }) + + // ===== Date range filters ===== + + t.Run("filter_by_created_after", func(t *testing.T) { + got := countJSONInt(t, "--created-after", "2000-01-01") + if want := listCount(); got != want { + t.Errorf("count --created-after 2000-01-01 = %d, want %d (all durable)", got, want) + } + }) + + t.Run("filter_by_created_before", func(t *testing.T) { + if got := countJSONInt(t, "--created-before", "2000-01-01"); got != 0 { + t.Errorf("expected 0 issues created before 2000-01-01, got %d", got) + } + }) + + t.Run("filter_by_updated_after", func(t *testing.T) { + got := countJSONInt(t, "--updated-after", "2000-01-01") + if want := listCount(); got != want { + t.Errorf("count --updated-after 2000-01-01 = %d, want %d (all durable)", got, want) + } + }) + + t.Run("filter_by_closed_after", func(t *testing.T) { + got := countJSONInt(t, "--closed-after", "2000-01-01") + if want := listCount("--status", "closed"); got != want { + t.Errorf("count --closed-after 2000-01-01 = %d, want %d (closed issues)", got, want) + } + if got < 1 { + t.Errorf("expected at least 1 closed issue after 2000-01-01, got %d", got) + } + }) + + // ===== Empty description filter ===== + + t.Run("filter_empty_description", func(t *testing.T) { + got := countJSONInt(t, "--empty-description") + if want := listCount("--empty-description"); got != want { + t.Errorf("count --empty-description = %d, want %d", got, want) + } + if got < 1 { + t.Errorf("expected at least 1 issue with empty description, got %d", got) + } + }) + + // ===== No assignee filter ===== + + t.Run("filter_no_assignee", func(t *testing.T) { + got := countJSONInt(t, "--no-assignee") + if want := listCount("--no-assignee"); got != want { + t.Errorf("count --no-assignee = %d, want %d", got, want) + } + if got < 1 { + t.Errorf("expected at least 1 issue with no assignee, got %d", got) + } + }) + + // ===== No labels filter ===== + + t.Run("filter_no_labels", func(t *testing.T) { + got := countJSONInt(t, "--no-labels") + if want := listCount("--no-labels"); got != want { + t.Errorf("count --no-labels = %d, want %d", got, want) + } + if got < 1 { + t.Errorf("expected at least 1 issue with no labels, got %d", got) + } + }) + + // ===== Priority range filter ===== + + t.Run("filter_priority_min_max", func(t *testing.T) { + got := countJSONInt(t, "--priority-min", "1", "--priority-max", "2") + if want := listCount("--priority-min", "1", "--priority-max", "2"); got != want { + t.Errorf("count --priority-min 1 --priority-max 2 = %d, want %d", got, want) + } + if got < 3 { + t.Errorf("expected at least 3 issues with priority 1-2, got %d", got) + } + }) + + // ===== Group by status ===== + + t.Run("group_by_status", func(t *testing.T) { + m := countJSON(t, "--by-status") + total := int(m["total"].(float64)) + if want := listCount(); total != want { + t.Errorf("by-status total = %d, want %d", total, want) + } + names := groupNames(t, "--by-status") + // by-status buckets are mutually exclusive, so they sum to the total. + sum := 0 + for _, c := range names { + sum += c + } + if sum != total { + t.Errorf("by-status group sum %d != total %d", sum, total) + } + if _, ok := names["open"]; !ok { + t.Error("expected 'open' group") + } + if _, ok := names["closed"]; !ok { + t.Error("expected 'closed' group") + } + }) + + // ===== Group by priority ===== + + t.Run("group_by_priority", func(t *testing.T) { + names := groupNames(t, "--by-priority") + if _, ok := names["P1"]; !ok { + t.Errorf("expected P1 group, got %v", names) + } + }) + + // ===== Group by type ===== + + t.Run("group_by_type", func(t *testing.T) { + names := groupNames(t, "--by-type") + if _, ok := names["bug"]; !ok { + t.Error("expected 'bug' group") + } + if _, ok := names["task"]; !ok { + t.Error("expected 'task' group") + } + }) + + // ===== Group by assignee ===== + + t.Run("group_by_assignee", func(t *testing.T) { + names := groupNames(t, "--by-assignee") + if _, ok := names["alice"]; !ok { + t.Error("expected 'alice' group") + } + if _, ok := names["(unassigned)"]; !ok { + t.Errorf("expected '(unassigned)' group, got %v", names) + } + }) + + // ===== Group by label ===== + + t.Run("group_by_label", func(t *testing.T) { + names := groupNames(t, "--by-label") + if _, ok := names["frontend"]; !ok { + t.Error("expected 'frontend' label group") + } + if _, ok := names["backend"]; !ok { + t.Error("expected 'backend' label group") + } + }) + + // ===== JSON plain count ===== + + t.Run("json_plain_count", func(t *testing.T) { + m := countJSON(t) + if _, ok := m["count"]; !ok { + t.Errorf("expected 'count' key in JSON output: %v", m) + } + }) + + // ===== JSON grouped count ===== + + t.Run("json_grouped_count", func(t *testing.T) { + m := countJSON(t, "--by-status") + if _, ok := m["total"]; !ok { + t.Error("expected 'total' key in grouped JSON output") + } + if _, ok := m["groups"]; !ok { + t.Error("expected 'groups' key in grouped JSON output") + } + }) + + // ===== Error: multiple --by-* flags ===== + + t.Run("error_multiple_by_flags", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "count", "--by-status", "--by-priority") + if err == nil { + t.Fatalf("expected error, got success: %s", out) + } + if !strings.Contains(string(out), "only one") { + t.Errorf("expected 'only one' error, got: %s", out) + } + }) + + // ===== Combined filters ===== + + t.Run("combined_filters", func(t *testing.T) { + got := countJSONInt(t, "--status", "open", "--type", "bug", "--assignee", "alice") + if want := listCount("--status", "open", "--type", "bug", "--assignee", "alice"); got != want { + t.Errorf("count open+bug+alice = %d, want %d", got, want) + } + if got < 1 { + t.Errorf("expected at least 1 open bug assigned to alice, got %d", got) + } + }) + + // ===== Plain text output ===== + + t.Run("plain_text_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "count", "--status", "open") + if err != nil { + t.Fatalf("count --status open: %v\n%s", err, out) + } + s := strings.TrimSpace(string(out)) + if len(s) == 0 { + t.Error("expected non-empty output") + } + for _, c := range s { + if c < '0' || c > '9' { + t.Errorf("expected plain integer, got: %q", s) + break + } + } + }) + + t.Run("plain_text_grouped_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "count", "--by-status") + if err != nil { + t.Fatalf("count --by-status: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "Total:") { + t.Errorf("expected 'Total:' in grouped text output, got: %s", s) + } + if !strings.Contains(s, "open:") { + t.Errorf("expected 'open:' in grouped text output, got: %s", s) + } + }) + + // ===== ID filter ===== + + t.Run("filter_by_id", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "ID filter target", "--type", "task") + if got := countJSONInt(t, "--id", issue.ID); got != 1 { + t.Errorf("expected exactly 1 issue matching ID, got %d", got) + } + }) +} + +// TestProxiedServerCountIncludeInfra is the proxied-server parity for GH#4387: +// `bd count --include-infra ` must return exactly the cardinality of +// `bd list --include-infra --all`, including the wisps tier (no_history +// + ephemeral beads). Without the flag, count keeps durable-only semantics. +func TestProxiedServerCountIncludeInfra(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "cci") + + // Durable issues tier. + bdProxiedCreate(t, bd, p.dir, "Infra durable task one", "--type", "task") + bdProxiedCreate(t, bd, p.dir, "Infra durable task two", "--type", "task") + bdProxiedCreate(t, bd, p.dir, "Infra durable bug", "--type", "bug") + closedIssue := bdProxiedCreate(t, bd, p.dir, "Infra durable task closed", "--type", "task") + if out, err := bdProxiedRun(t, bd, p.dir, "close", closedIssue.ID, "--force"); err != nil { + t.Fatalf("close %s: %v\n%s", closedIssue.ID, err, out) + } + // Wisps tier: no_history beads are durable work that list --include-infra + // returns; ephemeral beads are GC-eligible wisps. + bdProxiedCreate(t, bd, p.dir, "Infra nohistory task one", "--type", "task", "--no-history") + bdProxiedCreate(t, bd, p.dir, "Infra nohistory task two", "--type", "task", "--no-history") + bdProxiedCreate(t, bd, p.dir, "Infra ephemeral task", "--type", "task", "--ephemeral") + + countOf := func(t *testing.T, args ...string) int { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"count", "--json"}, args...)...) + if err != nil { + t.Fatalf("count --json %v: %v\n%s", args, err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal count %v: %v\n%s", args, err, out) + } + return int(m["count"].(float64)) + } + listCardinality := func(filters ...string) int { + full := append([]string{"--include-infra", "--all", "--limit", "0"}, filters...) + return len(bdProxiedListJSON(t, bd, p, full...)) + } + + t.Run("default_stays_durable_only", func(t *testing.T) { + if got := countOf(t, "--type", "task"); got != 3 { + t.Errorf("count --type task = %d, want 3 (durable tasks only)", got) + } + }) + + t.Run("include_infra_counts_wisps_tier", func(t *testing.T) { + // 3 durable tasks + 2 no_history tasks + 1 ephemeral task. + if got := countOf(t, "--include-infra", "--type", "task"); got != 6 { + t.Errorf("count --include-infra --type task = %d, want 6", got) + } + }) + + t.Run("include_infra_matches_list_cardinality", func(t *testing.T) { + for _, filters := range [][]string{ + nil, + {"--type", "task"}, + {"--type", "bug"}, + {"--status", "open"}, + {"--status", "closed"}, + } { + want := listCardinality(filters...) + got := countOf(t, append([]string{"--include-infra"}, filters...)...) + if got != want { + t.Errorf("count --include-infra %v = %d, but list --include-infra --all %v returned %d rows", filters, got, filters, want) + } + } + }) + + t.Run("include_infra_grouped_by_type", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "count", "--json", "--include-infra", "--by-type") + if err != nil { + t.Fatalf("count --include-infra --by-type: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + total := int(m["total"].(float64)) + if want := listCardinality(); total != want { + t.Errorf("count --include-infra --by-type total = %d, want %d", total, want) + } + byType := make(map[string]int) + for _, g := range m["groups"].([]interface{}) { + gm := g.(map[string]interface{}) + byType[gm["group"].(string)] = int(gm["count"].(float64)) + } + if byType["task"] != 6 { + t.Errorf("grouped task count = %d, want 6", byType["task"]) + } + if byType["bug"] != 1 { + t.Errorf("grouped bug count = %d, want 1", byType["bug"]) + } + }) + + t.Run("grouped_without_flag_stays_durable_only", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "count", "--json", "--by-type") + if err != nil { + t.Fatalf("count --by-type: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + for _, g := range m["groups"].([]interface{}) { + gm := g.(map[string]interface{}) + if gm["group"] == "task" { + if got := int(gm["count"].(float64)); got != 3 { + t.Errorf("count --by-type task = %d, want 3 (durable only)", got) + } + } + } + }) +} + +// TestProxiedServerCountConcurrent exercises count operations concurrently +// through the proxied server. +func TestProxiedServerCountConcurrent(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "ccc") + + for i := 0; i < 20; i++ { + args := []string{fmt.Sprintf("concurrent-count-%d", i), "--type", "task"} + if i%2 == 0 { + args = append(args, "--assignee", "alice") + } else { + args = append(args, "--assignee", "bob") + } + if i%3 == 0 { + args = append(args, "--priority", "1") + } + bdProxiedCreate(t, bd, p.dir, args...) + } + + const numWorkers = 8 + + type workerResult struct { + worker int + err error + } + + results := make([]workerResult, numWorkers) + var wg sync.WaitGroup + wg.Add(numWorkers) + + queries := [][]string{ + {}, + {"--status", "open"}, + {"--assignee", "alice"}, + {"--type", "task"}, + {"--by-status"}, + {"--by-assignee"}, + {"--by-priority"}, + {"--priority", "1"}, + } + + for w := 0; w < numWorkers; w++ { + go func(worker int) { + defer wg.Done() + r := workerResult{worker: worker} + q := queries[worker%len(queries)] + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"count", "--json"}, q...)...) + if err != nil { + r.err = fmt.Errorf("worker %d count %v: %v\n%s", worker, q, err, out) + results[worker] = r + return + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + r.err = fmt.Errorf("worker %d: JSON parse: %v\n%s", worker, err, out) + } + results[worker] = r + }(w) + } + wg.Wait() + + for _, r := range results { + if r.err != nil && !strings.Contains(r.err.Error(), "one writer at a time") { + t.Errorf("worker %d failed: %v", r.worker, r.err) + } + } +} diff --git a/cmd/bd/count_proxied_server.go b/cmd/bd/count_proxied_server.go new file mode 100644 index 000000000..e977f3212 --- /dev/null +++ b/cmd/bd/count_proxied_server.go @@ -0,0 +1,32 @@ +package main + +import ( + "context" + + "github.com/spf13/cobra" +) + +func runCountProxiedServer(cmd *cobra.Command, ctx context.Context) error { + filter, groupBy, issueType, includeInfra, err := parseCountFilter(cmd) + if err != nil { + return err + } + + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + if includeInfra { + cfg, err := loadProxiedListFilterConfig(ctx, uw) + if err != nil { + return HandleError("%v", err) + } + applyCountIncludeInfra(&filter, issueType, cfg) + } else { + filter.SkipWisps = true + } + + return executeCount(ctx, uw.IssueUseCase(), filter, groupBy) +} diff --git a/cmd/bd/create_proxied_server.go b/cmd/bd/create_proxied_server.go index 7bb95e0c0..7bb41629f 100644 --- a/cmd/bd/create_proxied_server.go +++ b/cmd/bd/create_proxied_server.go @@ -138,7 +138,7 @@ func runCreateProxiedSingle(_ *cobra.Command, ctx context.Context, in createInpu var result domain.CreateIssueResult var createErr error - if issue.Ephemeral { + if issue.Ephemeral || issue.NoHistory { result, createErr = uw.IssueUseCase().CreateWisp(ctx, params, in.createdBy) } else { result, createErr = uw.IssueUseCase().CreateIssue(ctx, params, in.createdBy) @@ -302,7 +302,7 @@ func runCreateProxiedMarkdown(_ *cobra.Command, ctx context.Context, in createIn var result domain.CreateIssuesResult var createErr error - if in.ephemeral { + if in.ephemeral || in.noHistory { result, createErr = uw.IssueUseCase().CreateWisps(ctx, paramsList, in.createdBy) } else { result, createErr = uw.IssueUseCase().CreateIssues(ctx, paramsList, in.createdBy) diff --git a/cmd/bd/defer.go b/cmd/bd/defer.go index 08be14070..b9af08851 100644 --- a/cmd/bd/defer.go +++ b/cmd/bd/defer.go @@ -35,11 +35,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("defer is not supported in proxied-server mode") - } - CheckReadonly("defer") - evt := metrics.NewCommandEvent("defer") defer func() { if c := metrics.Global(); c != nil { @@ -67,6 +62,12 @@ Examples: return HandleError("reason cannot be empty") } + CheckReadonly("defer") + + if usesProxiedServer() { + return runDeferProxiedServer(rootCtx, args, deferUntil, reason) + } + ctx := rootCtx _, err := utils.ResolvePartialIDs(ctx, store, args) diff --git a/cmd/bd/defer_proxied_integration_test.go b/cmd/bd/defer_proxied_integration_test.go new file mode 100644 index 000000000..44b5b1b79 --- /dev/null +++ b/cmd/bd/defer_proxied_integration_test.go @@ -0,0 +1,155 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func TestProxiedServerDeferUndefer(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "dfr") + + showStatus := func(t *testing.T, id string) (string, interface{}) { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, "show", id, "--json") + if err != nil { + t.Fatalf("show %s: %v\n%s", id, err, out) + } + var arr []map[string]interface{} + if err := json.Unmarshal(out, &arr); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if len(arr) == 0 { + t.Fatalf("show returned nothing for %s", id) + } + return arr[0]["status"].(string), arr[0]["defer_until"] + } + + t.Run("defer_then_undefer", func(t *testing.T) { + a := bdProxiedCreate(t, bd, p.dir, "Defer target", "--type", "task") + + out, err := bdProxiedRun(t, bd, p.dir, "defer", a.ID, "--until", "tomorrow", "--reason", "waiting on X", "--json") + if err != nil { + t.Fatalf("defer: %v\n%s", err, out) + } + var deferred []map[string]interface{} + if err := json.Unmarshal(out, &deferred); err != nil { + t.Fatalf("unmarshal defer: %v\n%s", err, out) + } + if len(deferred) != 1 || deferred[0]["status"] != string(types.StatusDeferred) { + t.Fatalf("expected 1 deferred issue, got %v", deferred) + } + if deferred[0]["defer_until"] == nil { + t.Errorf("expected defer_until to be set") + } + + status, deferUntil := showStatus(t, a.ID) + if status != string(types.StatusDeferred) { + t.Errorf("status = %s, want deferred", status) + } + if deferUntil == nil { + t.Errorf("defer_until should be set after defer") + } + + // Undefer restores to open and clears defer_until. + if out, err := bdProxiedRun(t, bd, p.dir, "undefer", a.ID); err != nil { + t.Fatalf("undefer: %v\n%s", err, out) + } + status, deferUntil = showStatus(t, a.ID) + if status != string(types.StatusOpen) { + t.Errorf("status = %s, want open after undefer", status) + } + if deferUntil != nil { + t.Errorf("defer_until should be cleared after undefer, got %v", deferUntil) + } + }) + + t.Run("deferred_excluded_from_ready", func(t *testing.T) { + b := bdProxiedCreate(t, bd, p.dir, "Ready-then-deferred", "--type", "task", "--priority", "1") + if out, err := bdProxiedRun(t, bd, p.dir, "defer", b.ID); err != nil { + t.Fatalf("defer: %v\n%s", err, out) + } + ready := bdProxiedListJSON(t, bd, p, "--ready") + for _, iss := range ready { + if iss.ID == b.ID { + t.Errorf("deferred issue %s should not appear in ready", b.ID) + } + } + }) + + t.Run("undefer_nondeferred_errors", func(t *testing.T) { + c := bdProxiedCreate(t, bd, p.dir, "Open issue", "--type", "task") + stdout, stderr, _ := bdProxiedRunBuffers(t, bd, p.dir, "undefer", c.ID) + if !strings.Contains(stdout+stderr, "is not deferred") { + t.Errorf("expected 'is not deferred' message, got stdout=%q stderr=%q", stdout, stderr) + } + }) + + t.Run("defer_is_idempotent", func(t *testing.T) { + d := bdProxiedCreate(t, bd, p.dir, "Idempotent defer", "--type", "task") + if out, err := bdProxiedRun(t, bd, p.dir, "defer", d.ID); err != nil { + t.Fatalf("first defer: %v\n%s", err, out) + } + // Second defer on an already-deferred issue must not error (ClientFoundRows fix). + if out, err := bdProxiedRun(t, bd, p.dir, "defer", d.ID, "--json"); err != nil { + t.Fatalf("second defer errored (no-op update regression): %v\n%s", err, out) + } + }) + + t.Run("defer_multiple", func(t *testing.T) { + e := bdProxiedCreate(t, bd, p.dir, "Defer multi 1", "--type", "task") + f := bdProxiedCreate(t, bd, p.dir, "Defer multi 2", "--type", "task") + + out, err := bdProxiedRun(t, bd, p.dir, "defer", e.ID, f.ID) + if err != nil { + t.Fatalf("defer multiple: %v\n%s", err, out) + } + if !strings.Contains(string(out), e.ID) || !strings.Contains(string(out), f.ID) { + t.Errorf("expected both IDs in defer output, got:\n%s", out) + } + for _, id := range []string{e.ID, f.ID} { + if status, _ := showStatus(t, id); status != string(types.StatusDeferred) { + t.Errorf("status of %s = %s, want deferred", id, status) + } + } + }) + + t.Run("undefer_multiple", func(t *testing.T) { + g := bdProxiedCreate(t, bd, p.dir, "Undefer multi 1", "--type", "task") + h := bdProxiedCreate(t, bd, p.dir, "Undefer multi 2", "--type", "task") + if out, err := bdProxiedRun(t, bd, p.dir, "defer", g.ID, h.ID); err != nil { + t.Fatalf("defer: %v\n%s", err, out) + } + + out, err := bdProxiedRun(t, bd, p.dir, "undefer", g.ID, h.ID) + if err != nil { + t.Fatalf("undefer multiple: %v\n%s", err, out) + } + if !strings.Contains(string(out), g.ID) || !strings.Contains(string(out), h.ID) { + t.Errorf("expected both IDs in undefer output, got:\n%s", out) + } + for _, id := range []string{g.ID, h.ID} { + if status, _ := showStatus(t, id); status != string(types.StatusOpen) { + t.Errorf("status of %s = %s, want open after undefer", id, status) + } + } + }) + + t.Run("defer_reason_appended_to_notes", func(t *testing.T) { + i := bdProxiedCreate(t, bd, p.dir, "Defer with reason", "--type", "task") + if out, err := bdProxiedRun(t, bd, p.dir, "defer", i.ID, "--reason", "waiting on API access"); err != nil { + t.Fatalf("defer --reason: %v\n%s", err, out) + } + iss := bdProxiedShow(t, bd, p.dir, i.ID) + if !strings.Contains(iss.Notes, "waiting on API access") { + t.Errorf("expected defer reason appended to notes, got notes=%q", iss.Notes) + } + }) +} diff --git a/cmd/bd/defer_proxied_server.go b/cmd/bd/defer_proxied_server.go new file mode 100644 index 000000000..5b3719d37 --- /dev/null +++ b/cmd/bd/defer_proxied_server.go @@ -0,0 +1,163 @@ +package main + +import ( + "context" + "fmt" + "os" + "time" + + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/ui" +) + +type deferProxiedResult struct { + issues []*types.Issue + errs []string +} + +func proxiedUpdateByID(ctx context.Context, uw uow.UnitOfWork, id string, isWisp bool, updates map[string]any) error { + if isWisp { + return uw.IssueUseCase().UpdateWisp(ctx, id, updates, actor) + } + return uw.IssueUseCase().UpdateIssue(ctx, id, updates, actor) +} + +func proxiedGetByID(ctx context.Context, uw uow.UnitOfWork, id string, isWisp bool) *types.Issue { + if isWisp { + iss, _ := uw.IssueUseCase().GetWisp(ctx, id) + return iss + } + iss, _ := uw.IssueUseCase().GetIssue(ctx, id) + return iss +} + +func runDeferProxiedServer(ctx context.Context, args []string, deferUntil *time.Time, reason string) error { + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (deferProxiedResult, string, error) { + var r deferProxiedResult + for _, id := range args { + issue, isWisp := proxiedResolveIssueOrWisp(ctx, uw, id) + if issue == nil { + r.errs = append(r.errs, fmt.Sprintf("Error resolving %s: not found", id)) + continue + } + fullID := issue.ID + + updates := map[string]interface{}{ + "status": string(types.StatusDeferred), + } + if deferUntil != nil { + updates["defer_until"] = *deferUntil + } + if reason != "" { + notes := issue.Notes + if notes != "" { + notes += "\n" + } + updates["notes"] = notes + reason + } + + if uerr := proxiedUpdateByID(ctx, uw, fullID, isWisp, updates); uerr != nil { + r.errs = append(r.errs, fmt.Sprintf("Error deferring %s: %v", fullID, uerr)) + continue + } + if updated := proxiedGetByID(ctx, uw, fullID, isWisp); updated != nil { + r.issues = append(r.issues, updated) + } + } + if len(r.issues) == 0 { + return r, "", nil + } + return r, "bd: defer", nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + for _, e := range res.errs { + fmt.Fprintln(os.Stderr, e) + } + + if jsonOutput { + if len(res.issues) > 0 { + if e := outputJSON(res.issues); e != nil { + return e + } + } + } else { + for _, iss := range res.issues { + fmt.Printf("%s Deferred %s\n", ui.RenderAccent("*"), iss.ID) + } + } + + if len(args) > 0 { + commandDidWrite.Store(true) + } + return nil +} + +func runUndeferProxiedServer(ctx context.Context, args []string) error { + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (deferProxiedResult, string, error) { + var r deferProxiedResult + for _, id := range args { + issue, isWisp := proxiedResolveIssueOrWisp(ctx, uw, id) + if issue == nil { + r.errs = append(r.errs, fmt.Sprintf("Error getting %s: not found", id)) + continue + } + fullID := issue.ID + if issue.Status != types.StatusDeferred { + r.errs = append(r.errs, fmt.Sprintf("%s is not deferred (status: %s)", fullID, string(issue.Status))) + continue + } + + updates := map[string]interface{}{ + "status": string(types.StatusOpen), + "defer_until": nil, + } + if uerr := proxiedUpdateByID(ctx, uw, fullID, isWisp, updates); uerr != nil { + r.errs = append(r.errs, fmt.Sprintf("Error undeferring %s: %v", fullID, uerr)) + continue + } + if updated := proxiedGetByID(ctx, uw, fullID, isWisp); updated != nil { + r.issues = append(r.issues, updated) + } + } + if len(r.issues) == 0 { + return r, "", nil + } + return r, "bd: undefer", nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + for _, e := range res.errs { + fmt.Fprintln(os.Stderr, e) + } + + if jsonOutput { + if len(res.issues) > 0 { + if e := outputJSON(res.issues); e != nil { + return e + } + } + } else { + for _, iss := range res.issues { + fmt.Printf("%s Undeferred %s (now open)\n", ui.RenderPass("*"), iss.ID) + } + } + + if len(args) > 0 { + commandDidWrite.Store(true) + } + return nil +} diff --git a/cmd/bd/duplicates.go b/cmd/bd/duplicates.go index f00eba6c7..32c6417c0 100644 --- a/cmd/bd/duplicates.go +++ b/cmd/bd/duplicates.go @@ -28,9 +28,6 @@ Example: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, _ []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("duplicates is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("duplicates") defer func() { if c := metrics.Global(); c != nil { @@ -40,6 +37,11 @@ Example: autoMerge, _ := cmd.Flags().GetBool("auto-merge") dryRun, _ := cmd.Flags().GetBool("dry-run") + + if usesProxiedServer() { + return runDuplicatesProxiedServer(rootCtx, autoMerge, dryRun) + } + if autoMerge && !dryRun { CheckReadonly("duplicates --auto-merge") } @@ -49,106 +51,140 @@ Example: if err != nil { return HandleError("fetching issues: %v", err) } - openIssues := make([]*types.Issue, 0, len(allIssues)) - for _, issue := range allIssues { - if issue.Status != types.StatusClosed { - openIssues = append(openIssues, issue) - } - } - duplicateGroups := findDuplicateGroups(openIssues) + duplicateGroups := findDuplicateGroups(openIssuesOf(allIssues)) if len(duplicateGroups) == 0 { - if !jsonOutput { - fmt.Println("No duplicates found!") - return nil - } - return outputJSON(map[string]interface{}{ - "duplicate_groups": 0, - "groups": []interface{}{}, - }) + return outputNoDuplicates() } refCounts := countReferences(allIssues) - structuralScores := countStructuralRelationships(duplicateGroups) - var mergeCommands []string - var mergeResults []map[string]interface{} - for _, group := range duplicateGroups { - target := chooseMergeTarget(group, refCounts, structuralScores) - sources := make([]string, 0, len(group)-1) - for _, issue := range group { - if issue.ID != target.ID { - sources = append(sources, issue.ID) - } - } - cmd := fmt.Sprintf("# Duplicate: %s (same content as %s)\n# Suggested action: bd close %s && bd dep add %s %s --type related", - strings.Join(sources, " "), - target.ID, - strings.Join(sources, " "), - strings.Join(sources, " "), - target.ID) - mergeCommands = append(mergeCommands, cmd) + depCounts, _ := store.GetDependencyCounts(ctx, collectDuplicateGroupIDs(duplicateGroups)) + structuralScores := buildStructuralScores(duplicateGroups, depCounts) - if autoMerge || dryRun { - if !dryRun { - result := performMerge(target.ID, sources) - mergeResults = append(mergeResults, result) - } - } - } + var mergeResults []map[string]interface{} if autoMerge && !dryRun { + mergeResults = executeDuplicateMerges(duplicateGroups, refCounts, structuralScores) commandDidWrite.Store(true) } - if jsonOutput { - output := map[string]interface{}{ - "duplicate_groups": len(duplicateGroups), - "groups": formatDuplicateGroupsJSON(duplicateGroups, refCounts, structuralScores), - } - if autoMerge || dryRun { - output["merge_commands"] = mergeCommands - if autoMerge && !dryRun { - output["merge_results"] = mergeResults - } - } - return outputJSON(output) - } - fmt.Printf("%s Found %d duplicate group(s):\n\n", ui.RenderWarn("🔍"), len(duplicateGroups)) - for i, group := range duplicateGroups { - target := chooseMergeTarget(group, refCounts, structuralScores) - fmt.Printf("%s Group %d: %s\n", ui.RenderAccent("━━"), i+1, group[0].Title) - for _, issue := range group { - refs := refCounts[issue.ID] - weight := 0 - if score, ok := structuralScores[issue.ID]; ok { - weight = score.dependentCount*3 + score.dependsOnCount - } - marker := " " - if issue.ID == target.ID { - marker = ui.RenderPass("→ ") - } - fmt.Printf("%s%s (%s, P%d, weight=%d, %d refs)\n", - marker, issue.ID, issue.Status, issue.Priority, weight, refs) - } - sources := make([]string, 0, len(group)-1) - for _, issue := range group { - if issue.ID != target.ID { - sources = append(sources, issue.ID) - } - } - fmt.Printf(" %s Duplicate: %s (same content as %s)\n", ui.RenderAccent("Note:"), strings.Join(sources, " "), target.ID) - fmt.Printf(" %s bd close %s && bd dep add %s %s --type related\n\n", - ui.RenderAccent("Suggested:"), strings.Join(sources, " "), strings.Join(sources, " "), target.ID) - } - if autoMerge { - if dryRun { - fmt.Printf("%s Dry run - would execute %d merge(s)\n", ui.RenderWarn("⚠"), len(mergeCommands)) - } else { - fmt.Printf("%s Merged %d group(s)\n", ui.RenderPass("✓"), len(mergeCommands)) - } - } else { - fmt.Printf("%s Run with --auto-merge to execute all suggested merges\n", ui.RenderAccent("💡")) - } - return nil + return outputDuplicates(duplicateGroups, refCounts, structuralScores, autoMerge, dryRun, mergeResults) }, } +func openIssuesOf(allIssues []*types.Issue) []*types.Issue { + openIssues := make([]*types.Issue, 0, len(allIssues)) + for _, issue := range allIssues { + if issue.Status != types.StatusClosed { + openIssues = append(openIssues, issue) + } + } + return openIssues +} + +func collectDuplicateGroupIDs(groups [][]*types.Issue) []string { + var ids []string + for _, group := range groups { + for _, issue := range group { + ids = append(ids, issue.ID) + } + } + return ids +} + +func outputNoDuplicates() error { + if !jsonOutput { + fmt.Println("No duplicates found!") + return nil + } + return outputJSON(map[string]interface{}{ + "duplicate_groups": 0, + "groups": []interface{}{}, + }) +} + +func executeDuplicateMerges(duplicateGroups [][]*types.Issue, refCounts map[string]int, structuralScores map[string]*issueScore) []map[string]interface{} { + var mergeResults []map[string]interface{} + for _, group := range duplicateGroups { + target := chooseMergeTarget(group, refCounts, structuralScores) + sources := make([]string, 0, len(group)-1) + for _, issue := range group { + if issue.ID != target.ID { + sources = append(sources, issue.ID) + } + } + mergeResults = append(mergeResults, performMerge(target.ID, sources)) + } + return mergeResults +} + +func outputDuplicates(duplicateGroups [][]*types.Issue, refCounts map[string]int, structuralScores map[string]*issueScore, autoMerge, dryRun bool, mergeResults []map[string]interface{}) error { + var mergeCommands []string + for _, group := range duplicateGroups { + target := chooseMergeTarget(group, refCounts, structuralScores) + sources := make([]string, 0, len(group)-1) + for _, issue := range group { + if issue.ID != target.ID { + sources = append(sources, issue.ID) + } + } + cmd := fmt.Sprintf("# Duplicate: %s (same content as %s)\n# Suggested action: bd close %s && bd dep add %s %s --type related", + strings.Join(sources, " "), + target.ID, + strings.Join(sources, " "), + strings.Join(sources, " "), + target.ID) + mergeCommands = append(mergeCommands, cmd) + } + + if jsonOutput { + output := map[string]interface{}{ + "duplicate_groups": len(duplicateGroups), + "groups": formatDuplicateGroupsJSON(duplicateGroups, refCounts, structuralScores), + } + if autoMerge || dryRun { + output["merge_commands"] = mergeCommands + if autoMerge && !dryRun { + output["merge_results"] = mergeResults + } + } + return outputJSON(output) + } + fmt.Printf("%s Found %d duplicate group(s):\n\n", ui.RenderWarn("🔍"), len(duplicateGroups)) + for i, group := range duplicateGroups { + target := chooseMergeTarget(group, refCounts, structuralScores) + fmt.Printf("%s Group %d: %s\n", ui.RenderAccent("━━"), i+1, group[0].Title) + for _, issue := range group { + refs := refCounts[issue.ID] + weight := 0 + if score, ok := structuralScores[issue.ID]; ok { + weight = score.dependentCount*3 + score.dependsOnCount + } + marker := " " + if issue.ID == target.ID { + marker = ui.RenderPass("→ ") + } + fmt.Printf("%s%s (%s, P%d, weight=%d, %d refs)\n", + marker, issue.ID, issue.Status, issue.Priority, weight, refs) + } + sources := make([]string, 0, len(group)-1) + for _, issue := range group { + if issue.ID != target.ID { + sources = append(sources, issue.ID) + } + } + fmt.Printf(" %s Duplicate: %s (same content as %s)\n", ui.RenderAccent("Note:"), strings.Join(sources, " "), target.ID) + fmt.Printf(" %s bd close %s && bd dep add %s %s --type related\n\n", + ui.RenderAccent("Suggested:"), strings.Join(sources, " "), strings.Join(sources, " "), target.ID) + } + if autoMerge { + if dryRun { + fmt.Printf("%s Dry run - would execute %d merge(s)\n", ui.RenderWarn("⚠"), len(mergeCommands)) + } else { + fmt.Printf("%s Merged %d group(s)\n", ui.RenderPass("✓"), len(mergeCommands)) + } + } else { + fmt.Printf("%s Run with --auto-merge to execute all suggested merges\n", ui.RenderAccent("💡")) + } + return nil +} + func init() { duplicatesCmd.Flags().Bool("auto-merge", false, "Automatically merge all duplicates") duplicatesCmd.Flags().Bool("dry-run", false, "Show what would be merged without making changes") @@ -216,32 +252,17 @@ func countReferences(issues []*types.Issue) map[string]int { return counts } -// countStructuralRelationships counts dependency relationships for issues in duplicate groups. -// Uses the efficient GetDependencyCounts batch query. -func countStructuralRelationships(groups [][]*types.Issue) map[string]*issueScore { +func buildStructuralScores(groups [][]*types.Issue, depCounts map[string]*types.DependencyCounts) map[string]*issueScore { scores := make(map[string]*issueScore) - ctx := rootCtx - - // Collect all issue IDs from all groups - var issueIDs []string for _, group := range groups { for _, issue := range group { - issueIDs = append(issueIDs, issue.ID) scores[issue.ID] = &issueScore{} } } - // Batch query for dependency counts - depCounts, err := store.GetDependencyCounts(ctx, issueIDs) - if err != nil { - // On error, return empty scores - fallback to text refs only - return scores - } - - // Populate scores from dependency counts for id, counts := range depCounts { if score, ok := scores[id]; ok { - score.dependentCount = counts.DependentCount // Issues that depend on this one (children, etc) + score.dependentCount = counts.DependentCount score.dependsOnCount = counts.DependencyCount } } diff --git a/cmd/bd/duplicates_proxied_integration_test.go b/cmd/bd/duplicates_proxied_integration_test.go new file mode 100644 index 000000000..b93869c7e --- /dev/null +++ b/cmd/bd/duplicates_proxied_integration_test.go @@ -0,0 +1,387 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "os" + "strings" + "testing" +) + +func TestProxiedServerDuplicates(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "dup") + + // Two issues with identical content form an exact-duplicate group. + a := bdProxiedCreate(t, bd, p.dir, "Fix login redirect", "--type", "bug", "--priority", "1", "--description", "Users bounce to /home after login") + b := bdProxiedCreate(t, bd, p.dir, "Fix login redirect", "--type", "bug", "--priority", "1", "--description", "Users bounce to /home after login") + // A distinct issue that must not be grouped. + bdProxiedCreate(t, bd, p.dir, "Unrelated task", "--type", "task", "--priority", "2") + + dupsJSON := func(t *testing.T, args ...string) map[string]interface{} { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"duplicates", "--json"}, args...)...) + if err != nil { + t.Fatalf("duplicates --json %v: %v\n%s", args, err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + return m + } + + t.Run("finds_exact_group", func(t *testing.T) { + var got struct { + DuplicateGroups int `json:"duplicate_groups"` + Groups []struct { + SuggestedTarget string `json:"suggested_target"` + SuggestedSources []string `json:"suggested_sources"` + Issues []struct { + ID string `json:"id"` + } `json:"issues"` + } `json:"groups"` + } + out, err := bdProxiedRun(t, bd, p.dir, "duplicates", "--json") + if err != nil { + t.Fatalf("duplicates --json: %v\n%s", err, out) + } + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if got.DuplicateGroups != 1 { + t.Fatalf("duplicate_groups = %d, want 1", got.DuplicateGroups) + } + ids := map[string]bool{} + for _, iss := range got.Groups[0].Issues { + ids[iss.ID] = true + } + if !ids[a.ID] || !ids[b.ID] { + t.Errorf("group should contain %s and %s, got %v", a.ID, b.ID, ids) + } + tgt := got.Groups[0].SuggestedTarget + if tgt != a.ID && tgt != b.ID { + t.Errorf("suggested_target %s not one of the duplicates", tgt) + } + }) + + t.Run("json_output_structure", func(t *testing.T) { + m := dupsJSON(t) + if _, ok := m["duplicate_groups"]; !ok { + t.Error("expected 'duplicate_groups' key") + } + if _, ok := m["groups"]; !ok { + t.Error("expected 'groups' key") + } + }) + + t.Run("human_readable", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "duplicates") + if err != nil { + t.Fatalf("duplicates: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "duplicate") && !strings.Contains(s, "Duplicate") && !strings.Contains(s, "No duplicates") { + t.Errorf("expected duplicate info in output: %s", s) + } + }) + + t.Run("no_duplicates_all_unique", func(t *testing.T) { + // A fresh project with only distinct issues yields zero groups. + p2 := newSharedProxiedProject(t, bd, "duq") + bdProxiedCreate(t, bd, p2.dir, "Unique 1", "--type", "task", "--description", "A") + bdProxiedCreate(t, bd, p2.dir, "Unique 2", "--type", "task", "--description", "B") + out, err := bdProxiedRun(t, bd, p2.dir, "duplicates", "--json") + if err != nil { + t.Fatalf("duplicates --json: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if groups := int(m["duplicate_groups"].(float64)); groups != 0 { + t.Errorf("expected 0 duplicate groups, got %d", groups) + } + }) + + t.Run("excludes_closed", func(t *testing.T) { + // When one of an exact-duplicate pair is closed, only the open one + // remains and no group is reported (proxied groups open issues only). + p3 := newSharedProxiedProject(t, bd, "duc") + x := bdProxiedCreate(t, bd, p3.dir, "Closed dup", "--type", "task", "--description", "Same closed") + bdProxiedCreate(t, bd, p3.dir, "Closed dup", "--type", "task", "--description", "Same closed") + if out, err := bdProxiedRun(t, bd, p3.dir, "close", x.ID); err != nil { + t.Fatalf("close: %v\n%s", err, out) + } + out, err := bdProxiedRun(t, bd, p3.dir, "duplicates", "--json") + if err != nil { + t.Fatalf("duplicates --json: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if groups := int(m["duplicate_groups"].(float64)); groups != 0 { + t.Errorf("expected 0 groups after closing one duplicate, got %d", groups) + } + }) + + t.Run("dry_run_lists_commands", func(t *testing.T) { + // Plain --dry-run (no --auto-merge) is read-only and emits merge_commands. + m := dupsJSON(t, "--dry-run") + if _, ok := m["merge_commands"]; !ok { + t.Errorf("expected merge_commands with --dry-run, got %v", m) + } + if _, ok := m["merge_results"]; ok { + t.Errorf("dry run must not have merge_results, got %v", m) + } + }) + + t.Run("auto_merge_rejected", func(t *testing.T) { + // Proxied mode refuses the write path of --auto-merge (embedded's auto_merge + // and auto_merge_reparents scenarios are intentionally not portable here). + out, err := bdProxiedRun(t, bd, p.dir, "duplicates", "--auto-merge") + if err == nil { + t.Fatalf("expected --auto-merge to be rejected, got success: %s", out) + } + if !strings.Contains(string(out), "not supported in proxied-server mode") { + t.Errorf("unexpected error: %s", out) + } + }) + + t.Run("auto_merge_dry_run_allowed", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "duplicates", "--auto-merge", "--dry-run", "--json") + if err != nil { + t.Fatalf("--auto-merge --dry-run should be read-only allowed: %v\n%s", err, out) + } + var got map[string]interface{} + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if _, ok := got["merge_commands"]; !ok { + t.Errorf("expected merge_commands in dry-run output, got %v", got) + } + if _, ok := got["merge_results"]; ok { + t.Errorf("dry-run must not perform merges (no merge_results), got %v", got) + } + }) +} + +func TestProxiedServerFindDuplicates(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "fdp") + + // Near-identical login issues (should be flagged as duplicates). + bdProxiedCreate(t, bd, p.dir, "Fix login page timeout error", "--type", "bug", + "--description", "The login page throws a timeout error after 30 seconds of inactivity") + bdProxiedCreate(t, bd, p.dir, "Login page timeout error fix needed", "--type", "bug", + "--description", "After 30 seconds the login page shows a timeout error to the user") + // Distinct issues (should NOT be flagged). + bdProxiedCreate(t, bd, p.dir, "Add dark mode to settings", "--type", "feature", + "--description", "Users want a dark mode toggle in the settings page") + bdProxiedCreate(t, bd, p.dir, "Upgrade database to PostgreSQL 16", "--type", "task", + "--description", "Migrate from PostgreSQL 14 to PostgreSQL 16 for performance") + bdProxiedCreate(t, bd, p.dir, "Write API documentation", "--type", "task", + "--description", "Document all REST endpoints with OpenAPI spec") + // A closed near-duplicate for status-filter testing. + closed := bdProxiedCreate(t, bd, p.dir, "Fix login page timeout error (old)", "--type", "bug", + "--description", "The login page throws a timeout error") + if out, err := bdProxiedRun(t, bd, p.dir, "close", closed.ID); err != nil { + t.Fatalf("close: %v\n%s", err, out) + } + + fdJSON := func(t *testing.T, args ...string) map[string]interface{} { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"find-duplicates", "--json"}, args...)...) + if err != nil { + t.Fatalf("find-duplicates --json %v: %v\n%s", args, err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + return m + } + + t.Run("mechanical_finds_near_identical", func(t *testing.T) { + m := fdJSON(t, "--threshold", "0.15") + if m["method"] != "mechanical" { + t.Errorf("method = %v, want mechanical", m["method"]) + } + pairs, ok := m["pairs"].([]interface{}) + if !ok { + t.Fatalf("expected pairs array, got %T", m["pairs"]) + } + if len(pairs) == 0 { + t.Fatal("expected at least 1 duplicate pair for near-identical issues") + } + var found bool + for _, pr := range pairs { + pm := pr.(map[string]interface{}) + ta := strings.ToLower(pm["issue_a_title"].(string)) + tb := strings.ToLower(pm["issue_b_title"].(string)) + if strings.Contains(ta, "login") && strings.Contains(tb, "login") { + found = true + } + } + if !found { + t.Error("expected login timeout issues to be flagged as duplicates") + } + }) + + t.Run("threshold_lower_finds_at_least_as_many", func(t *testing.T) { + high := fdJSON(t, "--threshold", "0.95")["pairs"].([]interface{}) + low := fdJSON(t, "--threshold", "0.2")["pairs"].([]interface{}) + if len(low) < len(high) { + t.Errorf("lower threshold should find >= as many pairs: low=%d high=%d", len(low), len(high)) + } + }) + + t.Run("threshold_zero_finds_pairs", func(t *testing.T) { + pairs := fdJSON(t, "--threshold", "0.0")["pairs"].([]interface{}) + if len(pairs) == 0 { + t.Error("expected at least some pairs at threshold 0") + } + }) + + t.Run("status_filter_open_excludes_closed", func(t *testing.T) { + pairs := fdJSON(t, "--status", "open", "--threshold", "0.2")["pairs"].([]interface{}) + for _, pr := range pairs { + pm := pr.(map[string]interface{}) + if strings.Contains(pm["issue_a_title"].(string), "(old)") || strings.Contains(pm["issue_b_title"].(string), "(old)") { + t.Error("closed issue should be excluded with --status open") + } + } + }) + + t.Run("status_filter_all", func(t *testing.T) { + pairs := fdJSON(t, "--status", "all", "--threshold", "0.3")["pairs"].([]interface{}) + if len(pairs) == 0 { + t.Error("expected at least 1 pair with --status all") + } + }) + + t.Run("limit_caps_results", func(t *testing.T) { + pairs := fdJSON(t, "--threshold", "0.0", "--limit", "1")["pairs"].([]interface{}) + if len(pairs) > 1 { + t.Errorf("expected at most 1 pair with --limit 1, got %d", len(pairs)) + } + }) + + t.Run("no_duplicates_high_threshold", func(t *testing.T) { + // A very high threshold should simply produce no pairs without crashing. + if _, err := bdProxiedRun(t, bd, p.dir, "find-duplicates", "--threshold", "0.99"); err != nil { + t.Fatalf("find-duplicates --threshold 0.99: %v", err) + } + }) + + t.Run("json_output_structure", func(t *testing.T) { + m := fdJSON(t, "--threshold", "0.3") + for _, key := range []string{"pairs", "count", "method", "threshold"} { + if _, ok := m[key]; !ok { + t.Errorf("expected %q key in JSON output", key) + } + } + if m["method"] != "mechanical" { + t.Errorf("expected method='mechanical', got %v", m["method"]) + } + }) + + t.Run("json_pair_fields", func(t *testing.T) { + pairs := fdJSON(t, "--threshold", "0.15")["pairs"].([]interface{}) + if len(pairs) == 0 { + t.Skip("no pairs to check fields on") + } + pm := pairs[0].(map[string]interface{}) + for _, key := range []string{"issue_a_id", "issue_b_id", "issue_a_title", "issue_b_title", "similarity", "method"} { + if _, ok := pm[key]; !ok { + t.Errorf("expected %q key in pair JSON", key) + } + } + }) + + t.Run("invalid_method_error", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "find-duplicates", "--method", "bogus") + if err == nil { + t.Fatalf("expected invalid method error, got success: %s", out) + } + if !strings.Contains(string(out), "invalid method") { + t.Errorf("expected 'invalid method' error, got: %s", out) + } + }) + + t.Run("ai_method_missing_key_error", func(t *testing.T) { + // The missing-key guard runs before any AI call. Skip when a key is + // present in the environment so we never actually reach the API. + if os.Getenv("ANTHROPIC_API_KEY") != "" { + t.Skip("ANTHROPIC_API_KEY set; skipping missing-key assertion to avoid a live AI call") + } + out, err := bdProxiedRun(t, bd, p.dir, "find-duplicates", "--method", "ai") + if err == nil { + t.Fatalf("expected missing-key error for --method ai, got success: %s", out) + } + if !strings.Contains(string(out), "ANTHROPIC_API_KEY") { + t.Errorf("expected ANTHROPIC_API_KEY hint in error, got: %s", out) + } + }) + + t.Run("find_dups_alias", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "find-dups", "--json", "--threshold", "0.3") + if err != nil { + t.Fatalf("find-dups alias: %v\n%s", err, out) + } + if !strings.Contains(string(out), "pairs") { + t.Errorf("expected JSON with 'pairs' from alias: %s", out) + } + }) + + t.Run("human_readable_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "find-duplicates", "--threshold", "0.15") + if err != nil { + t.Fatalf("find-duplicates: %v\n%s", err, out) + } + s := string(out) + if strings.Contains(s, "No similar issues") { + t.Skip("no pairs found at this threshold") + } + if !strings.Contains(s, "similar") { + t.Errorf("expected 'similar' in human-readable output: %s", s) + } + if !strings.Contains(s, "Pair") { + t.Errorf("expected 'Pair' in human-readable output: %s", s) + } + }) + + t.Run("fewer_than_2_issues", func(t *testing.T) { + p2 := newSharedProxiedProject(t, bd, "fd1") + bdProxiedCreate(t, bd, p2.dir, "Only one issue", "--type", "task") + out, err := bdProxiedRun(t, bd, p2.dir, "find-duplicates") + if err != nil { + t.Fatalf("find-duplicates: %v\n%s", err, out) + } + if !strings.Contains(string(out), "Not enough issues") { + t.Errorf("expected 'Not enough issues' message, got: %s", out) + } + }) + + t.Run("fewer_than_2_issues_json", func(t *testing.T) { + p3 := newSharedProxiedProject(t, bd, "fd2") + bdProxiedCreate(t, bd, p3.dir, "Only one issue json", "--type", "task") + out, err := bdProxiedRun(t, bd, p3.dir, "find-duplicates", "--json") + if err != nil { + t.Fatalf("find-duplicates --json: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if count := int(m["count"].(float64)); count != 0 { + t.Errorf("expected count=0 with fewer than 2 issues, got %d", count) + } + }) +} diff --git a/cmd/bd/duplicates_proxied_server.go b/cmd/bd/duplicates_proxied_server.go new file mode 100644 index 000000000..ba903c679 --- /dev/null +++ b/cmd/bd/duplicates_proxied_server.go @@ -0,0 +1,36 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +func runDuplicatesProxiedServer(ctx context.Context, autoMerge, dryRun bool) error { + if autoMerge && !dryRun { + return HandleErrorRespectJSON("duplicates --auto-merge is not supported in proxied-server mode") + } + + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{}) + if err != nil { + return HandleError("fetching issues: %v", err) + } + allIssues := page.Items + + duplicateGroups := findDuplicateGroups(openIssuesOf(allIssues)) + if len(duplicateGroups) == 0 { + return outputNoDuplicates() + } + + refCounts := countReferences(allIssues) + depCounts, _ := uw.DependencyUseCase().CountsByIssueIDs(ctx, collectDuplicateGroupIDs(duplicateGroups)) + structuralScores := buildStructuralScores(duplicateGroups, depCounts) + + return outputDuplicates(duplicateGroups, refCounts, structuralScores, autoMerge, dryRun, nil) +} diff --git a/cmd/bd/epic.go b/cmd/bd/epic.go index f40e159f8..06e7e2da9 100644 --- a/cmd/bd/epic.go +++ b/cmd/bd/epic.go @@ -20,9 +20,6 @@ var epicStatusCmd = &cobra.Command{ SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("epic status is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("epic-status") defer func() { if c := metrics.Global(); c != nil { @@ -31,66 +28,74 @@ var epicStatusCmd = &cobra.Command{ }() eligibleOnly, _ := cmd.Flags().GetBool("eligible-only") - var epics []*types.EpicStatus - var err error - ctx := rootCtx - epics, err = store.GetEpicsEligibleForClosure(ctx) + + if usesProxiedServer() { + return runEpicStatusProxiedServer(rootCtx, eligibleOnly) + } + + epics, err := store.GetEpicsEligibleForClosure(rootCtx) if err != nil { return HandleErrorRespectJSON("getting epic status: %v", err) } - if eligibleOnly { - filtered := []*types.EpicStatus{} - for _, epic := range epics { - if epic.EligibleForClose { - filtered = append(filtered, epic) - } - } - epics = filtered - } - if jsonOutput { - if epics == nil { - epics = []*types.EpicStatus{} - } - return outputJSON(epics) - } - if len(epics) == 0 { - fmt.Println("No open epics found") - return nil - } - for _, epicStatus := range epics { - epic := epicStatus.Epic - percentage := 0 - if epicStatus.TotalChildren > 0 { - percentage = (epicStatus.ClosedChildren * 100) / epicStatus.TotalChildren - } - statusIcon := "" - if epicStatus.EligibleForClose { - statusIcon = ui.RenderPass("✓") - } else if percentage > 0 { - statusIcon = ui.RenderWarn("○") - } else { - statusIcon = "○" - } - fmt.Printf("%s %s %s\n", statusIcon, ui.RenderAccent(epic.ID), ui.RenderBold(epic.Title)) - fmt.Printf(" Progress: %d/%d children closed (%d%%)\n", - epicStatus.ClosedChildren, epicStatus.TotalChildren, percentage) - if epicStatus.EligibleForClose { - fmt.Printf(" %s\n", ui.RenderPass("Eligible for closure")) - } - fmt.Println() - } - return nil + return renderEpicStatus(epics, eligibleOnly) }, } + +func renderEpicStatus(epics []*types.EpicStatus, eligibleOnly bool) error { + if eligibleOnly { + epics = filterEligibleEpics(epics) + } + if jsonOutput { + if epics == nil { + epics = []*types.EpicStatus{} + } + return outputJSON(epics) + } + if len(epics) == 0 { + fmt.Println("No open epics found") + return nil + } + for _, epicStatus := range epics { + epic := epicStatus.Epic + percentage := 0 + if epicStatus.TotalChildren > 0 { + percentage = (epicStatus.ClosedChildren * 100) / epicStatus.TotalChildren + } + statusIcon := "" + if epicStatus.EligibleForClose { + statusIcon = ui.RenderPass("✓") + } else if percentage > 0 { + statusIcon = ui.RenderWarn("○") + } else { + statusIcon = "○" + } + fmt.Printf("%s %s %s\n", statusIcon, ui.RenderAccent(epic.ID), ui.RenderBold(epic.Title)) + fmt.Printf(" Progress: %d/%d children closed (%d%%)\n", + epicStatus.ClosedChildren, epicStatus.TotalChildren, percentage) + if epicStatus.EligibleForClose { + fmt.Printf(" %s\n", ui.RenderPass("Eligible for closure")) + } + fmt.Println() + } + return nil +} + +func filterEligibleEpics(epics []*types.EpicStatus) []*types.EpicStatus { + filtered := []*types.EpicStatus{} + for _, epic := range epics { + if epic.EligibleForClose { + filtered = append(filtered, epic) + } + } + return filtered +} + var closeEligibleEpicsCmd = &cobra.Command{ Use: "close-eligible", Short: "Close epics where all children are complete", SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("epic close-eligible is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("epic-close-eligible") defer func() { if c := metrics.Global(); c != nil { @@ -99,40 +104,28 @@ var closeEligibleEpicsCmd = &cobra.Command{ }() dryRun, _ := cmd.Flags().GetBool("dry-run") + + if usesProxiedServer() { + return runCloseEligibleEpicsProxiedServer(rootCtx, dryRun) + } + if !dryRun { CheckReadonly("epic close-eligible") } - var eligibleEpics []*types.EpicStatus - ctx := rootCtx - epics, err := store.GetEpicsEligibleForClosure(ctx) + epics, err := store.GetEpicsEligibleForClosure(rootCtx) if err != nil { return HandleErrorRespectJSON("getting eligible epics: %v", err) } - for _, epic := range epics { - if epic.EligibleForClose { - eligibleEpics = append(eligibleEpics, epic) - } - } + eligibleEpics := filterEligibleEpics(epics) if len(eligibleEpics) == 0 { - if jsonOutput { - return outputJSON([]*types.EpicStatus{}) - } - fmt.Println("No epics eligible for closure") - return nil + return outputNoEligibleEpics() } if dryRun { - if jsonOutput { - return outputJSON(eligibleEpics) - } - fmt.Printf("Would close %d epic(s):\n", len(eligibleEpics)) - for _, epicStatus := range eligibleEpics { - fmt.Printf(" - %s: %s\n", epicStatus.Epic.ID, epicStatus.Epic.Title) - } - return nil + return outputCloseEligibleDryRun(eligibleEpics) } closedIDs := []string{} for _, epicStatus := range eligibleEpics { - err := store.CloseIssue(ctx, epicStatus.Epic.ID, "All children completed", "system", "") + err := store.CloseIssue(rootCtx, epicStatus.Epic.ID, "All children completed", "system", "") if err != nil { fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", epicStatus.Epic.ID, err) continue @@ -142,20 +135,43 @@ var closeEligibleEpicsCmd = &cobra.Command{ if len(closedIDs) > 0 { commandDidWrite.Store(true) } - if jsonOutput { - return outputJSON(map[string]interface{}{ - "closed": closedIDs, - "count": len(closedIDs), - }) - } - fmt.Printf("✓ Closed %d epic(s)\n", len(closedIDs)) - for _, id := range closedIDs { - fmt.Printf(" - %s\n", id) - } - return nil + return outputCloseEligibleResult(closedIDs) }, } +func outputNoEligibleEpics() error { + if jsonOutput { + return outputJSON([]*types.EpicStatus{}) + } + fmt.Println("No epics eligible for closure") + return nil +} + +func outputCloseEligibleDryRun(eligibleEpics []*types.EpicStatus) error { + if jsonOutput { + return outputJSON(eligibleEpics) + } + fmt.Printf("Would close %d epic(s):\n", len(eligibleEpics)) + for _, epicStatus := range eligibleEpics { + fmt.Printf(" - %s: %s\n", epicStatus.Epic.ID, epicStatus.Epic.Title) + } + return nil +} + +func outputCloseEligibleResult(closedIDs []string) error { + if jsonOutput { + return outputJSON(map[string]interface{}{ + "closed": closedIDs, + "count": len(closedIDs), + }) + } + fmt.Printf("✓ Closed %d epic(s)\n", len(closedIDs)) + for _, id := range closedIDs { + fmt.Printf(" - %s\n", id) + } + return nil +} + func init() { epicCmd.AddCommand(epicStatusCmd) epicCmd.AddCommand(closeEligibleEpicsCmd) diff --git a/cmd/bd/epic_proxied_integration_test.go b/cmd/bd/epic_proxied_integration_test.go new file mode 100644 index 000000000..716d1f26a --- /dev/null +++ b/cmd/bd/epic_proxied_integration_test.go @@ -0,0 +1,181 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func TestProxiedServerEpic(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "epc") + + // An epic with all children closed becomes eligible for closure. + epic := bdProxiedCreate(t, bd, p.dir, "Shipping epic", "--type", "epic") + c1 := bdProxiedCreate(t, bd, p.dir, "Child one", "--type", "task", "--parent", epic.ID) + c2 := bdProxiedCreate(t, bd, p.dir, "Child two", "--type", "task", "--parent", epic.ID) + + // A second epic that stays incomplete (one open child). + openEpic := bdProxiedCreate(t, bd, p.dir, "Incomplete epic", "--type", "epic") + bdProxiedCreate(t, bd, p.dir, "Open child", "--type", "task", "--parent", openEpic.ID) + + // A partially-done epic: two children, one closed. It shows progress but is + // never eligible for closure (one child stays open the whole test). + partialEpic := bdProxiedCreate(t, bd, p.dir, "Partial epic", "--type", "epic") + pc1 := bdProxiedCreate(t, bd, p.dir, "Partial child one", "--type", "task", "--parent", partialEpic.ID) + bdProxiedCreate(t, bd, p.dir, "Partial child two", "--type", "task", "--parent", partialEpic.ID) + if out, err := bdProxiedRun(t, bd, p.dir, "close", pc1.ID); err != nil { + t.Fatalf("close partial child: %v\n%s", err, out) + } + + epicStatus := func(t *testing.T, args ...string) []*types.EpicStatus { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"epic", "status", "--json"}, args...)...) + if err != nil { + t.Fatalf("epic status %v: %v\n%s", args, err, out) + } + var got []*types.EpicStatus + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + return got + } + + t.Run("status_shows_progress", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "epic", "status") + if err != nil { + t.Fatalf("epic status: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, partialEpic.ID) { + t.Errorf("expected partial epic %s in status output: %s", partialEpic.ID, s) + } + if !strings.Contains(s, "children closed") || !strings.Contains(s, "/") { + t.Errorf("expected progress fraction in output: %s", s) + } + }) + + t.Run("status_json_is_array", func(t *testing.T) { + got := epicStatus(t) + if len(got) < 1 { + t.Errorf("expected at least 1 epic in status, got %d", len(got)) + } + }) + + t.Run("status_eligible_only_excludes_incomplete", func(t *testing.T) { + // Neither the partially-done epic nor the fully-open epic is eligible. + out, err := bdProxiedRun(t, bd, p.dir, "epic", "status", "--eligible-only") + if err != nil { + t.Fatalf("epic status --eligible-only: %v\n%s", err, out) + } + s := string(out) + if strings.Contains(s, partialEpic.ID) { + t.Errorf("partial epic should not appear with --eligible-only: %s", s) + } + if strings.Contains(s, openEpic.ID) { + t.Errorf("incomplete epic should not appear with --eligible-only: %s", s) + } + }) + + t.Run("status_no_open_epics", func(t *testing.T) { + p2 := newSharedProxiedProject(t, bd, "epq") + out, err := bdProxiedRun(t, bd, p2.dir, "epic", "status") + if err != nil { + t.Fatalf("epic status: %v\n%s", err, out) + } + if !strings.Contains(string(out), "No open epics") { + t.Errorf("expected 'No open epics': %s", out) + } + }) + + t.Run("status_not_eligible_while_open", func(t *testing.T) { + for _, es := range epicStatus(t) { + if es.Epic.ID == epic.ID && es.EligibleForClose { + t.Errorf("epic should not be eligible before children closed") + } + } + }) + + // Close both children of the first epic. + bdProxiedRun(t, bd, p.dir, "close", c1.ID) + bdProxiedRun(t, bd, p.dir, "close", c2.ID) + + t.Run("status_eligible_after_children_closed", func(t *testing.T) { + var found bool + for _, es := range epicStatus(t) { + if es.Epic.ID == epic.ID { + found = true + if !es.EligibleForClose { + t.Errorf("epic %s should be eligible (2/2 closed), got %+v", epic.ID, es) + } + if es.TotalChildren != 2 || es.ClosedChildren != 2 { + t.Errorf("expected 2/2 children, got %d/%d", es.ClosedChildren, es.TotalChildren) + } + } + } + if !found { + t.Errorf("eligible epic %s missing from status", epic.ID) + } + }) + + t.Run("dry_run_lists_without_closing", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "epic", "close-eligible", "--dry-run", "--json") + if err != nil { + t.Fatalf("dry-run: %v\n%s", err, out) + } + var eligible []*types.EpicStatus + if err := json.Unmarshal(out, &eligible); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + var listed bool + for _, es := range eligible { + if es.Epic.ID == epic.ID { + listed = true + } + if es.Epic.ID == openEpic.ID || es.Epic.ID == partialEpic.ID { + t.Errorf("incomplete epic %s must not be listed as eligible", es.Epic.ID) + } + } + if !listed { + t.Errorf("dry-run should list eligible epic %s, got %+v", epic.ID, eligible) + } + // Confirm it was NOT closed. + show := bdProxiedShow(t, bd, p.dir, epic.ID) + if show.Status == types.StatusClosed { + t.Errorf("dry-run must not close the epic") + } + }) + + t.Run("write_closes_eligible", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "epic", "close-eligible", "--json") + if err != nil { + t.Fatalf("close-eligible: %v\n%s", err, out) + } + var res struct { + Closed []string `json:"closed"` + Count int `json:"count"` + } + if err := json.Unmarshal(out, &res); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + var closedIt bool + for _, id := range res.Closed { + if id == epic.ID { + closedIt = true + } + } + if !closedIt { + t.Errorf("expected %s in closed list, got %+v", epic.ID, res.Closed) + } + show := bdProxiedShow(t, bd, p.dir, epic.ID) + if show.Status != types.StatusClosed { + t.Errorf("epic %s should be closed after close-eligible, got %s", epic.ID, show.Status) + } + }) +} diff --git a/cmd/bd/epic_proxied_server.go b/cmd/bd/epic_proxied_server.go new file mode 100644 index 000000000..6b36a2ebd --- /dev/null +++ b/cmd/bd/epic_proxied_server.go @@ -0,0 +1,72 @@ +package main + +import ( + "context" + "fmt" + "os" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/uow" +) + +func runEpicStatusProxiedServer(ctx context.Context, eligibleOnly bool) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + epics, err := uw.IssueUseCase().GetEpicsEligibleForClosure(ctx) + if err != nil { + return HandleErrorRespectJSON("getting epic status: %v", err) + } + return renderEpicStatus(epics, eligibleOnly) +} + +func runCloseEligibleEpicsProxiedServer(ctx context.Context, dryRun bool) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + epics, err := uw.IssueUseCase().GetEpicsEligibleForClosure(ctx) + if err != nil { + uw.Close(ctx) + return HandleErrorRespectJSON("getting eligible epics: %v", err) + } + eligibleEpics := filterEligibleEpics(epics) + uw.Close(ctx) + + if len(eligibleEpics) == 0 { + return outputNoEligibleEpics() + } + if dryRun { + return outputCloseEligibleDryRun(eligibleEpics) + } + + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + closedIDs, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) ([]string, string, error) { + epics, err := uw.IssueUseCase().GetEpicsEligibleForClosure(ctx) + if err != nil { + return nil, "", err + } + var closed []string + for _, epicStatus := range filterEligibleEpics(epics) { + if _, err := uw.IssueUseCase().CloseIssue(ctx, epicStatus.Epic.ID, domain.CloseIssueParams{Reason: "All children completed"}, "system"); err != nil { + fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", epicStatus.Epic.ID, err) + continue + } + closed = append(closed, epicStatus.Epic.ID) + } + return closed, "epic: close eligible", nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + if len(closedIDs) > 0 { + commandDidWrite.Store(true) + } + return outputCloseEligibleResult(closedIDs) +} diff --git a/cmd/bd/find_duplicates.go b/cmd/bd/find_duplicates.go index 1633ab84f..ffae07e77 100644 --- a/cmd/bd/find_duplicates.go +++ b/cmd/bd/find_duplicates.go @@ -78,9 +78,6 @@ type duplicatePair struct { } func runFindDuplicates(cmd *cobra.Command, _ []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("find-duplicates is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("find-duplicates") defer func() { if c := metrics.Global(); c != nil { @@ -97,8 +94,6 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) error { model = config.DefaultAIModel() } - ctx := rootCtx - if method != "mechanical" && method != "ai" { return HandleErrorRespectJSON("invalid method %q (use: mechanical, ai)", method) } @@ -115,24 +110,33 @@ func runFindDuplicates(cmd *cobra.Command, _ []string) error { filter.Status = &s } - var issues []*types.Issue - var err error + if usesProxiedServer() { + return runFindDuplicatesProxiedServer(rootCtx, filter, status, method, threshold, limit, model) + } - issues, err = store.SearchIssues(ctx, "", filter) + issues, err := store.SearchIssues(rootCtx, "", filter) if err != nil { return HandleErrorRespectJSON("fetching issues: %v", err) } + issues = filterClosedIfNoStatus(issues, status) - if status == "" { - var filtered []*types.Issue - for _, issue := range issues { - if issue.Status != types.StatusClosed { - filtered = append(filtered, issue) - } - } - issues = filtered + return reportFindDuplicates(rootCtx, issues, method, threshold, limit, model) +} + +func filterClosedIfNoStatus(issues []*types.Issue, status string) []*types.Issue { + if status != "" { + return issues } + var filtered []*types.Issue + for _, issue := range issues { + if issue.Status != types.StatusClosed { + filtered = append(filtered, issue) + } + } + return filtered +} +func reportFindDuplicates(ctx context.Context, issues []*types.Issue, method string, threshold float64, limit int, model string) error { if len(issues) < 2 { if jsonOutput { return outputJSON(map[string]interface{}{ diff --git a/cmd/bd/find_duplicates_proxied_server.go b/cmd/bd/find_duplicates_proxied_server.go new file mode 100644 index 000000000..929569576 --- /dev/null +++ b/cmd/bd/find_duplicates_proxied_server.go @@ -0,0 +1,23 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +func runFindDuplicatesProxiedServer(ctx context.Context, filter types.IssueFilter, status, method string, threshold float64, limit int, model string) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter) + if err != nil { + return HandleErrorRespectJSON("fetching issues: %v", err) + } + issues := filterClosedIfNoStatus(page.Items, status) + + return reportFindDuplicates(ctx, issues, method, threshold, limit, model) +} diff --git a/cmd/bd/graph.go b/cmd/bd/graph.go index 76fbe27a6..904c7b83f 100644 --- a/cmd/bd/graph.go +++ b/cmd/bd/graph.go @@ -79,9 +79,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("graph is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("graph") defer func() { if c := metrics.Global(); c != nil { @@ -89,8 +86,6 @@ Examples: } }() - ctx := rootCtx - if graphAll && len(args) > 0 { return HandleErrorRespectJSON("cannot specify issue ID with --all flag") } @@ -98,6 +93,11 @@ Examples: return HandleErrorWithHintRespectJSON("issue ID required", "Use --all for all open issues") } + if usesProxiedServer() { + return runGraphProxiedServer(rootCtx, args) + } + + ctx := rootCtx if store == nil { return HandleErrorRespectJSON("no database connection") } @@ -107,61 +107,7 @@ Examples: if err != nil { return HandleErrorRespectJSON("loading all issues: %v", err) } - - if graphOpen { - var filtered []*TemplateSubgraph - for _, sg := range subgraphs { - f := filterSubgraphOpen(sg) - if f != nil && len(f.Issues) > 0 { - filtered = append(filtered, f) - } - } - subgraphs = filtered - } - - if len(subgraphs) == 0 { - fmt.Println("No open issues found") - return nil - } - - if jsonOutput { - return outputJSON(subgraphs) - } - - if graphHTML && !graphOpen { - merged := mergeSubgraphsForHTML(subgraphs) - layout := computeLayout(merged) - renderGraphHTML(layout, merged) - return nil - } - - if graphOpen { - for i, subgraph := range subgraphs { - layout := computeLayout(subgraph) - renderGraphCompact(layout, subgraph) - if i < len(subgraphs)-1 { - fmt.Println(strings.Repeat("─", 60)) - } - } - return nil - } - - for i, subgraph := range subgraphs { - layout := computeLayout(subgraph) - if graphDOT { - renderGraphDOT(layout, subgraph) - } else if graphCompact { - renderGraphCompact(layout, subgraph) - } else if graphBox { - renderGraph(layout, subgraph) - } else { - renderGraphVisual(layout, subgraph) - } - if !graphDOT && i < len(subgraphs)-1 { - fmt.Println(strings.Repeat("─", 60)) - } - } - return nil + return renderGraphAllSubgraphs(subgraphs) } issueID, err := utils.ResolvePartialID(ctx, store, args[0]) @@ -173,34 +119,53 @@ Examples: if err != nil { return HandleErrorRespectJSON("loading graph: %v", err) } + return renderGraphSingleSubgraph(subgraph) + }, +} - if graphOpen { - subgraph = filterSubgraphOpen(subgraph) - if subgraph == nil || len(subgraph.Issues) == 0 { - fmt.Println("No open issues in subgraph") - return nil +func renderGraphAllSubgraphs(subgraphs []*TemplateSubgraph) error { + if graphOpen { + var filtered []*TemplateSubgraph + for _, sg := range subgraphs { + f := filterSubgraphOpen(sg) + if f != nil && len(f.Issues) > 0 { + filtered = append(filtered, f) } } + subgraphs = filtered + } - layout := computeLayout(subgraph) + if len(subgraphs) == 0 { + fmt.Println("No open issues found") + return nil + } - if jsonOutput { - return outputJSON(map[string]interface{}{ - "root": subgraph.Root, - "issues": subgraph.Issues, - "layout": layout, - }) - } + if jsonOutput { + return outputJSON(subgraphs) + } - if graphOpen { + if graphHTML && !graphOpen { + merged := mergeSubgraphsForHTML(subgraphs) + layout := computeLayout(merged) + renderGraphHTML(layout, merged) + return nil + } + + if graphOpen { + for i, subgraph := range subgraphs { + layout := computeLayout(subgraph) renderGraphCompact(layout, subgraph) - return nil + if i < len(subgraphs)-1 { + fmt.Println(strings.Repeat("─", 60)) + } } + return nil + } + for i, subgraph := range subgraphs { + layout := computeLayout(subgraph) if graphDOT { renderGraphDOT(layout, subgraph) - } else if graphHTML { - renderGraphHTML(layout, subgraph) } else if graphCompact { renderGraphCompact(layout, subgraph) } else if graphBox { @@ -208,8 +173,49 @@ Examples: } else { renderGraphVisual(layout, subgraph) } + if !graphDOT && i < len(subgraphs)-1 { + fmt.Println(strings.Repeat("─", 60)) + } + } + return nil +} + +func renderGraphSingleSubgraph(subgraph *TemplateSubgraph) error { + if graphOpen { + subgraph = filterSubgraphOpen(subgraph) + if subgraph == nil || len(subgraph.Issues) == 0 { + fmt.Println("No open issues in subgraph") + return nil + } + } + + layout := computeLayout(subgraph) + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "root": subgraph.Root, + "issues": subgraph.Issues, + "layout": layout, + }) + } + + if graphOpen { + renderGraphCompact(layout, subgraph) return nil - }, + } + + if graphDOT { + renderGraphDOT(layout, subgraph) + } else if graphHTML { + renderGraphHTML(layout, subgraph) + } else if graphCompact { + renderGraphCompact(layout, subgraph) + } else if graphBox { + renderGraph(layout, subgraph) + } else { + renderGraphVisual(layout, subgraph) + } + return nil } var graphCheckCmd = &cobra.Command{ @@ -221,9 +227,6 @@ Returns exit code 0 if the graph is clean, 1 if issues are found.`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("graph check is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("graph-check") defer func() { if c := metrics.Global(); c != nil { @@ -231,69 +234,74 @@ Returns exit code 0 if the graph is clean, 1 if issues are found.`, } }() - ctx := rootCtx - - type GraphCheckResult struct { - Clean bool `json:"clean"` - Cycles [][]string `json:"cycles"` - Summary struct { - CycleCount int `json:"cycle_count"` - } `json:"summary"` + if usesProxiedServer() { + return runGraphCheckProxiedServer(rootCtx) } - result := GraphCheckResult{Clean: true} - - cycles, err := store.DetectCycles(ctx) + cycles, err := store.DetectCycles(rootCtx) if err != nil { return HandleErrorRespectJSON("cycle detection failed: %v", err) } + return renderGraphCheck(cycles) + }, +} - for _, cycle := range cycles { - ids := make([]string, len(cycle)) - for i, issue := range cycle { - ids[i] = issue.ID - } - result.Cycles = append(result.Cycles, ids) +func renderGraphCheck(cycles [][]*types.Issue) error { + type GraphCheckResult struct { + Clean bool `json:"clean"` + Cycles [][]string `json:"cycles"` + Summary struct { + CycleCount int `json:"cycle_count"` + } `json:"summary"` + } + + result := GraphCheckResult{Clean: true} + + for _, cycle := range cycles { + ids := make([]string, len(cycle)) + for i, issue := range cycle { + ids[i] = issue.ID } - result.Summary.CycleCount = len(cycles) + result.Cycles = append(result.Cycles, ids) + } + result.Summary.CycleCount = len(cycles) - if len(cycles) > 0 { - result.Clean = false + if len(cycles) > 0 { + result.Clean = false + } + + if jsonOutput { + if err := outputJSON(result); err != nil { + return err } - - if jsonOutput { - if err := outputJSON(result); err != nil { - return err - } - if !result.Clean { - return SilentExit() - } - return nil - } - - if result.Clean { - fmt.Printf("\n%s Graph integrity check passed\n\n", ui.RenderPass("✓")) - } else { - fmt.Printf("\n%s Graph integrity issues found\n\n", ui.RenderFail("✗")) - } - - if len(result.Cycles) > 0 { - fmt.Printf("%s Cycles (%d):\n\n", ui.RenderFail("⚠"), len(result.Cycles)) - for _, cycle := range result.Cycles { - fmt.Printf(" %s → %s\n", strings.Join(cycle, " → "), cycle[0]) - } - fmt.Println() - } else { - fmt.Printf(" %s No dependency cycles\n", ui.RenderPass("✓")) - } - - fmt.Println() - if !result.Clean { return SilentExit() } return nil - }, + } + + if result.Clean { + fmt.Printf("\n%s Graph integrity check passed\n\n", ui.RenderPass("✓")) + } else { + fmt.Printf("\n%s Graph integrity issues found\n\n", ui.RenderFail("✗")) + } + + if len(result.Cycles) > 0 { + fmt.Printf("%s Cycles (%d):\n\n", ui.RenderFail("⚠"), len(result.Cycles)) + for _, cycle := range result.Cycles { + fmt.Printf(" %s → %s\n", strings.Join(cycle, " → "), cycle[0]) + } + fmt.Println() + } else { + fmt.Printf(" %s No dependency cycles\n", ui.RenderPass("✓")) + } + + fmt.Println() + + if !result.Clean { + return SilentExit() + } + return nil } func init() { @@ -478,6 +486,10 @@ func loadAllGraphSubgraphs(ctx context.Context, s storage.DoltStorage) ([]*Templ } } + return assembleAllSubgraphs(allIssues, issueMap, allDeps), nil +} + +func assembleAllSubgraphs(allIssues []*types.Issue, issueMap map[string]*types.Issue, allDeps []*types.Dependency) []*TemplateSubgraph { // Build adjacency list for union-find adj := make(map[string][]string) for _, dep := range allDeps { @@ -580,7 +592,7 @@ func loadAllGraphSubgraphs(ctx context.Context, s storage.DoltStorage) ([]*Templ subgraphs = append(subgraphs, subgraph) } - return subgraphs, nil + return subgraphs } // isOpenStatus returns true for statuses considered "open" / actionable. diff --git a/cmd/bd/graph_proxied_integration_test.go b/cmd/bd/graph_proxied_integration_test.go new file mode 100644 index 000000000..45997c460 --- /dev/null +++ b/cmd/bd/graph_proxied_integration_test.go @@ -0,0 +1,227 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestProxiedServerGraph(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "grp") + + epic := bdProxiedCreate(t, bd, p.dir, "Graph epic", "--type", "epic") + c1 := bdProxiedCreate(t, bd, p.dir, "Child one", "--type", "task", "--parent", epic.ID) + c2 := bdProxiedCreate(t, bd, p.dir, "Child two", "--type", "task", "--parent", epic.ID) + // c2 depends on c1 (c1 blocks c2). + if out, err := bdProxiedRun(t, bd, p.dir, "dep", "add", c2.ID, c1.ID); err != nil { + t.Fatalf("dep add: %v\n%s", err, out) + } + standalone := bdProxiedCreate(t, bd, p.dir, "Standalone issue", "--type", "task") + + singleGraphIDs := func(t *testing.T, id string) map[string]bool { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, "graph", id, "--json") + if err != nil { + t.Fatalf("graph %s --json: %v\n%s", id, err, out) + } + var got struct { + Root *struct{ ID string } `json:"root"` + Issues []struct { + ID string `json:"id"` + } `json:"issues"` + } + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + set := make(map[string]bool, len(got.Issues)) + for _, iss := range got.Issues { + set[iss.ID] = true + } + return set + } + + t.Run("single_issue_human", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "graph", epic.ID) + if err != nil { + t.Fatalf("graph %s: %v\n%s", epic.ID, err, out) + } + if !strings.Contains(string(out), epic.ID) { + t.Errorf("expected epic ID in graph: %s", out) + } + }) + + t.Run("epic_subgraph_includes_children", func(t *testing.T) { + ids := singleGraphIDs(t, epic.ID) + for _, want := range []string{epic.ID, c1.ID, c2.ID} { + if !ids[want] { + t.Errorf("epic subgraph missing %s, got %v", want, ids) + } + } + }) + + t.Run("dependency_bfs_reaches_dependent", func(t *testing.T) { + // Starting from c1, the BFS should reach c2 (which depends on c1). + ids := singleGraphIDs(t, c1.ID) + if !ids[c2.ID] { + t.Errorf("graph from %s should reach dependent %s, got %v", c1.ID, c2.ID, ids) + } + }) + + t.Run("no_dependencies", func(t *testing.T) { + ids := singleGraphIDs(t, standalone.ID) + if !ids[standalone.ID] { + t.Errorf("expected standalone %s in its own graph, got %v", standalone.ID, ids) + } + }) + + t.Run("compact_format", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "graph", "--compact", epic.ID) + if err != nil { + t.Fatalf("graph --compact: %v\n%s", err, out) + } + if len(out) == 0 { + t.Error("expected non-empty compact output") + } + }) + + t.Run("box_format", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "graph", "--box", epic.ID) + if err != nil { + t.Fatalf("graph --box: %v\n%s", err, out) + } + if len(out) == 0 { + t.Error("expected non-empty box output") + } + }) + + t.Run("dot_format", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "graph", "--dot", epic.ID) + if err != nil { + t.Fatalf("graph --dot: %v\n%s", err, out) + } + if !strings.Contains(string(out), "digraph") { + t.Errorf("expected 'digraph' in DOT output: %s", out) + } + }) + + t.Run("html_format", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "graph", "--html", epic.ID) + if err != nil { + t.Fatalf("graph --html: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, " 0 { + currentID := queue[0] + queue = queue[1:] + addNeighbors(currentID, domain.DepDirectionIn) // dependents + addNeighbors(currentID, domain.DepDirectionOut) // dependencies + } + + ids := make([]string, 0, len(subgraph.Issues)) + for _, iss := range subgraph.Issues { + ids = append(ids, iss.ID) + } + recs, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, ids) + if err != nil { + return nil, fmt.Errorf("loading dependencies: %w", err) + } + for _, iss := range subgraph.Issues { + for _, dep := range recs[iss.ID] { + if _, ok := subgraph.IssueMap[dep.DependsOnID]; ok { + subgraph.Dependencies = append(subgraph.Dependencies, dep) + } + } + } + + return subgraph, nil +} + +func loadAllGraphSubgraphsUOW(ctx context.Context, uw uow.UnitOfWork) ([]*TemplateSubgraph, error) { + var allIssues []*types.Issue + for _, status := range []types.Status{types.StatusOpen, types.StatusInProgress, types.StatusBlocked} { + statusCopy := status + page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Status: &statusCopy}) + if err != nil { + return nil, fmt.Errorf("failed to search issues: %w", err) + } + allIssues = append(allIssues, page.Items...) + } + + if len(allIssues) == 0 { + return nil, nil + } + + issueMap := make(map[string]*types.Issue, len(allIssues)) + ids := make([]string, 0, len(allIssues)) + for _, issue := range allIssues { + issueMap[issue.ID] = issue + ids = append(ids, issue.ID) + } + + recs, err := uw.DependencyUseCase().GetIssueDependencyRecords(ctx, ids) + if err != nil { + return nil, fmt.Errorf("failed to load dependencies: %w", err) + } + var allDeps []*types.Dependency + for _, issue := range allIssues { + for _, dep := range recs[issue.ID] { + if _, ok := issueMap[dep.DependsOnID]; ok { + allDeps = append(allDeps, dep) + } + } + } + + return assembleAllSubgraphs(allIssues, issueMap, allDeps), nil +} diff --git a/cmd/bd/history.go b/cmd/bd/history.go index 3d1bc6d62..9109867bd 100644 --- a/cmd/bd/history.go +++ b/cmd/bd/history.go @@ -6,6 +6,7 @@ import ( "github.com/spf13/cobra" "github.com/steveyegge/beads/internal/metrics" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -30,9 +31,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("history is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("history") defer func() { if c := metrics.Global(); c != nil { @@ -40,68 +38,80 @@ Examples: } }() - ctx := rootCtx issueID := args[0] - if historyEvents { - events, err := collectHistoryEvents(ctx, issueID, historyLimit) - if err != nil { - return HandleErrorRespectJSON("failed to get history events: %v", err) - } - if jsonOutput { - return outputJSON(events) - } - printHistoryEvents(issueID, events) - return nil + if usesProxiedServer() { + return runHistoryProxiedServer(rootCtx, issueID, historyLimit, historyEvents) } - history, err := store.History(ctx, issueID) + return runHistory(rootCtx, store, issueID, historyLimit, historyEvents) + }, +} + +type historyBackend interface { + History(ctx context.Context, id string) ([]*storage.HistoryEntry, error) + IterEvents(ctx context.Context, id string, limit int) (storage.Iter[types.Event], error) +} + +func runHistory(ctx context.Context, backend historyBackend, issueID string, limit int, showEvents bool) error { + if showEvents { + events, err := collectHistoryEvents(ctx, backend, issueID, limit) if err != nil { - return HandleErrorRespectJSON("failed to get history: %v", err) + return HandleErrorRespectJSON("failed to get history events: %v", err) } - - if len(history) == 0 { - if jsonOutput { - return outputJSON(history) - } - fmt.Printf("No history found for issue %s\n", issueID) - return nil + if jsonOutput { + return outputJSON(events) } + printHistoryEvents(issueID, events) + return nil + } - if historyLimit > 0 && historyLimit < len(history) { - history = history[:historyLimit] - } + history, err := backend.History(ctx, issueID) + if err != nil { + return HandleErrorRespectJSON("failed to get history: %v", err) + } + if len(history) == 0 { if jsonOutput { return outputJSON(history) } - - fmt.Printf("\n%s History for %s (%d entries)\n\n", - ui.RenderAccent("📜"), issueID, len(history)) - - for i, entry := range history { - fmt.Printf("%s %s\n", - ui.RenderMuted(entry.CommitHash[:8]), - ui.RenderMuted(entry.CommitDate.Format("2006-01-02 15:04:05"))) - fmt.Printf(" Author: %s\n", entry.Committer) - - if entry.Issue != nil { - statusIcon := ui.GetStatusIcon(string(entry.Issue.Status)) - fmt.Printf(" %s %s: %s [P%d - %s]\n", - statusIcon, - entry.Issue.ID, - entry.Issue.Title, - entry.Issue.Priority, - entry.Issue.Status) - } - - if i < len(history)-1 { - fmt.Println() - } - } - fmt.Println() + fmt.Printf("No history found for issue %s\n", issueID) return nil - }, + } + + if limit > 0 && limit < len(history) { + history = history[:limit] + } + + if jsonOutput { + return outputJSON(history) + } + + fmt.Printf("\n%s History for %s (%d entries)\n\n", + ui.RenderAccent("📜"), issueID, len(history)) + + for i, entry := range history { + fmt.Printf("%s %s\n", + ui.RenderMuted(entry.CommitHash[:8]), + ui.RenderMuted(entry.CommitDate.Format("2006-01-02 15:04:05"))) + fmt.Printf(" Author: %s\n", entry.Committer) + + if entry.Issue != nil { + statusIcon := ui.GetStatusIcon(string(entry.Issue.Status)) + fmt.Printf(" %s %s: %s [P%d - %s]\n", + statusIcon, + entry.Issue.ID, + entry.Issue.Title, + entry.Issue.Priority, + entry.Issue.Status) + } + + if i < len(history)-1 { + fmt.Println() + } + } + fmt.Println() + return nil } func init() { @@ -111,8 +121,8 @@ func init() { rootCmd.AddCommand(historyCmd) } -func collectHistoryEvents(ctx context.Context, issueID string, limit int) ([]types.Event, error) { - iter, err := store.IterEvents(ctx, issueID, limit) +func collectHistoryEvents(ctx context.Context, backend historyBackend, issueID string, limit int) ([]types.Event, error) { + iter, err := backend.IterEvents(ctx, issueID, limit) if err != nil { return nil, err } diff --git a/cmd/bd/history_proxied_integration_test.go b/cmd/bd/history_proxied_integration_test.go new file mode 100644 index 000000000..5af6cdb6c --- /dev/null +++ b/cmd/bd/history_proxied_integration_test.go @@ -0,0 +1,259 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func TestProxiedServerHistory(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "hst") + + // Seed: create an issue then mutate it several times to build commit history. + issue := bdProxiedCreate(t, bd, p.dir, "History test issue", "--type", "task", "--priority", "3") + bdProxiedUpdate(t, bd, p.dir, issue.ID, "--status", "in_progress") + bdProxiedUpdate(t, bd, p.dir, issue.ID, "--priority", "1") + bdProxiedUpdate(t, bd, p.dir, issue.ID, "--title", "History test issue updated") + + const missingID = "hst-nonexistent999" + + // historyJSON parses commit-history (or --events) JSON into a generic slice. + historyJSON := func(t *testing.T, args ...string) []map[string]interface{} { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"history", "--json"}, args...)...) + if err != nil { + t.Fatalf("history --json %v: %v\n%s", args, err, out) + } + s := strings.TrimSpace(string(out)) + start := strings.Index(s, "[") + if start < 0 { + return nil + } + var entries []map[string]interface{} + if err := json.Unmarshal([]byte(s[start:]), &entries); err != nil { + t.Fatalf("parse history JSON: %v\n%s", err, s) + } + return entries + } + + // ===== Basic plain-text history ===== + + t.Run("basic_history", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", issue.ID) + if err != nil { + t.Fatalf("history %s: %v\n%s", issue.ID, err, out) + } + s := string(out) + if !strings.Contains(s, issue.ID) { + t.Errorf("expected issue ID in history output: %s", s) + } + if !strings.Contains(s, "History for") { + t.Errorf("expected 'History for' header: %s", s) + } + if !strings.Contains(s, "Author:") { + t.Errorf("expected 'Author:' in history output: %s", s) + } + }) + + t.Run("history_shows_multiple_entries", func(t *testing.T) { + entries := historyJSON(t, issue.ID) + // create + 3 updates = at least 4 commits touching this issue. + if len(entries) < 4 { + t.Errorf("expected at least 4 history entries, got %d", len(entries)) + } + }) + + // ===== --limit restricts entries ===== + + t.Run("limit_restricts_entries", func(t *testing.T) { + entries := historyJSON(t, issue.ID, "--limit", "2") + if len(entries) > 2 { + t.Errorf("expected at most 2 entries with --limit 2, got %d", len(entries)) + } + if len(entries) == 0 { + t.Error("expected at least 1 entry") + } + }) + + t.Run("limit_1", func(t *testing.T) { + entries := historyJSON(t, issue.ID, "--limit", "1") + if len(entries) != 1 { + t.Errorf("expected exactly 1 entry with --limit 1, got %d", len(entries)) + } + }) + + // ===== --events audit output ===== + + t.Run("events_json_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", issue.ID, "--events", "--json") + if err != nil { + t.Fatalf("history --events --json: %v\n%s", err, out) + } + var events []types.Event + if err := json.Unmarshal(out, &events); err != nil { + t.Fatalf("unmarshal events: %v\n%s", err, out) + } + if len(events) == 0 { + t.Fatal("expected non-empty history events") + } + var sawCreated, sawStatus bool + for _, e := range events { + if e.IssueID != issue.ID { + t.Errorf("event for wrong issue: %s", e.IssueID) + } + if e.EventType == types.EventCreated { + sawCreated = true + } + if e.EventType == types.EventStatusChanged { + sawStatus = true + } + } + if !sawCreated { + t.Errorf("expected a %q event, got %+v", types.EventCreated, events) + } + if !sawStatus { + t.Errorf("expected a %q event, got %+v", types.EventStatusChanged, events) + } + }) + + t.Run("events_limit", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", issue.ID, "--events", "--limit", "1", "--json") + if err != nil { + t.Fatalf("history --events --limit 1 --json: %v\n%s", err, out) + } + var events []types.Event + if err := json.Unmarshal(out, &events); err != nil { + t.Fatalf("unmarshal events: %v\n%s", err, out) + } + if len(events) != 1 { + t.Errorf("expected exactly 1 event with --limit 1, got %d", len(events)) + } + }) + + // ===== Commit-history --json shape ===== + + t.Run("json_output_structure", func(t *testing.T) { + entries := historyJSON(t, issue.ID) + if len(entries) == 0 { + t.Fatal("expected non-empty history") + } + e := entries[0] + for _, key := range []string{"CommitHash", "CommitDate", "Committer", "Issue"} { + if _, ok := e[key]; !ok { + t.Errorf("expected %q key in history entry", key) + } + } + }) + + t.Run("json_issue_snapshot_has_fields", func(t *testing.T) { + entries := historyJSON(t, issue.ID) + if len(entries) == 0 { + t.Fatal("expected non-empty history") + } + // Most recent entry should carry the updated title. + issueMap, ok := entries[0]["Issue"].(map[string]interface{}) + if !ok { + t.Fatalf("expected Issue to be a map, got %T", entries[0]["Issue"]) + } + if issueMap["title"] != "History test issue updated" { + t.Errorf("expected latest title 'History test issue updated', got %v", issueMap["title"]) + } + }) + + t.Run("commit_history_wrong_issue_guard", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", issue.ID, "--json") + if err != nil { + t.Fatalf("history --json: %v\n%s", err, out) + } + var entries []struct { + CommitHash string `json:"CommitHash"` + Issue *struct { + ID string `json:"id"` + } `json:"Issue"` + } + if err := json.Unmarshal(out, &entries); err != nil { + t.Fatalf("unmarshal history: %v\n%s", err, out) + } + for _, e := range entries { + if e.CommitHash == "" { + t.Error("entry missing CommitHash") + } + if e.Issue != nil && e.Issue.ID != issue.ID { + t.Errorf("history entry for wrong issue: %s", e.Issue.ID) + } + } + }) + + // ===== Nonexistent issue ===== + + t.Run("nonexistent_issue_empty_history", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", missingID) + if err != nil { + t.Fatalf("history %s: %v\n%s", missingID, err, out) + } + if !strings.Contains(string(out), "No history") { + t.Errorf("expected 'No history' message for nonexistent issue, got: %s", out) + } + }) + + // --json must always produce parseable JSON, even when history is empty. + t.Run("nonexistent_issue_json_returns_empty_array", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", "--json", missingID) + if err != nil { + t.Fatalf("history --json %s: %v\n%s", missingID, err, out) + } + var entries []map[string]interface{} + if err := json.Unmarshal([]byte(strings.TrimSpace(string(out))), &entries); err != nil { + t.Fatalf("expected valid JSON for empty history, got prose:\n%s\n(parse error: %v)", out, err) + } + if len(entries) != 0 { + t.Errorf("expected empty array for nonexistent issue, got %d entries", len(entries)) + } + }) + + // --limit combined with --json on empty history must still parse to empty. + t.Run("nonexistent_issue_json_with_limit_returns_empty_array", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "history", "--json", "--limit", "2", missingID) + if err != nil { + t.Fatalf("history --json --limit 2 %s: %v\n%s", missingID, err, out) + } + var entries []map[string]interface{} + if err := json.Unmarshal([]byte(strings.TrimSpace(string(out))), &entries); err != nil { + t.Fatalf("expected valid JSON for empty history with --limit, got prose:\n%s\n(parse error: %v)", out, err) + } + if len(entries) != 0 { + t.Errorf("expected empty array for nonexistent issue with --limit, got %d entries", len(entries)) + } + }) + + // ===== Argument validation ===== + + t.Run("no_args_fails", func(t *testing.T) { + if out, err := bdProxiedRun(t, bd, p.dir, "history"); err == nil { + t.Fatalf("expected 'history' with no args to fail, got:\n%s", out) + } + }) + + t.Run("too_many_args_fails", func(t *testing.T) { + if out, err := bdProxiedRun(t, bd, p.dir, "history", issue.ID, "extra"); err == nil { + t.Fatalf("expected 'history %s extra' to fail, got:\n%s", issue.ID, out) + } + }) + + // ===== Newly created issue has history ===== + + t.Run("single_entry_for_new_issue", func(t *testing.T) { + fresh := bdProxiedCreate(t, bd, p.dir, "Fresh issue no updates", "--type", "task") + entries := historyJSON(t, fresh.ID) + if len(entries) < 1 { + t.Error("expected at least 1 history entry for a newly created issue") + } + }) +} diff --git a/cmd/bd/history_proxied_server.go b/cmd/bd/history_proxied_server.go new file mode 100644 index 000000000..86adfaa63 --- /dev/null +++ b/cmd/bd/history_proxied_server.go @@ -0,0 +1,15 @@ +package main + +import ( + "context" +) + +func runHistoryProxiedServer(ctx context.Context, issueID string, limit int, showEvents bool) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + return runHistory(ctx, uw.IssueUseCase(), issueID, limit, showEvents) +} diff --git a/cmd/bd/info.go b/cmd/bd/info.go index ae01ef201..75fce7d7d 100644 --- a/cmd/bd/info.go +++ b/cmd/bd/info.go @@ -32,9 +32,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("info is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("info") defer func() { if c := metrics.Global(); c != nil { @@ -55,128 +52,123 @@ Examples: return showWhatsNew() } - // Get database path (absolute) - absDBPath, err := filepath.Abs(dbPath) - if err != nil { - absDBPath = dbPath + if usesProxiedServer() { + return runInfoProxiedServer(rootCtx, schemaFlag) } - // Build info structure + absDBPath := absoluteDBPath() + info := map[string]interface{}{ "database_path": absDBPath, "mode": "direct", } - // Get issue count from direct store if store != nil { ctx := rootCtx - filter := types.IssueFilter{} - issues, err := store.SearchIssues(ctx, "", filter) + issues, err := store.SearchIssues(ctx, "", types.IssueFilter{}) if err == nil { info["issue_count"] = len(issues) } - } - // Add config to info output - if store != nil { - ctx := rootCtx configMap, err := store.GetAllConfig(ctx) if err == nil && len(configMap) > 0 { info["config"] = configMap } - } - // Add schema information if requested - if schemaFlag && store != nil { - ctx := rootCtx - - // Get schema version - schemaVersion, err := store.GetLocalMetadata(ctx, "bd_version") - if err != nil { - schemaVersion = "unknown" - } - - // Get tables - tables := []string{"issues", "dependencies", "labels", "config", "metadata"} - - // Get config - configMap := make(map[string]string) - prefix, _ := store.GetConfig(ctx, "issue_prefix") // Best effort: empty prefix is valid - if prefix != "" { - configMap["issue_prefix"] = prefix - } - - // Get sample issue IDs - filter := types.IssueFilter{} - issues, err := store.SearchIssues(ctx, "", filter) - sampleIDs := []string{} - detectedPrefix := "" - if err == nil && len(issues) > 0 { - // Get first 3 issue IDs as samples - maxSamples := 3 - if len(issues) < maxSamples { - maxSamples = len(issues) + if schemaFlag { + schemaVersion, err := store.GetLocalMetadata(ctx, "bd_version") + if err != nil { + schemaVersion = "unknown" } - for i := 0; i < maxSamples; i++ { - sampleIDs = append(sampleIDs, issues[i].ID) - } - // Detect prefix from first issue - if len(issues) > 0 { - detectedPrefix = extractPrefix(issues[0].ID) - } - } - - info["schema"] = map[string]interface{}{ - "tables": tables, - "schema_version": schemaVersion, - "config": configMap, - "sample_issue_ids": sampleIDs, - "detected_prefix": detectedPrefix, + prefix, _ := store.GetConfig(ctx, "issue_prefix") // Best effort: empty prefix is valid + info["schema"] = buildInfoSchema(schemaVersion, prefix, issues) } } - if jsonOutput { - return outputJSON(info) - } - - fmt.Println("\nBeads Database Information") - fmt.Println("===========================") - fmt.Printf("Database: %s\n", absDBPath) - fmt.Printf("Mode: direct\n") - - // Show issue count - if count, ok := info["issue_count"].(int); ok { - fmt.Printf("\nIssue Count: %d\n", count) - } - - // Show schema information if requested - if schemaFlag { - if schemaInfo, ok := info["schema"].(map[string]interface{}); ok { - fmt.Println("\nSchema Information:") - fmt.Printf(" Tables: %v\n", schemaInfo["tables"]) - if version, ok := schemaInfo["schema_version"].(string); ok { - fmt.Printf(" Schema Version: %s\n", version) - } - if prefix, ok := schemaInfo["detected_prefix"].(string); ok && prefix != "" { - fmt.Printf(" Detected Prefix: %s\n", prefix) - } - if samples, ok := schemaInfo["sample_issue_ids"].([]string); ok && len(samples) > 0 { - fmt.Printf(" Sample Issues: %v\n", samples) - } - } - } - - hookStatuses := CheckGitHooks() - if warning := FormatHookWarnings(hookStatuses); warning != "" { - fmt.Printf("\n%s\n", warning) - } - - fmt.Println() - return nil + return renderInfo(info, schemaFlag, absDBPath) }, } +func absoluteDBPath() string { + absDBPath, err := filepath.Abs(dbPath) + if err != nil { + return dbPath + } + return absDBPath +} + +func buildInfoSchema(schemaVersion, prefix string, issues []*types.Issue) map[string]interface{} { + tables := []string{"issues", "dependencies", "labels", "config", "metadata"} + + configMap := make(map[string]string) + if prefix != "" { + configMap["issue_prefix"] = prefix + } + + sampleIDs := []string{} + detectedPrefix := "" + if len(issues) > 0 { + maxSamples := 3 + if len(issues) < maxSamples { + maxSamples = len(issues) + } + for i := 0; i < maxSamples; i++ { + sampleIDs = append(sampleIDs, issues[i].ID) + } + detectedPrefix = extractPrefix(issues[0].ID) + } + + return map[string]interface{}{ + "tables": tables, + "schema_version": schemaVersion, + "config": configMap, + "sample_issue_ids": sampleIDs, + "detected_prefix": detectedPrefix, + } +} + +func renderInfo(info map[string]interface{}, schemaFlag bool, absDBPath string) error { + if jsonOutput { + return outputJSON(info) + } + + mode, _ := info["mode"].(string) + + fmt.Println("\nBeads Database Information") + fmt.Println("===========================") + fmt.Printf("Database: %s\n", absDBPath) + fmt.Printf("Mode: %s\n", mode) + + if count, ok := info["issue_count"].(int); ok { + fmt.Printf("\nIssue Count: %d\n", count) + } + + if schemaFlag { + if schemaInfo, ok := info["schema"].(map[string]interface{}); ok { + fmt.Println("\nSchema Information:") + fmt.Printf(" Tables: %v\n", schemaInfo["tables"]) + if version, ok := schemaInfo["schema_version"].(string); ok { + fmt.Printf(" Schema Version: %s\n", version) + } + if prefix, ok := schemaInfo["detected_prefix"].(string); ok && prefix != "" { + fmt.Printf(" Detected Prefix: %s\n", prefix) + } + if samples, ok := schemaInfo["sample_issue_ids"].([]string); ok && len(samples) > 0 { + fmt.Printf(" Sample Issues: %v\n", samples) + } + } + } + + hookStatuses := CheckGitHooks() + if warning := FormatHookWarnings(hookStatuses); warning != "" { + fmt.Printf("\n%s\n", warning) + } + + fmt.Println() + return nil +} + // extractPrefix extracts the prefix from an issue ID (e.g., "bd-123" -> "bd") // Uses the last hyphen before a numeric suffix, so "beads-vscode-1" -> "beads-vscode" func extractPrefix(issueID string) string { @@ -1458,6 +1450,5 @@ func init() { infoCmd.Flags().Bool("schema", false, "Include schema information in output") infoCmd.Flags().Bool("whats-new", false, "Show agent-relevant changes from recent versions") infoCmd.Flags().Bool("thanks", false, "Show thank you page for contributors") - infoCmd.Flags().BoolVar(&jsonOutput, "json", false, "Output in JSON format") rootCmd.AddCommand(infoCmd) } diff --git a/cmd/bd/info_proxied_integration_test.go b/cmd/bd/info_proxied_integration_test.go new file mode 100644 index 000000000..ddcd51493 --- /dev/null +++ b/cmd/bd/info_proxied_integration_test.go @@ -0,0 +1,221 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "fmt" + "strings" + "sync" + "testing" +) + +func TestProxiedServerInfo(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "inf") + seedProxiedListData(t, bd, p) + + infoJSON := func(t *testing.T, args ...string) map[string]interface{} { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"info", "--json"}, args...)...) + if err != nil { + t.Fatalf("info %v: %v\n%s", args, err, out) + } + var got map[string]interface{} + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal info: %v\n%s", err, out) + } + return got + } + + infoText := func(t *testing.T, args ...string) string { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"info"}, args...)...) + if err != nil { + t.Fatalf("info %v: %v\n%s", args, err, out) + } + return string(out) + } + + // ===== Default output (JSON: mode, count, config) ===== + + t.Run("mode_and_count", func(t *testing.T) { + got := infoJSON(t) + if got["mode"] != "proxied-server" { + t.Errorf("mode = %v, want proxied-server", got["mode"]) + } + count, ok := got["issue_count"].(float64) + if !ok { + t.Fatalf("issue_count missing/not a number: %v", got["issue_count"]) + } + want := len(bdProxiedListJSON(t, bd, p, "--all")) + if int(count) != want { + t.Errorf("issue_count = %d, want %d (list --all)", int(count), want) + } + if _, ok := got["config"].(map[string]interface{}); !ok { + t.Errorf("expected config map in info output, got %v", got["config"]) + } + }) + + // ===== Default output (human-readable) ===== + + t.Run("info_default_text", func(t *testing.T) { + out := infoText(t) + if !strings.Contains(out, "Issue Count") { + t.Errorf("expected 'Issue Count' in info output: %s", out) + } + if !strings.Contains(out, "Mode: proxied-server") { + t.Errorf("expected proxied-server mode line in info output: %s", out) + } + }) + + // ===== Non-zero issue count with seeded data ===== + + t.Run("info_with_issues", func(t *testing.T) { + got := infoJSON(t) + count, _ := got["issue_count"].(float64) + if int(count) == 0 { + t.Errorf("expected non-zero issue count with seeded data: %v", got["issue_count"]) + } + out := infoText(t) + if strings.Contains(out, "Issue Count: 0") { + t.Errorf("expected non-zero issue count in text output: %s", out) + } + }) + + // ===== --schema (JSON) ===== + + t.Run("schema", func(t *testing.T) { + got := infoJSON(t, "--schema") + schema, ok := got["schema"].(map[string]interface{}) + if !ok { + t.Fatalf("schema block missing: %v", got["schema"]) + } + tables, ok := schema["tables"].([]interface{}) + if !ok { + t.Fatalf("schema tables missing: %v", schema["tables"]) + } + foundIssues := false + for _, tbl := range tables { + if tbl == "issues" { + foundIssues = true + } + } + if !foundIssues { + t.Errorf("expected 'issues' table in schema tables, got %v", tables) + } + if v, _ := schema["schema_version"].(string); v == "" || v == "unknown" { + t.Errorf("schema_version = %q, want a resolved bd_version", v) + } + samples, ok := schema["sample_issue_ids"].([]interface{}) + if !ok || len(samples) == 0 { + t.Errorf("expected sample_issue_ids, got %v", schema["sample_issue_ids"]) + } + if pfx, _ := schema["detected_prefix"].(string); pfx == "" { + t.Errorf("expected a detected_prefix, got empty") + } + }) + + // ===== --schema (human-readable) ===== + + t.Run("schema_text", func(t *testing.T) { + out := infoText(t, "--schema") + if !strings.Contains(out, "issues") { + t.Errorf("expected 'issues' table in schema output: %s", out) + } + if !strings.Contains(out, "Schema") { + t.Errorf("expected 'Schema' heading in schema output: %s", out) + } + }) + + // ===== --whats-new (static, version-independent of storage mode) ===== + + t.Run("whats_new_text", func(t *testing.T) { + out := infoText(t, "--whats-new") + if len(strings.TrimSpace(out)) == 0 { + t.Error("expected non-empty --whats-new output") + } + if !strings.Contains(out, "v0.") { + t.Errorf("expected a version string in whats-new output: %s", out[:min(200, len(out))]) + } + }) + + t.Run("whats_new_json", func(t *testing.T) { + got := infoJSON(t, "--whats-new") + if _, ok := got["current_version"]; !ok { + t.Errorf("expected 'current_version' in whats-new JSON: %v", got) + } + if _, ok := got["recent_changes"]; !ok { + t.Errorf("expected 'recent_changes' in whats-new JSON: %v", got) + } + }) + + // ===== --thanks (static) ===== + + t.Run("thanks", func(t *testing.T) { + out := infoText(t, "--thanks") + if len(strings.TrimSpace(out)) == 0 { + t.Error("expected non-empty --thanks output") + } + }) +} + +// TestProxiedServerInfoConcurrent exercises info operations concurrently +// through the proxied server. +func TestProxiedServerInfoConcurrent(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "ixc") + + for i := 0; i < 3; i++ { + bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("info-concurrent-%d", i), "--type", "task") + } + + const numWorkers = 8 + + type workerResult struct { + worker int + err error + } + + results := make([]workerResult, numWorkers) + var wg sync.WaitGroup + wg.Add(numWorkers) + + for w := 0; w < numWorkers; w++ { + go func(worker int) { + defer wg.Done() + r := workerResult{worker: worker} + + var args []string + switch worker % 3 { + case 0: + args = []string{"info"} + case 1: + args = []string{"info", "--schema"} + case 2: + args = []string{"info", "--whats-new"} + } + out, err := bdProxiedRun(t, bd, p.dir, args...) + if err != nil { + r.err = fmt.Errorf("info (worker %d): %v\n%s", worker, err, out) + results[worker] = r + return + } + if len(strings.TrimSpace(string(out))) == 0 { + r.err = fmt.Errorf("info (worker %d): empty output", worker) + } + results[worker] = r + }(w) + } + wg.Wait() + + for _, r := range results { + if r.err != nil && !strings.Contains(r.err.Error(), "one writer at a time") { + t.Errorf("worker %d failed: %v", r.worker, r.err) + } + } +} diff --git a/cmd/bd/info_proxied_server.go b/cmd/bd/info_proxied_server.go new file mode 100644 index 000000000..440be2b92 --- /dev/null +++ b/cmd/bd/info_proxied_server.go @@ -0,0 +1,45 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +func runInfoProxiedServer(ctx context.Context, schemaFlag bool) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + absDBPath := absoluteDBPath() + + info := map[string]interface{}{ + "database_path": absDBPath, + "mode": "proxied-server", + } + + page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{}) + var issues []*types.Issue + if err == nil { + issues = page.Items + info["issue_count"] = len(issues) + } + + configMap, err := uw.ConfigUseCase().GetAllConfig(ctx) + if err == nil && len(configMap) > 0 { + info["config"] = configMap + } + + if schemaFlag { + schemaVersion, err := uw.ConfigUseCase().GetLocalMetadata(ctx, "bd_version") + if err != nil { + schemaVersion = "unknown" + } + prefix, _ := uw.ConfigUseCase().GetConfig(ctx, "issue_prefix") + info["schema"] = buildInfoSchema(schemaVersion, prefix, issues) + } + + return renderInfo(info, schemaFlag, absDBPath) +} diff --git a/cmd/bd/lint.go b/cmd/bd/lint.go index 86b983f56..e414de9ee 100644 --- a/cmd/bd/lint.go +++ b/cmd/bd/lint.go @@ -1,6 +1,7 @@ package main import ( + "context" "encoding/json" "fmt" "os" @@ -45,9 +46,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("lint is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("lint") defer func() { if c := metrics.Global(); c != nil { @@ -55,116 +53,132 @@ Examples: } }() - ctx := rootCtx - typeFilter, _ := cmd.Flags().GetString("type") statusFilter, _ := cmd.Flags().GetString("status") - var issues []*types.Issue + if usesProxiedServer() { + return runLintProxiedServer(rootCtx, args, typeFilter, statusFilter) + } + ctx := rootCtx if store == nil { return HandleErrorWithHint("database not initialized", diagHint()) } + var issues []*types.Issue if len(args) > 0 { - for _, id := range args { - issue, err := store.GetIssue(ctx, id) - if err != nil { - fmt.Fprintf(os.Stderr, "Error getting %s: %v\n", id, err) - continue - } - if issue == nil { - fmt.Fprintf(os.Stderr, "Issue not found: %s\n", id) - continue - } - issues = append(issues, issue) - } + issues = lintCollectByIDs(ctx, args, store.GetIssue) } else { - filter := types.IssueFilter{} - - if statusFilter == "" || statusFilter == "open" { - s := types.StatusOpen - filter.Status = &s - } else if statusFilter != "all" { - s := types.Status(statusFilter) - filter.Status = &s - } - - if typeFilter != "" { - t := types.IssueType(typeFilter) - filter.IssueType = &t - } - var err error - issues, err = store.SearchIssues(ctx, "", filter) + issues, err = store.SearchIssues(ctx, "", buildLintFilter(typeFilter, statusFilter)) if err != nil { return HandleError("%v", err) } } - var results []LintResult - totalWarnings := 0 - - for _, issue := range issues { - err := validation.LintIssue(issue) - if err == nil { - continue - } - - templateErr, ok := err.(*validation.TemplateError) - if !ok { - continue - } - - missing := make([]string, len(templateErr.Missing)) - for i, m := range templateErr.Missing { - missing[i] = m.Heading - } - - result := LintResult{ - ID: issue.ID, - Title: issue.Title, - Type: string(issue.IssueType), - Missing: missing, - Warnings: len(missing), - } - results = append(results, result) - totalWarnings += len(missing) - } - - if jsonOutput { - output := struct { - Total int `json:"total"` - Issues int `json:"issues"` - Results []LintResult `json:"results"` - }{ - Total: totalWarnings, - Issues: len(results), - Results: results, - } - data, _ := json.MarshalIndent(output, "", " ") - fmt.Println(string(data)) - return nil - } - - if len(results) == 0 { - fmt.Printf("✓ No template warnings found (%d issues checked)\n", len(issues)) - return nil - } - - fmt.Printf("Template warnings (%d issues, %d warnings):\n\n", len(results), totalWarnings) - for _, r := range results { - fmt.Printf("%s [%s]: %s\n", r.ID, r.Type, r.Title) - for _, m := range r.Missing { - fmt.Printf(" ⚠ Missing: %s\n", m) - } - fmt.Println() - } - - return SilentExit() + return runLint(issues) }, } +func buildLintFilter(typeFilter, statusFilter string) types.IssueFilter { + filter := types.IssueFilter{} + + if statusFilter == "" || statusFilter == "open" { + s := types.StatusOpen + filter.Status = &s + } else if statusFilter != "all" { + s := types.Status(statusFilter) + filter.Status = &s + } + + if typeFilter != "" { + t := types.IssueType(typeFilter) + filter.IssueType = &t + } + + return filter +} + +func lintCollectByIDs(ctx context.Context, ids []string, get func(context.Context, string) (*types.Issue, error)) []*types.Issue { + var issues []*types.Issue + for _, id := range ids { + issue, err := get(ctx, id) + if err != nil { + fmt.Fprintf(os.Stderr, "Error getting %s: %v\n", id, err) + continue + } + if issue == nil { + fmt.Fprintf(os.Stderr, "Issue not found: %s\n", id) + continue + } + issues = append(issues, issue) + } + return issues +} + +func runLint(issues []*types.Issue) error { + var results []LintResult + totalWarnings := 0 + + for _, issue := range issues { + err := validation.LintIssue(issue) + if err == nil { + continue + } + + templateErr, ok := err.(*validation.TemplateError) + if !ok { + continue + } + + missing := make([]string, len(templateErr.Missing)) + for i, m := range templateErr.Missing { + missing[i] = m.Heading + } + + result := LintResult{ + ID: issue.ID, + Title: issue.Title, + Type: string(issue.IssueType), + Missing: missing, + Warnings: len(missing), + } + results = append(results, result) + totalWarnings += len(missing) + } + + if jsonOutput { + output := struct { + Total int `json:"total"` + Issues int `json:"issues"` + Results []LintResult `json:"results"` + }{ + Total: totalWarnings, + Issues: len(results), + Results: results, + } + data, _ := json.MarshalIndent(output, "", " ") + fmt.Println(string(data)) + return nil + } + + if len(results) == 0 { + fmt.Printf("✓ No template warnings found (%d issues checked)\n", len(issues)) + return nil + } + + fmt.Printf("Template warnings (%d issues, %d warnings):\n\n", len(results), totalWarnings) + for _, r := range results { + fmt.Printf("%s [%s]: %s\n", r.ID, r.Type, r.Title) + for _, m := range r.Missing { + fmt.Printf(" ⚠ Missing: %s\n", m) + } + fmt.Println() + } + + return SilentExit() +} + func init() { lintCmd.Flags().StringP("type", "t", "", "Filter by issue type (bug, task, feature, epic, decision, spike, story, chore, milestone)") lintCmd.Flags().StringP("status", "s", "", "Filter by status (default: open, use 'all' for all)") diff --git a/cmd/bd/lint_proxied_server.go b/cmd/bd/lint_proxied_server.go new file mode 100644 index 000000000..e0c228b7e --- /dev/null +++ b/cmd/bd/lint_proxied_server.go @@ -0,0 +1,28 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +func runLintProxiedServer(ctx context.Context, args []string, typeFilter, statusFilter string) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + var issues []*types.Issue + if len(args) > 0 { + issues = lintCollectByIDs(ctx, args, uw.IssueUseCase().GetIssue) + } else { + page, err := uw.IssueUseCase().SearchIssues(ctx, "", buildLintFilter(typeFilter, statusFilter)) + if err != nil { + return HandleError("%v", err) + } + issues = page.Items + } + + return runLint(issues) +} diff --git a/cmd/bd/lint_stale_proxied_integration_test.go b/cmd/bd/lint_stale_proxied_integration_test.go new file mode 100644 index 000000000..8a3942438 --- /dev/null +++ b/cmd/bd/lint_stale_proxied_integration_test.go @@ -0,0 +1,356 @@ +//go:build cgo + +package main + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" +) + +func TestProxiedServerLint(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "lnt") + + // Seed mirrors cmd/bd/lint_embedded_test.go. + // Bug without template sections -> warning. + bugBare := bdProxiedCreate(t, bd, p.dir, "Bug without template", "--type", "bug", + "--description", "Something is broken") + // Bug with the required sections -> no warning. + bugGood := bdProxiedCreate(t, bd, p.dir, "Bug with template", "--type", "bug", + "--description", "## Steps to Reproduce\n1. Do X\n2. See Y\n\n## Acceptance Criteria\nShould not crash") + // Task without acceptance criteria -> warning. + taskBare := bdProxiedCreate(t, bd, p.dir, "Task without AC", "--type", "task", + "--description", "Just do it") + // Chore -> never warns. + bdProxiedCreate(t, bd, p.dir, "Chore is fine", "--type", "chore") + // Feature without AC -> warning. + bdProxiedCreate(t, bd, p.dir, "Feature no AC", "--type", "feature", + "--description", "Add dark mode") + // Closed bare bug for --status all coverage. + closedBug := bdProxiedCreate(t, bd, p.dir, "Closed bug bare", "--type", "bug", + "--description", "Old bug") + if out, err := bdProxiedRun(t, bd, p.dir, "close", closedBug.ID); err != nil { + t.Fatalf("close %s: %v\n%s", closedBug.ID, err, out) + } + + type lintOutput struct { + Total int `json:"total"` + Issues int `json:"issues"` + Results []LintResult `json:"results"` + } + lintJSON := func(t *testing.T, args ...string) lintOutput { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"lint", "--json"}, args...)...) + if err != nil { + t.Fatalf("lint %v: %v\n%s", args, err, out) + } + var got lintOutput + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal lint: %v\n%s", err, out) + } + return got + } + hasID := func(results []LintResult, id string) bool { + for i := range results { + if results[i].ID == id { + return true + } + } + return false + } + + t.Run("specific_id_with_warnings", func(t *testing.T) { + got := lintJSON(t, bugBare.ID) + if got.Total == 0 { + t.Error("expected warnings for bare bug") + } + if len(got.Results) == 0 { + t.Error("expected results for bare bug") + } + if got.Issues != 1 || len(got.Results) != 1 || got.Results[0].ID != bugBare.ID { + t.Errorf("lint %s = %+v, want single result for that id", bugBare.ID, got) + } + }) + + t.Run("specific_id_clean", func(t *testing.T) { + got := lintJSON(t, bugGood.ID) + if got.Total != 0 { + t.Errorf("expected 0 warnings for well-formatted bug, got %d", got.Total) + } + }) + + t.Run("multiple_ids", func(t *testing.T) { + got := lintJSON(t, bugBare.ID, taskBare.ID) + if got.Issues < 2 { + t.Errorf("expected at least 2 issues with warnings, got %d", got.Issues) + } + }) + + t.Run("by_type_bug", func(t *testing.T) { + got := lintJSON(t, "--type", "bug") + if !hasID(got.Results, bugBare.ID) { + t.Errorf("expected bare bug %s in --type bug results", bugBare.ID) + } + }) + + t.Run("by_type_chore_no_warnings", func(t *testing.T) { + got := lintJSON(t, "--type", "chore") + if got.Total != 0 { + t.Errorf("expected 0 warnings for chores, got %d", got.Total) + } + }) + + t.Run("status_all_includes_closed", func(t *testing.T) { + got := lintJSON(t, "--status", "all") + if !hasID(got.Results, closedBug.ID) { + t.Errorf("expected closed bug %s in --status all results", closedBug.ID) + } + }) + + t.Run("status_default_excludes_closed", func(t *testing.T) { + got := lintJSON(t) + if hasID(got.Results, closedBug.ID) { + t.Errorf("closed bug %s should be excluded by default", closedBug.ID) + } + }) + + t.Run("clean_issues_not_in_results", func(t *testing.T) { + got := lintJSON(t) + if hasID(got.Results, bugGood.ID) { + t.Errorf("well-formatted bug %s should not have warnings", bugGood.ID) + } + }) + + t.Run("json_missing_sections", func(t *testing.T) { + got := lintJSON(t, bugBare.ID) + if len(got.Results) == 0 { + t.Fatal("expected results") + } + if len(got.Results[0].Missing) == 0 { + t.Error("expected non-empty 'missing' array for bare bug") + } + }) + + t.Run("exit_code_1_on_warnings", func(t *testing.T) { + // Non-JSON lint returns SilentExit (exit 1) when warnings exist. + out, err := bdProxiedRun(t, bd, p.dir, "lint") + if err == nil { + t.Errorf("expected non-zero exit when warnings exist, got success:\n%s", out) + } + }) + + t.Run("exit_code_0_when_clean", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "lint", "--type", "chore") + if err != nil { + t.Errorf("expected exit 0 for chores, got err %v:\n%s", err, out) + } + }) + + t.Run("nonexistent_id_graceful", func(t *testing.T) { + // Unknown ids are logged to stderr and skipped; the command still succeeds + // with zero warnings. + got := lintJSON(t, p.prefix+"-nonexistent999") + if got.Total != 0 { + t.Errorf("expected 0 warnings for nonexistent issue, got %d", got.Total) + } + }) + + t.Run("human_readable_warnings", func(t *testing.T) { + out, _ := bdProxiedRun(t, bd, p.dir, "lint") + if !strings.Contains(string(out), "Missing:") { + t.Errorf("expected 'Missing:' in human output: %s", out) + } + }) + + t.Run("human_readable_clean", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "lint", "--type", "chore") + if err != nil { + t.Fatalf("lint --type chore: %v\n%s", err, out) + } + if !strings.Contains(string(out), "No template warnings") { + t.Errorf("expected 'No template warnings' for chores: %s", out) + } + }) +} + +func TestProxiedServerStale(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "stl") + + // Seed mirrors cmd/bd/stale_embedded_test.go. + stale1 := bdProxiedCreate(t, bd, p.dir, "Stale open issue", "--type", "task") + stale2 := bdProxiedCreate(t, bd, p.dir, "Stale in_progress issue", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, stale2.ID, "--status", "in_progress") + stale3 := bdProxiedCreate(t, bd, p.dir, "Stale bug", "--type", "bug", "--assignee", "alice") + fresh1 := bdProxiedCreate(t, bd, p.dir, "Fresh issue", "--type", "task") + closedIssue := bdProxiedCreate(t, bd, p.dir, "Closed issue", "--type", "task") + if out, err := bdProxiedRun(t, bd, p.dir, "close", closedIssue.ID); err != nil { + t.Fatalf("close %s: %v\n%s", closedIssue.ID, err, out) + } + + // Backdate updated_at to 60 days ago for the three "stale" issues. Done last + // so the status change above does not overwrite the backdated timestamp. + db := openProxiedDB(t, p) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + backdate := time.Now().UTC().AddDate(0, 0, -60) + for _, id := range []string{stale1.ID, stale2.ID, stale3.ID} { + if _, err := db.ExecContext(ctx, + "UPDATE issues SET updated_at = ? WHERE id = ?", backdate, id); err != nil { + t.Fatalf("backdate updated_at for %s: %v", id, err) + } + } + + staleEntries := func(t *testing.T, args ...string) []map[string]interface{} { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"stale", "--json"}, args...)...) + if err != nil { + t.Fatalf("stale %v: %v\n%s", args, err, out) + } + var entries []map[string]interface{} + if err := json.Unmarshal(out, &entries); err != nil { + t.Fatalf("unmarshal stale: %v\n%s", err, out) + } + return entries + } + idSet := func(entries []map[string]interface{}) map[string]bool { + set := make(map[string]bool, len(entries)) + for _, e := range entries { + if id, ok := e["id"].(string); ok { + set[id] = true + } + } + return set + } + + t.Run("basic_stale_default_days", func(t *testing.T) { + entries := staleEntries(t) + if len(entries) < 3 { + t.Errorf("expected at least 3 stale issues, got %d", len(entries)) + } + if idSet(entries)[fresh1.ID] { + t.Errorf("fresh issue %s should not be stale", fresh1.ID) + } + }) + + t.Run("custom_days_above_cutoff", func(t *testing.T) { + // Issues are 60 days stale, so --days 90 finds none. + entries := staleEntries(t, "--days", "90") + if len(entries) != 0 { + t.Errorf("expected 0 stale issues at 90 days, got %d", len(entries)) + } + }) + + t.Run("custom_days_lower", func(t *testing.T) { + entries := staleEntries(t, "--days", "1") + if len(entries) < 3 { + t.Errorf("expected at least 3 stale issues at 1 day, got %d", len(entries)) + } + }) + + t.Run("status_filter_in_progress", func(t *testing.T) { + entries := staleEntries(t, "--status", "in_progress") + if !idSet(entries)[stale2.ID] { + t.Errorf("expected stale in_progress issue %s in results", stale2.ID) + } + }) + + t.Run("status_filter_open", func(t *testing.T) { + entries := staleEntries(t, "--status", "open") + if idSet(entries)[stale2.ID] { + t.Errorf("in_progress issue %s should not appear with --status open", stale2.ID) + } + }) + + t.Run("limit_caps_results", func(t *testing.T) { + entries := staleEntries(t, "--limit", "1") + if len(entries) > 1 { + t.Errorf("expected at most 1 result with --limit 1, got %d", len(entries)) + } + }) + + t.Run("json_output_is_array", func(t *testing.T) { + entries := staleEntries(t) + if entries == nil { + t.Error("expected non-nil JSON array") + } + }) + + t.Run("json_issue_has_fields", func(t *testing.T) { + entries := staleEntries(t) + if len(entries) == 0 { + t.Skip("no stale issues to check") + } + for _, key := range []string{"id", "title", "status"} { + if _, ok := entries[0][key]; !ok { + t.Errorf("expected %q key in stale issue JSON", key) + } + } + }) + + t.Run("no_stale_issues_message", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "stale", "--days", "90") + if err != nil { + t.Fatalf("stale --days 90: %v\n%s", err, out) + } + if !strings.Contains(string(out), "No stale issues") { + t.Errorf("expected 'No stale issues' message: %s", out) + } + }) + + t.Run("invalid_days_zero", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "stale", "--days", "0") + if err == nil { + t.Fatalf("expected error for --days 0, got success: %s", out) + } + if !strings.Contains(string(out), "at least 1") { + t.Errorf("expected 'at least 1' error: %s", out) + } + }) + + t.Run("invalid_status", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "stale", "--status", "bogus") + if err == nil { + t.Fatalf("expected error for --status bogus, got success: %s", out) + } + if !strings.Contains(string(out), "invalid status") { + t.Errorf("expected 'invalid status' error: %s", out) + } + }) + + t.Run("boundary_exact_cutoff", func(t *testing.T) { + entries60 := staleEntries(t, "--days", "60") + entries61 := staleEntries(t, "--days", "61") + if len(entries60) < len(entries61) { + t.Errorf("--days 60 should find >= issues than --days 61: got %d vs %d", len(entries60), len(entries61)) + } + }) + + t.Run("human_readable_format", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "stale") + if err != nil { + t.Fatalf("stale: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "Stale issues") { + t.Errorf("expected 'Stale issues' header: %s", s) + } + if !strings.Contains(s, "days ago") { + t.Errorf("expected 'days ago' in output: %s", s) + } + }) + + t.Run("closed_issues_excluded", func(t *testing.T) { + entries := staleEntries(t) + if idSet(entries)[closedIssue.ID] { + t.Errorf("closed issue %s should not appear in stale results", closedIssue.ID) + } + }) +} diff --git a/cmd/bd/orphans.go b/cmd/bd/orphans.go index bd93ce7d7..5f6ffa9d0 100644 --- a/cmd/bd/orphans.go +++ b/cmd/bd/orphans.go @@ -44,9 +44,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("orphans is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("orphans") defer func() { if c := metrics.Global(); c != nil { @@ -54,67 +51,74 @@ Examples: } }() - path := "." labels, _ := cmd.Flags().GetStringSlice("label") labelsAny, _ := cmd.Flags().GetStringSlice("label-any") labels = utils.NormalizeLabels(labels) labelsAny = utils.NormalizeLabels(labelsAny) - orphans, err := findOrphanedIssues(path, labels, labelsAny) + fix, _ := cmd.Flags().GetBool("fix") + details, _ := cmd.Flags().GetBool("details") + + if usesProxiedServer() { + return runOrphansProxiedServer(rootCtx, labels, labelsAny, fix, details) + } + + orphans, err := findOrphanedIssues(".", labels, labelsAny) if err != nil { return HandleErrorRespectJSON("%v", err) } - fix, _ := cmd.Flags().GetBool("fix") - details, _ := cmd.Flags().GetBool("details") + return reportOrphans(orphans, fix, details) + }, +} - if jsonOutput { - return outputJSON(orphans) +func reportOrphans(orphans []orphanIssueOutput, fix, details bool) error { + if jsonOutput { + return outputJSON(orphans) + } + + if len(orphans) == 0 { + fmt.Printf("%s No orphaned issues found\n", ui.RenderPass("✓")) + return nil + } + + fmt.Printf("\n%s Found %d orphaned issue(s):\n\n", ui.RenderWarn("⚠"), len(orphans)) + + sort.Slice(orphans, func(i, j int) bool { + return orphans[i].IssueID < orphans[j].IssueID + }) + + for i, orphan := range orphans { + fmt.Printf("%d. %s: %s\n", i+1, ui.RenderID(orphan.IssueID), orphan.Title) + fmt.Printf(" Status: %s\n", orphan.Status) + if details && orphan.LatestCommit != "" { + fmt.Printf(" Latest commit: %s - %s\n", orphan.LatestCommit, orphan.LatestCommitMessage) } + } - if len(orphans) == 0 { - fmt.Printf("%s No orphaned issues found\n", ui.RenderPass("✓")) + if fix { + fmt.Println() + fmt.Printf("This will close %d orphaned issue(s). Continue? (Y/n): ", len(orphans)) + var response string + _, _ = fmt.Scanln(&response) + response = strings.ToLower(strings.TrimSpace(response)) + if response != "" && response != "y" && response != "yes" { + fmt.Println("Canceled.") return nil } - fmt.Printf("\n%s Found %d orphaned issue(s):\n\n", ui.RenderWarn("⚠"), len(orphans)) - - sort.Slice(orphans, func(i, j int) bool { - return orphans[i].IssueID < orphans[j].IssueID - }) - - for i, orphan := range orphans { - fmt.Printf("%d. %s: %s\n", i+1, ui.RenderID(orphan.IssueID), orphan.Title) - fmt.Printf(" Status: %s\n", orphan.Status) - if details && orphan.LatestCommit != "" { - fmt.Printf(" Latest commit: %s - %s\n", orphan.LatestCommit, orphan.LatestCommitMessage) + closedCount := 0 + for _, orphan := range orphans { + err := closeIssue(orphan.IssueID) + if err != nil { + fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", orphan.IssueID, err) + } else { + fmt.Printf("✓ Closed %s\n", orphan.IssueID) + closedCount++ } } - - if fix { - fmt.Println() - fmt.Printf("This will close %d orphaned issue(s). Continue? (Y/n): ", len(orphans)) - var response string - _, _ = fmt.Scanln(&response) - response = strings.ToLower(strings.TrimSpace(response)) - if response != "" && response != "y" && response != "yes" { - fmt.Println("Canceled.") - return nil - } - - closedCount := 0 - for _, orphan := range orphans { - err := closeIssue(orphan.IssueID) - if err != nil { - fmt.Fprintf(os.Stderr, "Error closing %s: %v\n", orphan.IssueID, err) - } else { - fmt.Printf("✓ Closed %s\n", orphan.IssueID) - closedCount++ - } - } - fmt.Printf("\nClosed %d issue(s)\n", closedCount) - } - return nil - }, + fmt.Printf("\nClosed %d issue(s)\n", closedCount) + } + return nil } // orphanIssueOutput is the JSON output format for orphaned issues @@ -193,6 +197,10 @@ func findOrphanedIssues(path string, labels, labelsAny []string) ([]orphanIssueO } defer cleanup() + return findOrphanedIssuesWithProvider(path, provider) +} + +func findOrphanedIssuesWithProvider(path string, provider types.IssueProvider) ([]orphanIssueOutput, error) { orphans, err := doctorFindOrphanedIssues(path, provider) if err != nil { return nil, fmt.Errorf("unable to find orphaned issues: %w", err) diff --git a/cmd/bd/orphans_proxied_integration_test.go b/cmd/bd/orphans_proxied_integration_test.go new file mode 100644 index 000000000..9b19fbf3a --- /dev/null +++ b/cmd/bd/orphans_proxied_integration_test.go @@ -0,0 +1,125 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "os/exec" + "strings" + "testing" +) + +func TestProxiedServerOrphans(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "orp") + + gitCommit := func(t *testing.T, message string) { + t.Helper() + cmd := exec.Command("git", "commit", "--allow-empty", "-m", message) + cmd.Dir = p.dir + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git commit: %v\n%s", err, out) + } + } + + orphanIDs := func(t *testing.T, args ...string) map[string]bool { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"orphans", "--json"}, args...)...) + if err != nil { + t.Fatalf("orphans %v: %v\n%s", args, err, out) + } + if !json.Valid(out) { + t.Fatalf("invalid JSON: %s", out) + } + var orphans []orphanIssueOutput + if err := json.Unmarshal(out, &orphans); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + set := make(map[string]bool, len(orphans)) + for _, o := range orphans { + set[o.IssueID] = true + } + return set + } + + // An open issue referenced by a commit message is an orphan. + referenced := bdProxiedCreate(t, bd, p.dir, "Referenced but never closed", "--type", "task") + unreferenced := bdProxiedCreate(t, bd, p.dir, "Never mentioned", "--type", "task") + // Give the referenced issue a label so --label can select it. + bdProxiedLabel(t, bd, p.dir, "add", referenced.ID, "theme:personal") + gitCommit(t, "feat: implemented ("+referenced.ID+")") + + t.Run("detects_referenced_open_issue", func(t *testing.T) { + got := orphanIDs(t) + if !got[referenced.ID] { + t.Errorf("expected orphan %s (referenced in a commit, still open), got %v", referenced.ID, got) + } + if got[unreferenced.ID] { + t.Errorf("did not expect unreferenced issue %s as orphan", unreferenced.ID) + } + }) + + // Plain (non-JSON) default output must succeed and mention the orphan. + t.Run("default_plain_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "orphans") + if err != nil { + t.Fatalf("orphans: %v\n%s", err, out) + } + if !strings.Contains(string(out), referenced.ID) { + t.Errorf("expected default output to mention %s, got:\n%s", referenced.ID, out) + } + }) + + // --json on a db with orphans must still produce valid JSON. + t.Run("json_valid", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "orphans", "--json") + if err != nil { + t.Fatalf("orphans --json: %v\n%s", err, out) + } + if !json.Valid(out) { + t.Errorf("invalid JSON in orphans --json output: %s", out) + } + }) + + // --details should succeed and include the orphan. + t.Run("details", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "orphans", "--details") + if err != nil { + t.Fatalf("orphans --details: %v\n%s", err, out) + } + if !strings.Contains(string(out), referenced.ID) { + t.Errorf("expected --details output to mention %s, got:\n%s", referenced.ID, out) + } + }) + + t.Run("label_filter_excludes", func(t *testing.T) { + // referenced lacks this label, so a label filter should drop it. + got := orphanIDs(t, "--label", "nonexistent-label-xyz") + if got[referenced.ID] { + t.Errorf("label filter should have excluded %s, got %v", referenced.ID, got) + } + }) + + t.Run("label_filter_includes", func(t *testing.T) { + // referenced carries theme:personal, so a matching filter keeps it. + got := orphanIDs(t, "--label", "theme:personal") + if !got[referenced.ID] { + t.Errorf("label filter should have included %s, got %v", referenced.ID, got) + } + }) + + t.Run("label_any_filter", func(t *testing.T) { + // --label-any is OR semantics; theme:personal matches referenced. + got := orphanIDs(t, "--label-any", "theme:personal,theme:ventures") + if !got[referenced.ID] { + t.Errorf("--label-any should have included %s, got %v", referenced.ID, got) + } + // A label-any set with no matches must produce valid JSON and no referenced orphan. + none := orphanIDs(t, "--label-any", "nonexistent-label-xyz") + if none[referenced.ID] { + t.Errorf("--label-any with no matching label should exclude %s, got %v", referenced.ID, none) + } + }) +} diff --git a/cmd/bd/orphans_proxied_server.go b/cmd/bd/orphans_proxied_server.go new file mode 100644 index 000000000..a1fe0777c --- /dev/null +++ b/cmd/bd/orphans_proxied_server.go @@ -0,0 +1,65 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" +) + +func runOrphansProxiedServer(ctx context.Context, labels, labelsAny []string, fix, details bool) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + provider := &uowIssueProvider{uw: uw, ctx: ctx, labels: labels, labelsAny: labelsAny} + orphans, err := findOrphanedIssuesWithProvider(".", provider) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + return reportOrphans(orphans, fix, details) +} + +type uowIssueProvider struct { + uw uow.UnitOfWork + ctx context.Context + labels []string + labelsAny []string +} + +func (p *uowIssueProvider) GetOpenIssues(ctx context.Context) ([]*types.Issue, error) { + openStatus := types.StatusOpen + openPage, err := p.uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{ + Status: &openStatus, + Labels: p.labels, + LabelsAny: p.labelsAny, + }) + if err != nil { + return nil, err + } + inProgressStatus := types.StatusInProgress + inProgressPage, err := p.uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{ + Status: &inProgressStatus, + Labels: p.labels, + LabelsAny: p.labelsAny, + }) + if err != nil { + return nil, err + } + return append(openPage.Items, inProgressPage.Items...), nil +} + +func (p *uowIssueProvider) GetIssuePrefix() string { + if yamlPrefix := config.GetString("issue-prefix"); yamlPrefix != "" { + return yamlPrefix + } + prefix, err := p.uw.ConfigUseCase().GetConfig(p.ctx, "issue_prefix") + if err != nil || prefix == "" { + return "bd" + } + return prefix +} diff --git a/cmd/bd/reclaim.go b/cmd/bd/reclaim.go index 1c18a5434..c0d1c78fa 100644 --- a/cmd/bd/reclaim.go +++ b/cmd/bd/reclaim.go @@ -7,6 +7,7 @@ import ( "github.com/steveyegge/beads/internal/metrics" "github.com/steveyegge/beads/internal/storage/issueops" + "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -36,11 +37,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("reclaim is not supported in proxied-server mode") - } - CheckReadonly("reclaim") - evt := metrics.NewCommandEvent("reclaim") defer func() { if c := metrics.Global(); c != nil { @@ -53,6 +49,12 @@ Examples: return HandleErrorRespectJSON("--older-than must not be negative") } + CheckReadonly("reclaim") + + if usesProxiedServer() { + return runReclaimProxiedServer(rootCtx, olderThan) + } + ctx := rootCtx reclaimed, err := store.ReclaimExpiredLeases(ctx, olderThan, actor) if err != nil { @@ -70,28 +72,32 @@ Examples: return HandleErrorRespectJSON("failed to commit: %v", err) } - if jsonOutput { - return outputJSON(map[string]interface{}{ - "reclaimed": reclaimed, - "count": len(reclaimed), - }) - } - if len(reclaimed) == 0 { - fmt.Printf("%s No stale leases to reclaim\n", ui.RenderPass("✓")) - return nil - } - fmt.Printf("%s Reclaimed %d stale-lease issue(s):\n", ui.RenderPass("✓"), len(reclaimed)) - for _, r := range reclaimed { - owner := r.PreviousOwner - if owner == "" { - owner = "(unassigned)" - } - fmt.Printf(" %s (was held by %s)\n", r.ID, owner) - } - return nil + return renderReclaim(reclaimed) }, } +func renderReclaim(reclaimed []types.ReclaimedLease) error { + if jsonOutput { + return outputJSON(map[string]interface{}{ + "reclaimed": reclaimed, + "count": len(reclaimed), + }) + } + if len(reclaimed) == 0 { + fmt.Printf("%s No stale leases to reclaim\n", ui.RenderPass("✓")) + return nil + } + fmt.Printf("%s Reclaimed %d stale-lease issue(s):\n", ui.RenderPass("✓"), len(reclaimed)) + for _, r := range reclaimed { + owner := r.PreviousOwner + if owner == "" { + owner = "(unassigned)" + } + fmt.Printf(" %s (was held by %s)\n", r.ID, owner) + } + return nil +} + func init() { reclaimCmd.Flags().Duration("older-than", 2*issueops.DefaultLeaseTTL, "Only reclaim leases that expired at least this long ago (grace window)") diff --git a/cmd/bd/set_state_proxied_integration_test.go b/cmd/bd/set_state_proxied_integration_test.go new file mode 100644 index 000000000..ec8695c41 --- /dev/null +++ b/cmd/bd/set_state_proxied_integration_test.go @@ -0,0 +1,178 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestProxiedServerSetState(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "sst") + issue := bdProxiedCreate(t, bd, p.dir, "Set-state target") + + setStateJSON := func(t *testing.T, spec string, extra ...string) map[string]interface{} { + t.Helper() + args := append([]string{"set-state", issue.ID, spec, "--json"}, extra...) + out, err := bdProxiedRun(t, bd, p.dir, args...) + if err != nil { + t.Fatalf("set-state %s: %v\n%s", spec, err, out) + } + var got map[string]interface{} + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + return got + } + + t.Run("set_new_dimension", func(t *testing.T) { + got := setStateJSON(t, "patrol=active", "--reason", "starting patrol") + if got["changed"] != true { + t.Errorf("expected changed=true, got %v", got["changed"]) + } + if got["old_value"] != nil { + t.Errorf("expected old_value nil for a new dimension, got %v", got["old_value"]) + } + if got["new_value"] != "active" { + t.Errorf("new_value = %v, want active", got["new_value"]) + } + if _, ok := got["event_id"].(string); !ok || got["event_id"] == "" { + t.Errorf("expected an event_id, got %v", got["event_id"]) + } + // Label cache must reflect the new state. + db := openProxiedDB(t, p) + labels := getProxiedLabels(t, db, issue.ID) + if !containsStr(labels, "patrol:active") { + t.Errorf("expected label patrol:active, got %v", labels) + } + }) + + t.Run("change_swaps_label", func(t *testing.T) { + got := setStateJSON(t, "patrol=muted") + if got["changed"] != true || got["old_value"] != "active" || got["new_value"] != "muted" { + t.Errorf("unexpected change result: %v", got) + } + db := openProxiedDB(t, p) + labels := getProxiedLabels(t, db, issue.ID) + if containsStr(labels, "patrol:active") { + t.Errorf("old label patrol:active should have been removed, got %v", labels) + } + if !containsStr(labels, "patrol:muted") { + t.Errorf("expected label patrol:muted, got %v", labels) + } + }) + + t.Run("no_change_is_noop", func(t *testing.T) { + got := setStateJSON(t, "patrol=muted") + if got["changed"] != false { + t.Errorf("expected changed=false for identical value, got %v", got) + } + }) + + t.Run("event_bead_created_as_child", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "state", "list", issue.ID, "--json") + if err != nil { + t.Fatalf("state list: %v\n%s", err, out) + } + var res struct { + States map[string]string `json:"states"` + } + if err := json.Unmarshal(out, &res); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if res.States["patrol"] != "muted" { + t.Errorf("state list shows patrol=%q, want muted", res.States["patrol"]) + } + // The set-state calls created event children under the issue. + children := bdProxiedListJSON(t, bd, p, "--parent", issue.ID, "--status", "all") + var events int + for _, c := range children { + if strings.HasPrefix(c.ID, issue.ID+".") { + events++ + } + } + if events == 0 { + t.Errorf("expected event child beads under %s, got none", issue.ID) + } + }) + + t.Run("invalid_format", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "set-state", issue.ID, "patrolactive") + if err == nil { + t.Fatalf("expected error for missing '=', got success: %s", out) + } + }) + + t.Run("multiple_dimensions", func(t *testing.T) { + m := bdProxiedCreate(t, bd, p.dir, "Multi-dimension state") + + for _, spec := range []string{"phase=planning", "env=staging"} { + out, err := bdProxiedRun(t, bd, p.dir, "set-state", m.ID, spec) + if err != nil { + t.Fatalf("set-state %s: %v\n%s", spec, err, out) + } + } + + out, err := bdProxiedRun(t, bd, p.dir, "state", "list", m.ID, "--json") + if err != nil { + t.Fatalf("state list: %v\n%s", err, out) + } + var res struct { + States map[string]string `json:"states"` + } + if err := json.Unmarshal(out, &res); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if res.States["phase"] != "planning" { + t.Errorf("phase = %q, want planning (states=%v)", res.States["phase"], res.States) + } + if res.States["env"] != "staging" { + t.Errorf("env = %q, want staging (states=%v)", res.States["env"], res.States) + } + + // Each distinct dimension is an independent label; both must be present. + db := openProxiedDB(t, p) + labels := getProxiedLabels(t, db, m.ID) + if !containsStr(labels, "phase:planning") || !containsStr(labels, "env:staging") { + t.Errorf("expected both phase:planning and env:staging labels, got %v", labels) + } + }) + + t.Run("set_state_on_wisp", func(t *testing.T) { + wisp := bdProxiedCreate(t, bd, p.dir, "Wisp set-state", "--ephemeral") + + out, err := bdProxiedRun(t, bd, p.dir, "set-state", wisp.ID, "patrol=muted", "--json") + if err != nil { + t.Fatalf("set-state on wisp: %v\n%s", err, out) + } + var got map[string]interface{} + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if got["changed"] != true || got["new_value"] != "muted" { + t.Errorf("unexpected wisp set-state result: %v", got) + } + + // Wisp state lives in wisp_labels; verify via the state reader. + val, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "state", wisp.ID, "patrol") + if err != nil { + t.Fatalf("state on wisp: %v\nstderr:\n%s", err, stderr) + } + if strings.TrimSpace(val) != "muted" { + t.Errorf("wisp state value = %q, want muted", strings.TrimSpace(val)) + } + }) +} + +func containsStr(ss []string, want string) bool { + for _, s := range ss { + if s == want { + return true + } + } + return false +} diff --git a/cmd/bd/stale.go b/cmd/bd/stale.go index 3f1ca7bf5..e16f2201a 100644 --- a/cmd/bd/stale.go +++ b/cmd/bd/stale.go @@ -22,9 +22,6 @@ This helps identify: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("stale is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("stale") defer func() { if c := metrics.Global(); c != nil { @@ -46,23 +43,30 @@ This helps identify: Status: status, Limit: limit, } - ctx := rootCtx - issues, err := store.GetStaleIssues(ctx, filter) + if usesProxiedServer() { + return runStaleProxiedServer(rootCtx, filter) + } + + issues, err := store.GetStaleIssues(rootCtx, filter) if err != nil { return HandleErrorRespectJSON("%v", err) } - if jsonOutput { - if issues == nil { - issues = []*types.Issue{} - } - return outputJSON(issues) - } - displayStaleIssues(issues, days) - return nil + return renderStale(issues, filter.Days) }, } +func renderStale(issues []*types.Issue, days int) error { + if jsonOutput { + if issues == nil { + issues = []*types.Issue{} + } + return outputJSON(issues) + } + displayStaleIssues(issues, days) + return nil +} + func displayStaleIssues(issues []*types.Issue, days int) { if len(issues) == 0 { fmt.Printf("\n%s No stale issues found (all active)\n\n", ui.RenderPass("✨")) diff --git a/cmd/bd/stale_proxied_server.go b/cmd/bd/stale_proxied_server.go new file mode 100644 index 000000000..5b0e03484 --- /dev/null +++ b/cmd/bd/stale_proxied_server.go @@ -0,0 +1,22 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +func runStaleProxiedServer(ctx context.Context, filter types.StaleFilter) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + issues, err := uw.IssueUseCase().GetStaleIssues(ctx, filter) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + return renderStale(issues, filter.Days) +} diff --git a/cmd/bd/state.go b/cmd/bd/state.go index cddf97092..8fbf7170b 100644 --- a/cmd/bd/state.go +++ b/cmd/bd/state.go @@ -120,11 +120,6 @@ The --reason flag provides context for the event bead (recommended).`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("set-state is not supported in proxied-server mode") - } - CheckReadonly("set-state") - evt := metrics.NewCommandEvent("set-state") defer func() { if c := metrics.Global(); c != nil { @@ -132,7 +127,6 @@ The --reason flag provides context for the event bead (recommended).`, } }() - ctx := rootCtx issueID := args[0] stateSpec := args[1] @@ -145,6 +139,14 @@ The --reason flag provides context for the event bead (recommended).`, reason, _ := cmd.Flags().GetString("reason") + CheckReadonly("set-state") + + if usesProxiedServer() { + return runSetStateProxiedServer(rootCtx, issueID, dimension, newValue, reason) + } + + ctx := rootCtx + var fullID string var err error fullID, err = utils.ResolvePartialID(ctx, store, issueID) diff --git a/cmd/bd/state_proxied_server.go b/cmd/bd/state_proxied_server.go index 0bb126417..a1417a3aa 100644 --- a/cmd/bd/state_proxied_server.go +++ b/cmd/bd/state_proxied_server.go @@ -5,7 +5,9 @@ import ( "fmt" "strings" + "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" "github.com/steveyegge/beads/internal/ui" ) @@ -70,6 +72,146 @@ func runStateProxiedServer(ctx context.Context, issueID, dimension string) error return nil } +type setStateResult struct { + fullID string + oldValue string + eventID string + changed bool +} + +func runSetStateProxiedServer(ctx context.Context, issueID, dimension, newValue, reason string) error { + if uowProvider == nil { + return HandleErrorRespectJSON("proxied-server UOW provider not initialized") + } + + newLabel := dimension + ":" + newValue + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (setStateResult, string, error) { + issue, isWisp := proxiedResolveIssueOrWisp(ctx, uw, issueID) + if issue == nil { + return setStateResult{}, "", fmt.Errorf("issue %s not found", issueID) + } + fullID := issue.ID + + var labels []string + var lerr error + if isWisp { + labels, lerr = uw.LabelUseCase().GetWispLabels(ctx, fullID) + } else { + labels, lerr = uw.LabelUseCase().GetLabels(ctx, fullID) + } + if lerr != nil { + return setStateResult{}, "", lerr + } + + prefix := dimension + ":" + var oldLabel, oldValue string + for _, label := range labels { + if strings.HasPrefix(label, prefix) { + oldLabel = label + oldValue = strings.TrimPrefix(label, prefix) + break + } + } + + if oldLabel == newLabel { + return setStateResult{fullID: fullID, oldValue: oldValue, changed: false}, "", nil + } + + eventDesc := fmt.Sprintf("Set %s to %s", dimension, newValue) + if oldValue != "" { + eventDesc = fmt.Sprintf("Changed %s from %s to %s", dimension, oldValue, newValue) + } + if reason != "" { + eventDesc += "\n\nReason: " + reason + } + + event := &types.Issue{ + Title: fmt.Sprintf("State change: %s → %s", dimension, newValue), + Description: eventDesc, + Status: types.StatusClosed, + Priority: 4, + IssueType: types.TypeEvent, + CreatedBy: getActorWithGit(), + } + params := domain.CreateIssueParams{Issue: event, ParentID: fullID} + + var eventID string + if isWisp { + cr, cerr := uw.IssueUseCase().CreateWisp(ctx, params, actor) + if cerr != nil { + return setStateResult{}, "", fmt.Errorf("creating event: %w", cerr) + } + eventID = cr.Issue.ID + } else { + cr, cerr := uw.IssueUseCase().CreateIssue(ctx, params, actor) + if cerr != nil { + return setStateResult{}, "", fmt.Errorf("creating event: %w", cerr) + } + eventID = cr.Issue.ID + } + + if oldLabel != "" { + if isWisp { + _ = uw.LabelUseCase().RemoveWispLabel(ctx, fullID, oldLabel, actor) + } else { + _ = uw.LabelUseCase().RemoveLabel(ctx, fullID, oldLabel, actor) + } + } + if isWisp { + if aerr := uw.LabelUseCase().AddWispLabel(ctx, fullID, newLabel, actor); aerr != nil { + return setStateResult{}, "", fmt.Errorf("adding label: %w", aerr) + } + } else { + if aerr := uw.LabelUseCase().AddLabel(ctx, fullID, newLabel, actor); aerr != nil { + return setStateResult{}, "", fmt.Errorf("adding label: %w", aerr) + } + } + + return setStateResult{fullID: fullID, oldValue: oldValue, eventID: eventID, changed: true}, "bd: set-state " + fullID, nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + if !res.changed { + if jsonOutput { + return outputJSON(map[string]interface{}{ + "issue_id": res.fullID, + "dimension": dimension, + "value": newValue, + "changed": false, + }) + } + fmt.Printf("(no change: %s already set to %s)\n", dimension, newValue) + return nil + } + + commandDidWrite.Store(true) + + if jsonOutput { + result := map[string]interface{}{ + "issue_id": res.fullID, + "dimension": dimension, + "old_value": res.oldValue, + "new_value": newValue, + "event_id": res.eventID, + "changed": true, + } + if res.oldValue == "" { + result["old_value"] = nil + } + return outputJSON(result) + } + + fmt.Printf("%s Set %s = %s on %s\n", ui.RenderPass("✓"), dimension, newValue, res.fullID) + if res.oldValue != "" { + fmt.Printf(" Previous: %s\n", res.oldValue) + } + fmt.Printf(" Event: %s\n", res.eventID) + return nil +} + func runStateListProxiedServer(ctx context.Context, issueID string) error { uw, err := proxiedOpenReadUOW(ctx) if err != nil { diff --git a/cmd/bd/status.go b/cmd/bd/status.go index 2f05cd076..0f3dfaa8a 100644 --- a/cmd/bd/status.go +++ b/cmd/bd/status.go @@ -55,9 +55,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("status is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("status") defer func() { if c := metrics.Global(); c != nil { @@ -65,7 +62,6 @@ Examples: } }() - showAll, _ := cmd.Flags().GetBool("all") showAssigned, _ := cmd.Flags().GetBool("assigned") noActivity, _ := cmd.Flags().GetBool("no-activity") jsonFormat, _ := cmd.Flags().GetBool("json") @@ -74,12 +70,13 @@ Examples: jsonOutput = true } - var stats *types.Statistics - var err error + if usesProxiedServer() { + return runStatusProxiedServer(rootCtx, showAssigned, noActivity) + } ctx := rootCtx - stats, err = store.GetStatistics(ctx) + stats, err := store.GetStatistics(ctx) if err != nil { return HandleErrorRespectJSON("%v", err) } @@ -96,59 +93,62 @@ Examples: recentActivity = getGitActivity(24) } - output := &StatusOutput{ - Summary: stats, - RecentActivity: recentActivity, - } - - if jsonOutput { - return outputJSON(output) - } - - // Human-readable colorized output using semantic ui package - fmt.Printf("\n%s Issue Database Status\n\n", ui.RenderAccent("📊")) - fmt.Printf("Summary:\n") - fmt.Printf(" Total Issues: %d\n", stats.TotalIssues) - fmt.Printf(" Open: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.OpenIssues))) - fmt.Printf(" In Progress: %s\n", ui.RenderWarn(fmt.Sprintf("%d", stats.InProgressIssues))) - fmt.Printf(" Blocked: %s\n", ui.RenderFail(fmt.Sprintf("%d", stats.BlockedIssues))) - fmt.Printf(" Closed: %d\n", stats.ClosedIssues) - fmt.Printf(" Ready to Work: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.ReadyIssues))) - - // Extended statistics (only show if non-zero) - hasExtended := stats.PinnedIssues > 0 || - stats.EpicsEligibleForClosure > 0 || stats.AverageLeadTime > 0 - if hasExtended { - fmt.Printf("\nExtended:\n") - if stats.PinnedIssues > 0 { - fmt.Printf(" Pinned: %d\n", stats.PinnedIssues) - } - if stats.EpicsEligibleForClosure > 0 { - fmt.Printf(" Epics Ready to Close: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.EpicsEligibleForClosure))) - } - if stats.AverageLeadTime > 0 { - fmt.Printf(" Avg Lead Time: %.1f hours\n", stats.AverageLeadTime) - } - } - - if recentActivity != nil { - fmt.Printf("\nRecent Activity (last %d hours):\n", recentActivity.HoursTracked) - fmt.Printf(" Commits: %d\n", recentActivity.CommitCount) - fmt.Printf(" Total Changes: %d\n", recentActivity.TotalChanges) - fmt.Printf(" Issues Created: %d\n", recentActivity.IssuesCreated) - fmt.Printf(" Issues Closed: %d\n", recentActivity.IssuesClosed) - fmt.Printf(" Issues Reopened: %d\n", recentActivity.IssuesReopened) - fmt.Printf(" Issues Updated: %d\n", recentActivity.IssuesUpdated) - } - - fmt.Printf("\nFor more details, use 'bd list' to see individual issues.\n") - fmt.Println() - - _ = showAll - return nil + return renderStatus(stats, recentActivity) }, } +func renderStatus(stats *types.Statistics, recentActivity *RecentActivitySummary) error { + output := &StatusOutput{ + Summary: stats, + RecentActivity: recentActivity, + } + + if jsonOutput { + return outputJSON(output) + } + + // Human-readable colorized output using semantic ui package + fmt.Printf("\n%s Issue Database Status\n\n", ui.RenderAccent("📊")) + fmt.Printf("Summary:\n") + fmt.Printf(" Total Issues: %d\n", stats.TotalIssues) + fmt.Printf(" Open: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.OpenIssues))) + fmt.Printf(" In Progress: %s\n", ui.RenderWarn(fmt.Sprintf("%d", stats.InProgressIssues))) + fmt.Printf(" Blocked: %s\n", ui.RenderFail(fmt.Sprintf("%d", stats.BlockedIssues))) + fmt.Printf(" Closed: %d\n", stats.ClosedIssues) + fmt.Printf(" Ready to Work: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.ReadyIssues))) + + // Extended statistics (only show if non-zero) + hasExtended := stats.PinnedIssues > 0 || + stats.EpicsEligibleForClosure > 0 || stats.AverageLeadTime > 0 + if hasExtended { + fmt.Printf("\nExtended:\n") + if stats.PinnedIssues > 0 { + fmt.Printf(" Pinned: %d\n", stats.PinnedIssues) + } + if stats.EpicsEligibleForClosure > 0 { + fmt.Printf(" Epics Ready to Close: %s\n", ui.RenderPass(fmt.Sprintf("%d", stats.EpicsEligibleForClosure))) + } + if stats.AverageLeadTime > 0 { + fmt.Printf(" Avg Lead Time: %.1f hours\n", stats.AverageLeadTime) + } + } + + if recentActivity != nil { + fmt.Printf("\nRecent Activity (last %d hours):\n", recentActivity.HoursTracked) + fmt.Printf(" Commits: %d\n", recentActivity.CommitCount) + fmt.Printf(" Total Changes: %d\n", recentActivity.TotalChanges) + fmt.Printf(" Issues Created: %d\n", recentActivity.IssuesCreated) + fmt.Printf(" Issues Closed: %d\n", recentActivity.IssuesClosed) + fmt.Printf(" Issues Reopened: %d\n", recentActivity.IssuesReopened) + fmt.Printf(" Issues Updated: %d\n", recentActivity.IssuesUpdated) + } + + fmt.Printf("\nFor more details, use 'bd list' to see individual issues.\n") + fmt.Println() + + return nil +} + // getGitActivity returns recent activity statistics. // Previously calculated from git log of issues.jsonl; now returns nil // as activity tracking has moved to Dolt-native queries. @@ -164,22 +164,26 @@ func getAssignedStatistics(assignee string) *types.Statistics { ctx := rootCtx - // Filter by assignee assigneePtr := assignee - filter := types.IssueFilter{ - Assignee: &assigneePtr, - } - - issues, err := store.SearchIssues(ctx, "", filter) + issues, err := store.SearchIssues(ctx, "", types.IssueFilter{Assignee: &assigneePtr}) if err != nil { return nil } + readyCount := 0 + readyIssues, err := store.GetReadyWork(ctx, types.WorkFilter{Assignee: &assigneePtr}) + if err == nil { + readyCount = len(readyIssues) + } + + return buildAssignedStats(issues, readyCount) +} + +func buildAssignedStats(issues []*types.Issue, readyCount int) *types.Statistics { stats := &types.Statistics{ TotalIssues: len(issues), } - // Count by status for _, issue := range issues { switch issue.Status { case types.StatusOpen: @@ -195,15 +199,7 @@ func getAssignedStatistics(assignee string) *types.Statistics { } } - // Get ready work count for this assignee - readyFilter := types.WorkFilter{ - Assignee: &assigneePtr, - } - readyIssues, err := store.GetReadyWork(ctx, readyFilter) - if err == nil { - stats.ReadyIssues = len(readyIssues) - } - + stats.ReadyIssues = readyCount return stats } diff --git a/cmd/bd/status_proxied_integration_test.go b/cmd/bd/status_proxied_integration_test.go new file mode 100644 index 000000000..d649fb172 --- /dev/null +++ b/cmd/bd/status_proxied_integration_test.go @@ -0,0 +1,257 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "fmt" + "strings" + "sync" + "testing" +) + +func TestProxiedServerStatus(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "sts") + + // Seed the same known status distribution as TestEmbeddedStatus: + // 3 open, 1 in_progress, 1 closed (5 total). + bdProxiedCreate(t, bd, p.dir, "Status open 1", "--type", "task") + bdProxiedCreate(t, bd, p.dir, "Status open 2", "--type", "bug") + ip := bdProxiedCreate(t, bd, p.dir, "Status in_progress", "--type", "task", "--assignee", "alice") + bdProxiedUpdate(t, bd, p.dir, ip.ID, "--status", "in_progress") + closed := bdProxiedCreate(t, bd, p.dir, "Status closed", "--type", "task") + if out, err := bdProxiedRun(t, bd, p.dir, "close", closed.ID); err != nil { + t.Fatalf("close %s: %v\n%s", closed.ID, err, out) + } + bdProxiedCreate(t, bd, p.dir, "Status assigned bob", "--type", "task", "--assignee", "bob") + + statusJSON := func(t *testing.T, args ...string) StatusOutput { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"status", "--json"}, args...)...) + if err != nil { + t.Fatalf("status %v: %v\n%s", args, err, out) + } + var got StatusOutput + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal status: %v\n%s", err, out) + } + if got.Summary == nil { + t.Fatalf("status summary is nil: %s", out) + } + return got + } + + statusText := func(t *testing.T, args ...string) string { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"status"}, args...)...) + if err != nil { + t.Fatalf("status %v: %v\n%s", args, err, out) + } + return string(out) + } + + // ===== Default (human-readable) output ===== + + t.Run("default_output", func(t *testing.T) { + out := statusText(t) + for _, want := range []string{"Issue Database Status", "Total Issues:", "Open:"} { + if !strings.Contains(out, want) { + t.Errorf("expected %q in output: %s", want, out) + } + } + }) + + t.Run("human_readable_sections", func(t *testing.T) { + out := statusText(t) + for _, want := range []string{"Summary:", "In Progress:", "Ready to Work:"} { + if !strings.Contains(out, want) { + t.Errorf("expected %q section: %s", want, out) + } + } + }) + + // ===== --json structure ===== + + t.Run("json_output_structure", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "status", "--json") + if err != nil { + t.Fatalf("status --json: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + summary, ok := m["summary"].(map[string]interface{}) + if !ok { + t.Fatalf("expected 'summary' object: %v", m) + } + for _, key := range []string{"total_issues", "open_issues", "in_progress_issues", "closed_issues"} { + if _, ok := summary[key]; !ok { + t.Errorf("expected '%s' key in summary", key) + } + } + }) + + // ===== --json counts ===== + + t.Run("json_counts_match", func(t *testing.T) { + got := statusJSON(t) + if got.Summary.TotalIssues < 5 { + t.Errorf("expected at least 5 total issues, got %d", got.Summary.TotalIssues) + } + if got.Summary.OpenIssues < 3 { + t.Errorf("expected at least 3 open issues, got %d", got.Summary.OpenIssues) + } + if got.Summary.InProgressIssues < 1 { + t.Errorf("expected at least 1 in_progress issue, got %d", got.Summary.InProgressIssues) + } + if got.Summary.ClosedIssues < 1 { + t.Errorf("expected at least 1 closed issue, got %d", got.Summary.ClosedIssues) + } + }) + + t.Run("total_matches_list_all", func(t *testing.T) { + got := statusJSON(t) + want := len(bdProxiedListJSON(t, bd, p, "--all")) + if got.Summary.TotalIssues != want { + t.Errorf("status total = %d, want %d (list --all)", got.Summary.TotalIssues, want) + } + }) + + t.Run("open_matches_list", func(t *testing.T) { + got := statusJSON(t) + want := len(bdProxiedListJSON(t, bd, p, "--status", "open")) + if got.Summary.OpenIssues != want { + t.Errorf("status open = %d, want %d (list --status open)", got.Summary.OpenIssues, want) + } + }) + + // ===== --assigned ===== + + t.Run("assigned_within_total", func(t *testing.T) { + total := statusJSON(t).Summary.TotalIssues + got := statusJSON(t, "--assigned") + if got.Summary.TotalIssues < 0 || got.Summary.TotalIssues > total { + t.Errorf("assigned total %d out of range [0, %d]", got.Summary.TotalIssues, total) + } + }) + + // ===== --no-activity ===== + + t.Run("no_activity_flag", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "status", "--json", "--no-activity") + if err != nil { + t.Fatalf("status --json --no-activity: %v\n%s", err, out) + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if _, ok := m["summary"]; !ok { + t.Error("expected 'summary' even with --no-activity") + } + if activity, ok := m["recent_activity"]; ok && activity != nil { + t.Error("expected no recent_activity with --no-activity") + } + }) + + // ===== stats alias ===== + + t.Run("stats_alias", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "stats", "--json") + if err != nil { + t.Fatalf("stats --json: %v\n%s", err, out) + } + var got StatusOutput + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal stats: %v\n%s", err, out) + } + if got.Summary == nil || got.Summary.TotalIssues != statusJSON(t).Summary.TotalIssues { + t.Errorf("stats alias total mismatch") + } + }) + + // ===== Empty database ===== + + t.Run("empty_database", func(t *testing.T) { + empty := newSharedProxiedProject(t, bd, "ste") + out, err := bdProxiedRun(t, bd, empty.dir, "status", "--json") + if err != nil { + t.Fatalf("status --json (empty): %v\n%s", err, out) + } + var got StatusOutput + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if got.Summary == nil { + t.Fatalf("empty status summary is nil: %s", out) + } + if got.Summary.TotalIssues != 0 { + t.Errorf("expected 0 total issues in empty db, got %d", got.Summary.TotalIssues) + } + }) +} + +// TestProxiedServerStatusConcurrent exercises status operations concurrently +// through the proxied server. +func TestProxiedServerStatusConcurrent(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "ssc") + + for i := 0; i < 10; i++ { + bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("concurrent-status-%d", i), "--type", "task") + } + + const numWorkers = 8 + + type workerResult struct { + worker int + err error + } + + results := make([]workerResult, numWorkers) + var wg sync.WaitGroup + wg.Add(numWorkers) + + queries := [][]string{ + {"--json"}, + {"--json", "--no-activity"}, + {"--json"}, + {"--json", "--no-activity"}, + {"--json"}, + {"--json"}, + {"--json", "--no-activity"}, + {"--json"}, + } + + for w := 0; w < numWorkers; w++ { + go func(worker int) { + defer wg.Done() + r := workerResult{worker: worker} + q := queries[worker%len(queries)] + out, err := bdProxiedRun(t, bd, p.dir, append([]string{"status"}, q...)...) + if err != nil { + r.err = fmt.Errorf("worker %d status %v: %v\n%s", worker, q, err, out) + results[worker] = r + return + } + var m map[string]interface{} + if err := json.Unmarshal(out, &m); err != nil { + r.err = fmt.Errorf("worker %d: JSON parse: %v\n%s", worker, err, out) + } + results[worker] = r + }(w) + } + wg.Wait() + + for _, r := range results { + if r.err != nil && !strings.Contains(r.err.Error(), "one writer at a time") { + t.Errorf("worker %d failed: %v", r.worker, r.err) + } + } +} diff --git a/cmd/bd/status_proxied_server.go b/cmd/bd/status_proxied_server.go new file mode 100644 index 000000000..4ef7c0c62 --- /dev/null +++ b/cmd/bd/status_proxied_server.go @@ -0,0 +1,51 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" +) + +func runStatusProxiedServer(ctx context.Context, showAssigned, noActivity bool) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + stats, err := uw.IssueUseCase().GetStatistics(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + if showAssigned { + stats, err = proxiedAssignedStatistics(ctx, uw, actor) + if err != nil { + return HandleErrorRespectJSON("failed to get assigned statistics: %v", err) + } + } + + var recentActivity *RecentActivitySummary + if !noActivity { + recentActivity = getGitActivity(24) + } + + return renderStatus(stats, recentActivity) +} + +func proxiedAssignedStatistics(ctx context.Context, uw uow.UnitOfWork, assignee string) (*types.Statistics, error) { + assigneePtr := assignee + page, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Assignee: &assigneePtr}) + if err != nil { + return nil, err + } + + readyCount := 0 + readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{Assignee: &assigneePtr}) + if err == nil { + readyCount = len(readyPage.Items) + } + + return buildAssignedStats(page.Items, readyCount), nil +} diff --git a/cmd/bd/statuses.go b/cmd/bd/statuses.go index 0ffcb2c21..fc272cc15 100644 --- a/cmd/bd/statuses.go +++ b/cmd/bd/statuses.go @@ -51,9 +51,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("statuses is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("statuses") defer func() { if c := metrics.Global(); c != nil { @@ -61,6 +58,10 @@ Examples: } }() + if usesProxiedServer() { + return runStatusesProxiedServer(rootCtx) + } + if err := ensureDirectMode("statuses command requires direct database access"); err != nil { return HandleError("%v", err) } @@ -73,45 +74,49 @@ Examples: } } - if jsonOutput { - result := struct { - BuiltInStatuses []statusInfo `json:"built_in_statuses"` - CustomStatuses []types.CustomStatus `json:"custom_statuses,omitempty"` - }{} - - for _, s := range builtInStatuses { - result.BuiltInStatuses = append(result.BuiltInStatuses, statusInfo{ - Name: string(s.Status), - Category: string(s.Category), - Icon: ui.GetStatusIcon(string(s.Status)), - Description: s.Description, - }) - } - result.CustomStatuses = customStatuses - return outputJSON(result) - } - - fmt.Println("Built-in statuses:") - for _, s := range builtInStatuses { - icon := ui.RenderStatusIcon(string(s.Status)) - fmt.Printf(" %s %-14s [%-6s] %s\n", icon, s.Status, s.Category, s.Description) - } - - if len(customStatuses) > 0 { - fmt.Println("\nCustom statuses:") - for _, cs := range customStatuses { - icon := ui.RenderStatusIconWithCategory(cs.Name, cs.Category) - fmt.Printf(" %s %-14s [%-6s]\n", icon, cs.Name, cs.Category) - } - } else { - fmt.Println("\nNo custom statuses configured.") - fmt.Println("Configure with: bd config set status.custom \"name:category,...\"") - fmt.Println("Categories: active, wip, done, frozen") - } - return nil + return renderStatuses(customStatuses) }, } +func renderStatuses(customStatuses []types.CustomStatus) error { + if jsonOutput { + result := struct { + BuiltInStatuses []statusInfo `json:"built_in_statuses"` + CustomStatuses []types.CustomStatus `json:"custom_statuses,omitempty"` + }{} + + for _, s := range builtInStatuses { + result.BuiltInStatuses = append(result.BuiltInStatuses, statusInfo{ + Name: string(s.Status), + Category: string(s.Category), + Icon: ui.GetStatusIcon(string(s.Status)), + Description: s.Description, + }) + } + result.CustomStatuses = customStatuses + return outputJSON(result) + } + + fmt.Println("Built-in statuses:") + for _, s := range builtInStatuses { + icon := ui.RenderStatusIcon(string(s.Status)) + fmt.Printf(" %s %-14s [%-6s] %s\n", icon, s.Status, s.Category, s.Description) + } + + if len(customStatuses) > 0 { + fmt.Println("\nCustom statuses:") + for _, cs := range customStatuses { + icon := ui.RenderStatusIconWithCategory(cs.Name, cs.Category) + fmt.Printf(" %s %-14s [%-6s]\n", icon, cs.Name, cs.Category) + } + } else { + fmt.Println("\nNo custom statuses configured.") + fmt.Println("Configure with: bd config set status.custom \"name:category,...\"") + fmt.Println("Categories: active, wip, done, frozen") + } + return nil +} + type statusInfo struct { Name string `json:"name"` Category string `json:"category"` diff --git a/cmd/bd/statuses_proxied_server.go b/cmd/bd/statuses_proxied_server.go new file mode 100644 index 000000000..16c4bd744 --- /dev/null +++ b/cmd/bd/statuses_proxied_server.go @@ -0,0 +1,22 @@ +package main + +import ( + "context" + + "github.com/steveyegge/beads/internal/types" +) + +func runStatusesProxiedServer(ctx context.Context) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + var customStatuses []types.CustomStatus + if cs, err := uw.ConfigUseCase().GetCustomStatuses(ctx); err == nil { + customStatuses = cs + } + + return renderStatuses(customStatuses) +} diff --git a/cmd/bd/statuses_types_proxied_integration_test.go b/cmd/bd/statuses_types_proxied_integration_test.go new file mode 100644 index 000000000..8edf6f697 --- /dev/null +++ b/cmd/bd/statuses_types_proxied_integration_test.go @@ -0,0 +1,267 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func TestProxiedServerStatuses(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "sta") + + type statusesResult struct { + BuiltInStatuses []statusInfo `json:"built_in_statuses"` + CustomStatuses []types.CustomStatus `json:"custom_statuses"` + } + get := func(t *testing.T) statusesResult { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, "statuses", "--json") + if err != nil { + t.Fatalf("statuses --json: %v\n%s", err, out) + } + var got statusesResult + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + return got + } + + // NOTE: There is no statuses_embedded_test.go counterpart. These scenarios + // mirror the shape of the types embedded coverage (default text output, JSON + // field structure, custom-from-config fallback) applied to statuses. + + t.Run("built_ins", func(t *testing.T) { + got := get(t) + if len(got.BuiltInStatuses) != len(builtInStatuses) { + t.Errorf("built-in statuses = %d, want %d", len(got.BuiltInStatuses), len(builtInStatuses)) + } + if len(got.CustomStatuses) != 0 { + t.Errorf("expected no custom statuses initially, got %v", got.CustomStatuses) + } + }) + + t.Run("default_output_text", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "statuses") + if err != nil { + t.Fatalf("statuses: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "Built-in statuses") { + t.Errorf("expected 'Built-in statuses' header: %s", s) + } + for _, name := range []string{"open", "in_progress", "blocked", "deferred", "closed"} { + if !strings.Contains(s, name) { + t.Errorf("expected status %q in output: %s", name, s) + } + } + if !strings.Contains(s, "No custom statuses") { + t.Errorf("expected 'No custom statuses' message: %s", s) + } + }) + + t.Run("json_builtin_fields", func(t *testing.T) { + got := get(t) + if len(got.BuiltInStatuses) == 0 { + t.Fatal("expected built-in statuses") + } + for _, s := range got.BuiltInStatuses { + if s.Name == "" { + t.Error("expected non-empty name in built-in status") + } + if s.Category == "" { + t.Errorf("expected non-empty category for status %q", s.Name) + } + if s.Description == "" { + t.Errorf("expected non-empty description for status %q", s.Name) + } + } + }) + + t.Run("custom_from_config_fallback", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "config", "set", "status.custom", "in_review:active") + if err != nil { + t.Fatalf("config set status.custom: %v\n%s", err, out) + } + got := get(t) + var found bool + for _, cs := range got.CustomStatuses { + if cs.Name == "in_review" { + found = true + if cs.Category != types.CategoryActive { + t.Errorf("in_review category = %q, want active", cs.Category) + } + } + } + if !found { + t.Errorf("expected custom status in_review resolved from config, got %v", got.CustomStatuses) + } + }) + + t.Run("custom_in_text_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "statuses") + if err != nil { + t.Fatalf("statuses: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "Custom statuses") { + t.Errorf("expected 'Custom statuses' section after config set: %s", s) + } + if !strings.Contains(s, "in_review") { + t.Errorf("expected custom status in_review in text output: %s", s) + } + }) +} + +func TestProxiedServerTypes(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "typ") + + type typesResult struct { + CoreTypes []typeInfo `json:"core_types"` + CustomTypes []string `json:"custom_types"` + } + get := func(t *testing.T) typesResult { + t.Helper() + out, err := bdProxiedRun(t, bd, p.dir, "types", "--json") + if err != nil { + t.Fatalf("types --json: %v\n%s", err, out) + } + var got typesResult + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + return got + } + + t.Run("core_types", func(t *testing.T) { + got := get(t) + if len(got.CoreTypes) != len(coreWorkTypes) { + t.Errorf("core types = %d, want %d", len(got.CoreTypes), len(coreWorkTypes)) + } + if len(got.CoreTypes) < 6 { + t.Errorf("expected at least 6 core types, got %d", len(got.CoreTypes)) + } + if len(got.CustomTypes) != 0 { + t.Errorf("expected no custom types initially, got %v", got.CustomTypes) + } + }) + + t.Run("default_output_text", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "types") + if err != nil { + t.Fatalf("types: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "Core work types") { + t.Errorf("expected 'Core work types' header: %s", s) + } + for _, typeName := range []string{"task", "bug", "feature", "chore", "epic", "decision"} { + if !strings.Contains(s, typeName) { + t.Errorf("expected %q in types output: %s", typeName, s) + } + } + }) + + t.Run("default_output_descriptions", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "types") + if err != nil { + t.Fatalf("types: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "General work item") { + t.Errorf("expected task description in output: %s", s) + } + if !strings.Contains(s, "Bug report") { + t.Errorf("expected bug description in output: %s", s) + } + }) + + t.Run("json_core_type_fields", func(t *testing.T) { + got := get(t) + for _, ct := range got.CoreTypes { + if ct.Name == "" { + t.Error("expected non-empty 'name' in core type") + } + if ct.Description == "" { + t.Errorf("expected non-empty 'description' for core type %q", ct.Name) + } + } + }) + + t.Run("json_has_all_core_types", func(t *testing.T) { + got := get(t) + names := make(map[string]bool) + for _, ct := range got.CoreTypes { + names[ct.Name] = true + } + for _, expected := range []string{"task", "bug", "feature", "chore", "epic", "decision"} { + if !names[expected] { + t.Errorf("expected core type %q in JSON output", expected) + } + } + }) + + t.Run("sections_static", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "types", "--sections", "--json") + if err != nil { + t.Fatalf("types --sections --json: %v\n%s", err, out) + } + var sections []typeSectionsInfo + if err := json.Unmarshal(out, §ions); err != nil { + t.Fatalf("unmarshal sections: %v\n%s", err, out) + } + if len(sections) != len(coreWorkTypes) { + t.Errorf("sections entries = %d, want %d", len(sections), len(coreWorkTypes)) + } + }) + + t.Run("no_custom_types_message", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "types") + if err != nil { + t.Fatalf("types: %v\n%s", err, out) + } + if !strings.Contains(string(out), "No custom types") { + t.Errorf("expected 'No custom types' message: %s", out) + } + }) + + t.Run("custom_from_config_fallback", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "config", "set", "types.custom", "spike_x,research,ops") + if err != nil { + t.Fatalf("config set types.custom: %v\n%s", err, out) + } + got := get(t) + names := make(map[string]bool) + for _, ct := range got.CustomTypes { + names[ct] = true + } + for _, expected := range []string{"spike_x", "research", "ops"} { + if !names[expected] { + t.Errorf("expected custom type %q resolved from config, got %v", expected, got.CustomTypes) + } + } + }) + + t.Run("custom_types_in_text_output", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "types") + if err != nil { + t.Fatalf("types: %v\n%s", err, out) + } + s := string(out) + if !strings.Contains(s, "custom types") { + t.Errorf("expected custom types section: %s", s) + } + if !strings.Contains(s, "research") { + t.Errorf("expected configured custom type in text output: %s", s) + } + }) +} diff --git a/cmd/bd/types.go b/cmd/bd/types.go index 8e23a83f0..a10d65a52 100644 --- a/cmd/bd/types.go +++ b/cmd/bd/types.go @@ -43,9 +43,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("types is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("types") defer func() { if c := metrics.Global(); c != nil { @@ -58,6 +55,10 @@ Examples: return printSections(jsonOutput) } + if usesProxiedServer() { + return runTypesProxiedServer(rootCtx) + } + if err := ensureDirectMode("types command requires direct database access"); err != nil { return HandleError("%v", err) } @@ -70,40 +71,44 @@ Examples: } } - if jsonOutput { - result := struct { - CoreTypes []typeInfo `json:"core_types"` - CustomTypes []string `json:"custom_types,omitempty"` - }{} - - for _, t := range coreWorkTypes { - result.CoreTypes = append(result.CoreTypes, typeInfo{ - Name: string(t.Type), - Description: t.Description, - }) - } - result.CustomTypes = customTypes - return outputJSON(result) - } - - fmt.Println("Core work types (built-in):") - for _, t := range coreWorkTypes { - fmt.Printf(" %-14s %s\n", t.Type, t.Description) - } - - if len(customTypes) > 0 { - fmt.Println("\nConfigured custom types:") - for _, t := range customTypes { - fmt.Printf(" %s\n", t) - } - } else { - fmt.Println("\nNo custom types configured.") - fmt.Println("Configure with: bd config set types.custom \"type1,type2,...\"") - } - return nil + return renderTypes(customTypes) }, } +func renderTypes(customTypes []string) error { + if jsonOutput { + result := struct { + CoreTypes []typeInfo `json:"core_types"` + CustomTypes []string `json:"custom_types,omitempty"` + }{} + + for _, t := range coreWorkTypes { + result.CoreTypes = append(result.CoreTypes, typeInfo{ + Name: string(t.Type), + Description: t.Description, + }) + } + result.CustomTypes = customTypes + return outputJSON(result) + } + + fmt.Println("Core work types (built-in):") + for _, t := range coreWorkTypes { + fmt.Printf(" %-14s %s\n", t.Type, t.Description) + } + + if len(customTypes) > 0 { + fmt.Println("\nConfigured custom types:") + for _, t := range customTypes { + fmt.Printf(" %s\n", t) + } + } else { + fmt.Println("\nNo custom types configured.") + fmt.Println("Configure with: bd config set types.custom \"type1,type2,...\"") + } + return nil +} + // typeSectionsInfo holds section data for JSON output. type typeSectionsInfo struct { Name string `json:"name"` diff --git a/cmd/bd/types_proxied_server.go b/cmd/bd/types_proxied_server.go new file mode 100644 index 000000000..cefb89af6 --- /dev/null +++ b/cmd/bd/types_proxied_server.go @@ -0,0 +1,20 @@ +package main + +import ( + "context" +) + +func runTypesProxiedServer(ctx context.Context) error { + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleError("%v", err) + } + defer uw.Close(ctx) + + var customTypes []string + if ct, err := uw.ConfigUseCase().GetCustomTypes(ctx); err == nil { + customTypes = ct + } + + return renderTypes(customTypes) +} diff --git a/cmd/bd/unclaim.go b/cmd/bd/unclaim.go index 0939c3bb9..ff0052237 100644 --- a/cmd/bd/unclaim.go +++ b/cmd/bd/unclaim.go @@ -44,10 +44,6 @@ Examples: bd unclaim bd-123 --if-assignee worker-7 # only if still held by worker-7`, Args: cobra.MinimumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("unclaim is not supported in proxied-server mode") - } - CheckReadonly("unclaim") reason, _ := cmd.Flags().GetString("reason") force, _ := cmd.Flags().GetBool("force") ifAssignee, _ := cmd.Flags().GetString("if-assignee") @@ -62,6 +58,16 @@ Examples: if conditional && ifAssignee == "" { return HandleErrorRespectJSON("--if-assignee requires a non-empty assignee; it releases the issue only while that assignee still holds it") } + + CheckReadonly("unclaim") + + if usesProxiedServer() { + if conditional { + return HandleErrorRespectJSON("--if-assignee is not supported in proxied-server mode") + } + return runUnclaimProxiedServer(rootCtx, args, reason, force) + } + ctx := rootCtx unclaimedIssues := []*types.Issue{} diff --git a/cmd/bd/unclaim_proxied_integration_test.go b/cmd/bd/unclaim_proxied_integration_test.go new file mode 100644 index 000000000..f7fcdfa06 --- /dev/null +++ b/cmd/bd/unclaim_proxied_integration_test.go @@ -0,0 +1,220 @@ +//go:build cgo + +package main + +import ( + "context" + "encoding/json" + "strings" + "testing" + "time" + + "github.com/steveyegge/beads/internal/types" +) + +func TestProxiedServerUnclaim(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "unc") + + statusAssignee := func(t *testing.T, id string) (string, string) { + t.Helper() + iss := bdProxiedShow(t, bd, p.dir, id) + return string(iss.Status), iss.Assignee + } + + t.Run("unclaim_own_claim", func(t *testing.T) { + a := bdProxiedCreate(t, bd, p.dir, "Unclaim target", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, a.ID, "--claim") + if st, as := statusAssignee(t, a.ID); st != string(types.StatusInProgress) || as == "" { + t.Fatalf("expected in_progress+assignee after claim, got status=%s assignee=%q", st, as) + } + + if out, err := bdProxiedRun(t, bd, p.dir, "unclaim", a.ID, "--reason", "abandoning"); err != nil { + t.Fatalf("unclaim: %v\n%s", err, out) + } + st, as := statusAssignee(t, a.ID) + if st != string(types.StatusOpen) { + t.Errorf("status = %s, want open after unclaim", st) + } + if as != "" { + t.Errorf("assignee = %q, want cleared after unclaim", as) + } + + // The --reason should have been added as a comment. + out, err := bdProxiedRun(t, bd, p.dir, "comments", a.ID, "--json") + if err != nil { + t.Fatalf("comments: %v\n%s", err, out) + } + if !strings.Contains(string(out), "abandoning") { + t.Errorf("expected reason comment 'abandoning' on %s, got %s", a.ID, out) + } + }) + + t.Run("unclaim_unassigned_errors", func(t *testing.T) { + b := bdProxiedCreate(t, bd, p.dir, "Never claimed", "--type", "task") + stdout, stderr, _ := bdProxiedRunBuffers(t, bd, p.dir, "unclaim", b.ID) + if !strings.Contains(stdout+stderr, "not assigned") { + t.Errorf("expected 'not assigned' error, got stdout=%q stderr=%q", stdout, stderr) + } + }) + + t.Run("unclaim_reason_in_output", func(t *testing.T) { + c := bdProxiedCreate(t, bd, p.dir, "Reason output", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, c.ID, "--claim") + out, err := bdProxiedRun(t, bd, p.dir, "unclaim", c.ID, "--reason", "Agent crashed") + if err != nil { + t.Fatalf("unclaim --reason: %v\n%s", err, out) + } + if !strings.Contains(string(out), "Agent crashed") { + t.Errorf("expected reason in output, got: %s", out) + } + if st, as := statusAssignee(t, c.ID); st != string(types.StatusOpen) || as != "" { + t.Errorf("expected open+cleared after unclaim, got status=%s assignee=%q", st, as) + } + }) + + t.Run("unclaim_json_output", func(t *testing.T) { + d := bdProxiedCreate(t, bd, p.dir, "JSON output", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, d.ID, "--claim") + out, err := bdProxiedRun(t, bd, p.dir, "unclaim", d.ID, "--json") + if err != nil { + t.Fatalf("unclaim --json: %v\n%s", err, out) + } + var unclaimed []struct { + Assignee string `json:"assignee"` + Status string `json:"status"` + } + if err := json.Unmarshal(out, &unclaimed); err != nil { + t.Fatalf("parse unclaim --json: %v\n%s", err, out) + } + if len(unclaimed) != 1 { + t.Fatalf("expected 1 issue in unclaim --json, got %d:\n%s", len(unclaimed), out) + } + if unclaimed[0].Assignee != "" { + t.Errorf("expected empty assignee, got %q", unclaimed[0].Assignee) + } + if unclaimed[0].Status != string(types.StatusOpen) { + t.Errorf("expected status open, got %q", unclaimed[0].Status) + } + }) + + t.Run("unclaim_multiple_ids", func(t *testing.T) { + e := bdProxiedCreate(t, bd, p.dir, "Multi 1", "--type", "task") + f := bdProxiedCreate(t, bd, p.dir, "Multi 2", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, e.ID, "--claim") + bdProxiedUpdate(t, bd, p.dir, f.ID, "--claim") + if out, err := bdProxiedRun(t, bd, p.dir, "unclaim", e.ID, f.ID); err != nil { + t.Fatalf("unclaim multiple: %v\n%s", err, out) + } + for _, id := range []string{e.ID, f.ID} { + if st, as := statusAssignee(t, id); st != string(types.StatusOpen) || as != "" { + t.Errorf("%s: expected open+cleared, got status=%s assignee=%q", id, st, as) + } + } + }) + + t.Run("unclaim_nonexistent_errors", func(t *testing.T) { + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "unclaim", "nonexistent") + if err == nil { + t.Fatalf("expected failure for nonexistent id, got success:\n%s", stdout) + } + if !strings.Contains(stdout+stderr, "not found") { + t.Errorf("expected 'not found' error, got stdout=%q stderr=%q", stdout, stderr) + } + }) + + t.Run("unclaim_closed_errors", func(t *testing.T) { + g := bdProxiedCreate(t, bd, p.dir, "Closed target", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, g.ID, "--claim") + if out, err := bdProxiedRun(t, bd, p.dir, "close", g.ID); err != nil { + t.Fatalf("close: %v\n%s", err, out) + } + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "unclaim", g.ID) + if err == nil { + t.Fatalf("expected failure unclaiming closed issue, got success:\n%s", stdout) + } + if !strings.Contains(stdout+stderr, "cannot unclaim closed issue") { + t.Errorf("expected closed-issue error, got stdout=%q stderr=%q", stdout, stderr) + } + }) +} + +func TestProxiedServerReclaim(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + p := newSharedProxiedProject(t, bd, "rcl") + + issue := bdProxiedCreate(t, bd, p.dir, "Reclaim target", "--type", "task") + bdProxiedUpdate(t, bd, p.dir, issue.ID, "--claim") + + // Backdate the lease so it is expired well in the past. + db := openProxiedDB(t, p) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + res, err := db.ExecContext(ctx, + "UPDATE leases SET lease_expires_at = ? WHERE issue_id = ?", + time.Now().UTC().Add(-1*time.Hour), issue.ID) + if err != nil { + t.Fatalf("backdate lease: %v", err) + } + if n, _ := res.RowsAffected(); n == 0 { + t.Fatalf("claim did not create a lease row for %s; cannot test reclaim", issue.ID) + } + + t.Run("reclaims_stale_lease", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "reclaim", "--older-than", "0s", "--json") + if err != nil { + t.Fatalf("reclaim: %v\n%s", err, out) + } + var got struct { + Count int `json:"count"` + Reclaimed []struct { + ID string `json:"id"` + PreviousOwner string `json:"previous_owner"` + } `json:"reclaimed"` + } + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + var found bool + for _, r := range got.Reclaimed { + if r.ID == issue.ID { + found = true + if r.PreviousOwner == "" { + t.Errorf("expected a previous owner for reclaimed %s", issue.ID) + } + } + } + if !found { + t.Fatalf("expected %s in reclaimed set, got %+v", issue.ID, got.Reclaimed) + } + + // Issue must now be open with the assignee cleared. + iss := bdProxiedShow(t, bd, p.dir, issue.ID) + if iss.Status != types.StatusOpen { + t.Errorf("status = %s, want open after reclaim", iss.Status) + } + if iss.Assignee != "" { + t.Errorf("assignee = %q, want cleared after reclaim", iss.Assignee) + } + }) + + t.Run("nothing_to_reclaim", func(t *testing.T) { + out, err := bdProxiedRun(t, bd, p.dir, "reclaim", "--older-than", "0s", "--json") + if err != nil { + t.Fatalf("reclaim: %v\n%s", err, out) + } + var got struct { + Count int `json:"count"` + } + if err := json.Unmarshal(out, &got); err != nil { + t.Fatalf("unmarshal: %v\n%s", err, out) + } + if got.Count != 0 { + t.Errorf("expected 0 reclaimed on second run, got %d", got.Count) + } + }) +} diff --git a/cmd/bd/unclaim_proxied_server.go b/cmd/bd/unclaim_proxied_server.go new file mode 100644 index 000000000..6e71b66fc --- /dev/null +++ b/cmd/bd/unclaim_proxied_server.go @@ -0,0 +1,121 @@ +package main + +import ( + "context" + "fmt" + "os" + "strings" + "time" + + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/ui" +) + +type unclaimProxiedResult struct { + unclaimed []*types.Issue + ids []string + errs []string +} + +func runUnclaimProxiedServer(ctx context.Context, args []string, reason string, force bool) error { + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (unclaimProxiedResult, string, error) { + var r unclaimProxiedResult + for _, id := range args { + issue, _ := proxiedResolveIssueOrWisp(ctx, uw, id) + if issue == nil { + r.errs = append(r.errs, fmt.Sprintf("Error resolving %s: not found", id)) + continue + } + fullID := issue.ID + + if uerr := uw.IssueUseCase().Unclaim(ctx, fullID, actor, force); uerr != nil { + r.errs = append(r.errs, fmt.Sprintf("Error unclaiming %s: %v", fullID, uerr)) + continue + } + + if reason != "" { + if _, cerr := uw.CommentUseCase().AddCommentToIssue(ctx, fullID, actor, reason); cerr != nil { + r.errs = append(r.errs, fmt.Sprintf("Warning: failed to add reason comment on %s: %v", fullID, cerr)) + } + } + + if jsonOutput { + if updated, _ := uw.IssueUseCase().GetIssue(ctx, fullID); updated != nil { + r.unclaimed = append(r.unclaimed, updated) + } + } + r.ids = append(r.ids, fullID) + } + if len(r.ids) == 0 { + return r, "", nil + } + return r, "bd: unclaim " + strings.Join(r.ids, ", "), nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + for _, e := range res.errs { + fmt.Fprintln(os.Stderr, e) + } + + if len(res.ids) > 0 { + commandDidWrite.Store(true) + } + + if jsonOutput { + if len(res.unclaimed) > 0 { + if e := outputJSON(res.unclaimed); e != nil { + return HandleError("%v", e) + } + } + } else { + reasonMsg := "" + if reason != "" { + reasonMsg = ": " + reason + } + for _, id := range res.ids { + fmt.Printf("%s Unclaimed %s%s\n", ui.RenderPass("✓"), id, reasonMsg) + } + } + + if len(res.errs) > 0 { + return SilentExit() + } + return nil +} + +func runReclaimProxiedServer(ctx context.Context, olderThan time.Duration) error { + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + reclaimed, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) ([]types.ReclaimedLease, string, error) { + out, rerr := uw.IssueUseCase().ReclaimExpiredLeases(ctx, olderThan, actor) + if rerr != nil { + return nil, "", rerr + } + if len(out) == 0 { + return out, "", nil + } + ids := make([]string, 0, len(out)) + for _, r := range out { + ids = append(ids, r.ID) + } + return out, "bd: reclaim " + strings.Join(ids, ", "), nil + }) + if err != nil { + return HandleErrorRespectJSON("reclaim: %v", err) + } + + if len(reclaimed) > 0 { + commandDidWrite.Store(true) + } + + return renderReclaim(reclaimed) +} diff --git a/cmd/bd/undefer.go b/cmd/bd/undefer.go index 38af66409..f2f0e0c81 100644 --- a/cmd/bd/undefer.go +++ b/cmd/bd/undefer.go @@ -26,11 +26,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("undefer is not supported in proxied-server mode") - } - CheckReadonly("undefer") - evt := metrics.NewCommandEvent("undefer") defer func() { if c := metrics.Global(); c != nil { @@ -38,6 +33,12 @@ Examples: } }() + CheckReadonly("undefer") + + if usesProxiedServer() { + return runUndeferProxiedServer(rootCtx, args) + } + ctx := rootCtx _, err := utils.ResolvePartialIDs(ctx, store, args) diff --git a/internal/storage/dbproxy/util/dsn.go b/internal/storage/dbproxy/util/dsn.go index 9bd109f87..d69908b48 100644 --- a/internal/storage/dbproxy/util/dsn.go +++ b/internal/storage/dbproxy/util/dsn.go @@ -8,17 +8,18 @@ import ( ) type DoltServerDSN struct { - Socket string - Host string - Port int - User string - Password string //nolint:gosec // G117: MySQL DSN password field; required by the connection-string builder, not serialized as JSON - Database string - Timeout time.Duration - TLSRequired bool - TLSCert string - TLSKey string - TLSConfigName string + Socket string + Host string + Port int + User string + Password string //nolint:gosec // G117: MySQL DSN password field; required by the connection-string builder, not serialized as JSON + Database string + Timeout time.Duration + TLSRequired bool + TLSCert string + TLSKey string + TLSConfigName string + ClientFoundRows bool } func (d DoltServerDSN) String() string { @@ -44,6 +45,7 @@ func (d DoltServerDSN) String() string { MultiStatements: true, Timeout: timeout, AllowNativePasswords: true, + ClientFoundRows: d.ClientFoundRows, } switch { case d.TLSConfigName != "": diff --git a/internal/storage/domain/config.go b/internal/storage/domain/config.go index c70a7d87a..1ba2189cd 100644 --- a/internal/storage/domain/config.go +++ b/internal/storage/domain/config.go @@ -43,6 +43,7 @@ type ConfigUseCase interface { DeleteConfig(ctx context.Context, key string) error GetAllConfig(ctx context.Context) (map[string]string, error) GetMetadata(ctx context.Context, key string) (string, error) + GetLocalMetadata(ctx context.Context, key string) (string, error) ReconcileVersion(ctx context.Context, cliVersion string) (VersionReconcileResult, error) } @@ -184,6 +185,14 @@ func (u *configUseCaseImpl) GetMetadata(ctx context.Context, key string) (string return out, nil } +func (u *configUseCaseImpl) GetLocalMetadata(ctx context.Context, key string) (string, error) { + out, err := u.cfgRepo.GetLocalMetadata(ctx, key) + if err != nil { + return "", fmt.Errorf("GetLocalMetadata: %w", err) + } + return out, nil +} + func (u *configUseCaseImpl) SetConfig(ctx context.Context, key, value string) error { if err := u.cfgRepo.SetConfig(ctx, key, value); err != nil { return fmt.Errorf("SetConfig: %w", err) diff --git a/internal/storage/domain/db/config.go b/internal/storage/domain/db/config.go index e011e9f76..5a7046876 100644 --- a/internal/storage/domain/db/config.go +++ b/internal/storage/domain/db/config.go @@ -12,6 +12,7 @@ import ( "github.com/steveyegge/beads/internal/config" "github.com/steveyegge/beads/internal/storage/dberrors" "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/types" ) @@ -249,26 +250,7 @@ func (r *configSQLRepositoryImpl) GetAdaptiveIDConfig(ctx context.Context) (doma } func (r *configSQLRepositoryImpl) GetCustomStatuses(ctx context.Context) ([]types.CustomStatus, error) { - rows, err := r.runner.QueryContext(ctx, "SELECT name, category FROM custom_statuses ORDER BY name") - if err != nil { - return nil, fmt.Errorf("db: GetCustomStatuses: query custom_statuses: %w", err) - } - defer rows.Close() - var result []types.CustomStatus - for rows.Next() { - var name, category string - if err := rows.Scan(&name, &category); err != nil { - return nil, fmt.Errorf("db: GetCustomStatuses: scan: %w", err) - } - result = append(result, types.CustomStatus{ - Name: name, - Category: types.StatusCategory(category), - }) - } - if err := rows.Err(); err != nil { - return nil, fmt.Errorf("db: GetCustomStatuses: read custom_statuses: %w", err) - } - return result, nil + return issueops.ResolveCustomStatusesDetailedInTx(ctx, r.runner) } func (r *configSQLRepositoryImpl) ListAllStatusNames(ctx context.Context) ([]string, error) { diff --git a/internal/storage/domain/db/issue.go b/internal/storage/domain/db/issue.go index 41fbf9297..e6f4603bc 100644 --- a/internal/storage/domain/db/issue.go +++ b/internal/storage/domain/db/issue.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/domain" "github.com/steveyegge/beads/internal/storage/issueops" "github.com/steveyegge/beads/internal/storage/sqlbuild" @@ -931,4 +932,68 @@ func (r *issueSQLRepositoryImpl) GetStatistics(ctx context.Context) (*types.Stat return stats, nil } +func (r *issueSQLRepositoryImpl) CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) { + n, err := issueops.CountIssuesInTx(ctx, r.runner, query, filter) + if err != nil { + return 0, fmt.Errorf("db: IssueSQLRepository.CountIssues: %w", err) + } + return int64(n), nil +} + +func (r *issueSQLRepositoryImpl) CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) { + out, err := issueops.CountIssuesByGroupInTx(ctx, r.runner, filter, groupBy) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.CountIssuesByGroup: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) History(ctx context.Context, id string) ([]*storage.HistoryEntry, error) { + out, err := issueops.HistoryInTx(ctx, r.runner, id) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.History: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) IterEvents(ctx context.Context, id string, limit int) (storage.Iter[types.Event], error) { + events, err := issueops.GetEventsInTx(ctx, r.runner, id, limit) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.IterEvents: %w", err) + } + return storage.NewSliceIter(events), nil +} + +func (r *issueSQLRepositoryImpl) GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error) { + out, err := issueops.GetStaleIssuesInTx(ctx, r.runner, filter) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.GetStaleIssues: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) { + out, err := issueops.GetEpicsEligibleForClosureInTx(ctx, r.runner) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.GetEpicsEligibleForClosure: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) UnclaimIssue(ctx context.Context, id, actor string, force bool) error { + if err := issueops.UnclaimIssueInTx(ctx, r.runner, id, actor, force); err != nil { + return fmt.Errorf("db: IssueSQLRepository.UnclaimIssue: %w", err) + } + return nil +} + +func (r *issueSQLRepositoryImpl) ReclaimExpiredLeases(ctx context.Context, olderThan time.Duration, actor string) ([]types.ReclaimedLease, error) { + cutoff := time.Now().UTC().Add(-olderThan) + out, err := issueops.ReclaimExpiredLeasesInTx(ctx, r.runner, cutoff, actor) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.ReclaimExpiredLeases: %w", err) + } + return out, nil +} + const deleteBatchSize = 200 diff --git a/internal/storage/domain/issue.go b/internal/storage/domain/issue.go index df013429f..b78ce3848 100644 --- a/internal/storage/domain/issue.go +++ b/internal/storage/domain/issue.go @@ -63,6 +63,14 @@ type IssueSQLRepository interface { ClaimReadyWisp(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) GetStatistics(ctx context.Context) (*types.Statistics, error) + CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) + CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) + History(ctx context.Context, id string) ([]*storage.HistoryEntry, error) + IterEvents(ctx context.Context, id string, limit int) (storage.Iter[types.Event], error) + GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error) + GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) + UnclaimIssue(ctx context.Context, id, actor string, force bool) error + ReclaimExpiredLeases(ctx context.Context, olderThan time.Duration, actor string) ([]types.ReclaimedLease, error) } type CloseRowParams struct { @@ -225,6 +233,14 @@ type IssueUseCase interface { ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (ClaimReadyResult, error) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) GetStatistics(ctx context.Context) (*types.Statistics, error) + CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) + CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) + History(ctx context.Context, id string) ([]*storage.HistoryEntry, error) + IterEvents(ctx context.Context, id string, limit int) (storage.Iter[types.Event], error) + GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error) + GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) + Unclaim(ctx context.Context, id, actor string, force bool) error + ReclaimExpiredLeases(ctx context.Context, olderThan time.Duration, actor string) ([]types.ReclaimedLease, error) CreateIssue(ctx context.Context, params CreateIssueParams, actor string) (CreateIssueResult, error) CreateIssues(ctx context.Context, params []CreateIssueParams, actor string) (CreateIssuesResult, error) @@ -1443,3 +1459,69 @@ func (u *issueUseCaseImpl) GetStatistics(ctx context.Context) (*types.Statistics } return out, nil } + +func (u *issueUseCaseImpl) CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) { + out, err := u.issueRepo.CountIssues(ctx, query, filter) + if err != nil { + return 0, fmt.Errorf("CountIssues: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) { + out, err := u.issueRepo.CountIssuesByGroup(ctx, filter, groupBy) + if err != nil { + return nil, fmt.Errorf("CountIssuesByGroup: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) History(ctx context.Context, id string) ([]*storage.HistoryEntry, error) { + out, err := u.issueRepo.History(ctx, id) + if err != nil { + return nil, fmt.Errorf("History: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) IterEvents(ctx context.Context, id string, limit int) (storage.Iter[types.Event], error) { + out, err := u.issueRepo.IterEvents(ctx, id, limit) + if err != nil { + return nil, fmt.Errorf("IterEvents: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error) { + out, err := u.issueRepo.GetStaleIssues(ctx, filter) + if err != nil { + return nil, fmt.Errorf("GetStaleIssues: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) { + out, err := u.issueRepo.GetEpicsEligibleForClosure(ctx) + if err != nil { + return nil, fmt.Errorf("GetEpicsEligibleForClosure: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) Unclaim(ctx context.Context, id, actor string, force bool) error { + if id == "" { + return fmt.Errorf("Unclaim: id must not be empty") + } + if err := u.issueRepo.UnclaimIssue(ctx, id, actor, force); err != nil { + return fmt.Errorf("Unclaim: %w", err) + } + return nil +} + +func (u *issueUseCaseImpl) ReclaimExpiredLeases(ctx context.Context, olderThan time.Duration, actor string) ([]types.ReclaimedLease, error) { + out, err := u.issueRepo.ReclaimExpiredLeases(ctx, olderThan, actor) + if err != nil { + return nil, fmt.Errorf("ReclaimExpiredLeases: %w", err) + } + return out, nil +} diff --git a/internal/storage/issueops/count.go b/internal/storage/issueops/count.go index 71d7fcd3a..bb60f2f60 100644 --- a/internal/storage/issueops/count.go +++ b/internal/storage/issueops/count.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "strings" @@ -14,7 +13,7 @@ import ( // only the count: ephemeral-only filters route to the wisps table, // SkipWisps=true counts the durable issues table only, and otherwise the // wisps count is merged in (GH#4387). -func CountIssuesInTx(ctx context.Context, tx *sql.Tx, query string, filter types.IssueFilter) (int, error) { +func CountIssuesInTx(ctx context.Context, tx DBTX, query string, filter types.IssueFilter) (int, error) { if filter.Ephemeral != nil && *filter.Ephemeral { wispCount, err := countTableInTx(ctx, tx, query, filter, WispsFilterTables) if err != nil && !isTableNotExistError(err) { @@ -67,7 +66,7 @@ func CountIssuesInTx(ctx context.Context, tx *sql.Tx, query string, filter types // Mirrors CountIssuesInTx's wisps-merge semantics: ephemeral-only filters // route to the wisps table, SkipWisps=true counts the durable issues table // only, and otherwise the wisps tier is merged into each group (GH#4387). -func CountIssuesByGroupInTx(ctx context.Context, tx *sql.Tx, filter types.IssueFilter, groupBy string) (map[string]int, error) { +func CountIssuesByGroupInTx(ctx context.Context, tx DBTX, filter types.IssueFilter, groupBy string) (map[string]int, error) { if filter.Ephemeral != nil && *filter.Ephemeral { wispCounts, err := countGroupForTablesInTx(ctx, tx, filter, groupBy, WispsFilterTables) if err != nil && !isTableNotExistError(err) { @@ -117,7 +116,7 @@ func CountIssuesByGroupInTx(ctx context.Context, tx *sql.Tx, filter types.IssueF // countGroupForTablesInTx runs a grouped count against one table set // (issues or wisps) and normalizes keys to bd count's display format. -func countGroupForTablesInTx(ctx context.Context, tx *sql.Tx, filter types.IssueFilter, groupBy string, tables FilterTables) (map[string]int, error) { +func countGroupForTablesInTx(ctx context.Context, tx DBTX, filter types.IssueFilter, groupBy string, tables FilterTables) (map[string]int, error) { if groupBy == "label" { return countByLabelInTx(ctx, tx, filter, tables) } @@ -156,7 +155,7 @@ func countGroupForTablesInTx(ctx context.Context, tx *sql.Tx, filter types.Issue } // countTableInTx runs SELECT COUNT(*) FROM WHERE . -func countTableInTx(ctx context.Context, tx *sql.Tx, query string, filter types.IssueFilter, tables FilterTables) (int, error) { +func countTableInTx(ctx context.Context, tx DBTX, query string, filter types.IssueFilter, tables FilterTables) (int, error) { clauses, args, err := BuildIssueFilterClauses(query, filter, tables) if err != nil { return 0, err @@ -176,7 +175,7 @@ func countTableInTx(ctx context.Context, tx *sql.Tx, query string, filter types. // countByColumnInTx runs SELECT , COUNT(*) GROUP BY against a table. // Returns raw column values as keys (callers normalize for display). -func countByColumnInTx(ctx context.Context, tx *sql.Tx, filter types.IssueFilter, col string, tables FilterTables) (map[string]int, error) { +func countByColumnInTx(ctx context.Context, tx DBTX, filter types.IssueFilter, col string, tables FilterTables) (map[string]int, error) { clauses, args, err := BuildIssueFilterClauses("", filter, tables) if err != nil { return nil, err @@ -209,7 +208,7 @@ func countByColumnInTx(ctx context.Context, tx *sql.Tx, filter types.IssueFilter // countByLabelInTx counts issues grouped by label using a subquery to avoid // Dolt's joinIter panic (join_iters.go:192). Issues with no labels are counted // under "(no labels)". -func countByLabelInTx(ctx context.Context, tx *sql.Tx, filter types.IssueFilter, tables FilterTables) (map[string]int, error) { +func countByLabelInTx(ctx context.Context, tx DBTX, filter types.IssueFilter, tables FilterTables) (map[string]int, error) { clauses, args, err := BuildIssueFilterClauses("", filter, tables) if err != nil { return nil, err diff --git a/internal/storage/issueops/epic_closure.go b/internal/storage/issueops/epic_closure.go index 2e37f65d4..ede8f3b50 100644 --- a/internal/storage/issueops/epic_closure.go +++ b/internal/storage/issueops/epic_closure.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "github.com/steveyegge/beads/internal/types" @@ -10,7 +9,7 @@ import ( // GetEpicsEligibleForClosureInTx returns epics whose children are all closed. // nolint:gosec // G201: table names are hardcoded, placeholders contain only ? markers -func GetEpicsEligibleForClosureInTx(ctx context.Context, tx *sql.Tx) ([]*types.EpicStatus, error) { +func GetEpicsEligibleForClosureInTx(ctx context.Context, tx DBTX) ([]*types.EpicStatus, error) { // Step 1: Get open epic IDs (single-table scan) epicRows, err := tx.QueryContext(ctx, ` SELECT id FROM issues diff --git a/internal/storage/issueops/events.go b/internal/storage/issueops/events.go index c80a56ce8..693ab5ed9 100644 --- a/internal/storage/issueops/events.go +++ b/internal/storage/issueops/events.go @@ -12,7 +12,7 @@ import ( // GetEventsInTx retrieves events for an issue. If limit <= 0, all events are returned. // //nolint:gosec // G201: table is hardcoded via WispTableRouting -func GetEventsInTx(ctx context.Context, tx *sql.Tx, issueID string, limit int) ([]*types.Event, error) { +func GetEventsInTx(ctx context.Context, tx DBTX, issueID string, limit int) ([]*types.Event, error) { _, _, eventTable, _ := WispTableRouting(IsActiveWispInTx(ctx, tx, issueID)) query := fmt.Sprintf(` diff --git a/internal/storage/issueops/history.go b/internal/storage/issueops/history.go index 31a020bbd..7eedbfce2 100644 --- a/internal/storage/issueops/history.go +++ b/internal/storage/issueops/history.go @@ -16,7 +16,7 @@ import ( // The subquery wrapper avoids Dolt's max1Row optimization on PK lookup: // dolt_history_* tables return multiple rows per PK (one per commit), but // the query planner incorrectly assumes WHERE id=? returns one row. -func HistoryInTx(ctx context.Context, tx *sql.Tx, issueID string) ([]*storage.HistoryEntry, error) { +func HistoryInTx(ctx context.Context, tx DBTX, issueID string) ([]*storage.HistoryEntry, error) { rows, err := tx.QueryContext(ctx, ` SELECT id, title, description, design, acceptance_criteria, notes, diff --git a/internal/storage/issueops/stale.go b/internal/storage/issueops/stale.go index 5e1526348..37238f263 100644 --- a/internal/storage/issueops/stale.go +++ b/internal/storage/issueops/stale.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "time" @@ -15,7 +14,7 @@ import ( // Results are ordered by updated_at ascending (stalest first). // // nolint:gosec // G201: statusClause contains only literal SQL or a single ? placeholder -func GetStaleIssuesInTx(ctx context.Context, tx *sql.Tx, filter types.StaleFilter) ([]*types.Issue, error) { +func GetStaleIssuesInTx(ctx context.Context, tx DBTX, filter types.StaleFilter) ([]*types.Issue, error) { cutoff := time.Now().UTC().AddDate(0, 0, -filter.Days) statusClause := "status IN ('open', 'in_progress')" diff --git a/internal/storage/issueops/unclaim.go b/internal/storage/issueops/unclaim.go index c74b139c8..9f9ed7854 100644 --- a/internal/storage/issueops/unclaim.go +++ b/internal/storage/issueops/unclaim.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "encoding/json" "fmt" "time" @@ -29,7 +28,7 @@ import ( // - Issue is claimed by a different actor and force is false (ErrNotOwner) // //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func UnclaimIssueInTx(ctx context.Context, tx *sql.Tx, id string, actor string, force bool) error { +func UnclaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string, force bool) error { // Route to the correct table (issues/wisps) automatically, matching // ClaimIssueInTx — a wisp claim lives in the wisp tables, so its release // must update them too rather than no-op against the permanent issues table. @@ -110,7 +109,7 @@ func UnclaimIssueInTx(ctx context.Context, tx *sql.Tx, id string, actor string, // no-op when none exists, e.g. a wisp or an open-but-assigned issue that was // never leased) and records the "unclaimed" event. The row mutation // (assignee/status/started_at/row_lock) must already have been applied in tx. -func finishUnclaimInTx(ctx context.Context, tx *sql.Tx, eventTable string, id string, actor string, oldIssue *types.Issue) error { +func finishUnclaimInTx(ctx context.Context, tx DBTX, eventTable string, id string, actor string, oldIssue *types.Issue) error { if err := DeleteLeaseInTx(ctx, tx, id); err != nil { return err } @@ -139,7 +138,7 @@ func finishUnclaimInTx(ctx context.Context, tx *sql.Tx, eventTable string, id st // untouched. actor is recorded as the event author. // //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func UnclaimIssueIfAssigneeInTx(ctx context.Context, tx *sql.Tx, id string, actor string, expectedAssignee string) error { +func UnclaimIssueIfAssigneeInTx(ctx context.Context, tx DBTX, id string, actor string, expectedAssignee string) error { if expectedAssignee == "" { return fmt.Errorf("conditional unclaim of %s: expected assignee must not be empty (use UnclaimIssueInTx for an unconditional release)", id) } diff --git a/internal/storage/uow/dolt_sql_provider.go b/internal/storage/uow/dolt_sql_provider.go index 42205e1d1..ce43c7456 100644 --- a/internal/storage/uow/dolt_sql_provider.go +++ b/internal/storage/uow/dolt_sql_provider.go @@ -98,12 +98,13 @@ func (p *doltSQLProvider) initSchema(ctx context.Context, database string) error func buildDSN(ep proxy.Endpoint, database, user, password, tlsConfigName string) string { return util.DoltServerDSN{ - Host: ep.Host, - Port: ep.Port, - User: user, - Password: password, - Database: database, - TLSConfigName: tlsConfigName, + Host: ep.Host, + Port: ep.Port, + User: user, + Password: password, + Database: database, + TLSConfigName: tlsConfigName, + ClientFoundRows: true, }.String() }