diff --git a/cmd/bd/blocked_proxied_integration_test.go b/cmd/bd/blocked_proxied_integration_test.go new file mode 100644 index 000000000..fa2009990 --- /dev/null +++ b/cmd/bd/blocked_proxied_integration_test.go @@ -0,0 +1,124 @@ +//go:build cgo + +package main + +import ( + "bytes" + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/types" +) + +func bdProxiedBlockedJSON(t *testing.T, bd string, p proxiedProject, args ...string) []*types.BlockedIssue { + t.Helper() + fullArgs := append([]string{"blocked", "--json"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...) + if err != nil { + t.Fatalf("bd blocked --json %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "[") + if start < 0 { + t.Fatalf("no JSON array in blocked --json output: %s", stdout) + } + var out []*types.BlockedIssue + if err := json.Unmarshal([]byte(s[start:]), &out); err != nil { + t.Fatalf("parse blocked JSON: %v\n%s", err, s[start:]) + } + return out +} + +func bdProxiedBlockedCapture(t *testing.T, bd string, p proxiedProject, args ...string) (string, string) { + t.Helper() + fullArgs := append([]string{"blocked"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...) + if err != nil { + t.Fatalf("bd blocked %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + return stdout, stderr +} + +func TestProxiedServerBlocked(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("json_and_text_with_blockers", func(t *testing.T) { + p := bdProxiedInit(t, bd, "bk1") + blocker := bdProxiedCreate(t, bd, p.dir, "The blocker") + dependent := bdProxiedCreate(t, bd, p.dir, "I am blocked", "--deps", "depends-on:"+blocker.ID) + + got := bdProxiedBlockedJSON(t, bd, p) + var entry *types.BlockedIssue + for _, bi := range got { + if bi.ID == dependent.ID { + entry = bi + break + } + } + if entry == nil { + out, _ := json.Marshal(got) + t.Fatalf("expected %s in blocked listing, got: %s", dependent.ID, out) + } + if entry.BlockedByCount != 1 { + t.Errorf("BlockedByCount = %d, want 1", entry.BlockedByCount) + } + if len(entry.BlockedBy) != 1 || entry.BlockedBy[0] != blocker.ID { + t.Errorf("BlockedBy = %v, want [%s]", entry.BlockedBy, blocker.ID) + } + + stdout, _ := bdProxiedBlockedCapture(t, bd, p) + if !strings.Contains(stdout, "Blocked issues") { + t.Errorf("expected heading in text output, got: %s", stdout) + } + if !strings.Contains(stdout, "Blocked by 1 open dependencies") { + t.Errorf("expected blocker summary line, got: %s", stdout) + } + }) + + t.Run("empty_case", func(t *testing.T) { + p := bdProxiedInit(t, bd, "bk2") + bdProxiedCreate(t, bd, p.dir, "Nothing blocked here") + + out, err := bdProxiedRun(t, bd, p.dir, "blocked", "--json") + if err != nil { + t.Fatalf("bd blocked --json failed: %v\n%s", err, out) + } + var empty []*types.BlockedIssue + if err := json.Unmarshal(bytes.TrimSpace(out), &empty); err != nil { + t.Fatalf("parse empty blocked JSON: %v\n%s", err, out) + } + if len(empty) != 0 { + t.Errorf("expected [] for no blockers, got %d entries", len(empty)) + } + + stdout, _ := bdProxiedBlockedCapture(t, bd, p) + if !strings.Contains(stdout, "No blocked issues") { + t.Errorf("expected 'No blocked issues' message, got: %s", stdout) + } + }) + + t.Run("parent_filter_restricts_to_descendants", func(t *testing.T) { + p := bdProxiedInit(t, bd, "bk3") + parent := bdProxiedCreate(t, bd, p.dir, "Parent epic", "--type", "epic") + blocker := bdProxiedCreate(t, bd, p.dir, "Inside blocker") + inside := bdProxiedCreate(t, bd, p.dir, "Inside blocked", "--parent", parent.ID, "--deps", "depends-on:"+blocker.ID) + outsideBlocker := bdProxiedCreate(t, bd, p.dir, "Outside blocker") + outside := bdProxiedCreate(t, bd, p.dir, "Outside blocked", "--deps", "depends-on:"+outsideBlocker.ID) + + got := bdProxiedBlockedJSON(t, bd, p, "--parent", parent.ID) + ids := map[string]bool{} + for _, bi := range got { + ids[bi.ID] = true + } + if !ids[inside.ID] { + t.Errorf("expected descendant %s in --parent result", inside.ID) + } + if ids[outside.ID] { + t.Errorf("non-descendant %s leaked into --parent result", outside.ID) + } + }) +} diff --git a/cmd/bd/ready.go b/cmd/bd/ready.go index cb818bb22..1399a66c4 100644 --- a/cmd/bd/ready.go +++ b/cmd/bd/ready.go @@ -36,6 +36,11 @@ Use --claim to atomically claim the first ready issue matching the filters: This is useful for agents executing molecules to see which steps can run next.`, Run: func(cmd *cobra.Command, args []string) { + if usesProxiedServer() { + runReadyProxiedServer(cmd, rootCtx) + return + } + claimReady, _ := cmd.Flags().GetBool("claim") // Handle --gated flag (gate-resume discovery) @@ -321,6 +326,10 @@ var blockedCmd = &cobra.Command{ Use: "blocked", Short: "Show blocked issues", Run: func(cmd *cobra.Command, args []string) { + if usesProxiedServer() { + runBlockedProxiedServer(cmd, rootCtx) + return + } // Use global jsonOutput set by PersistentPreRun (respects config.yaml + env vars) // Use factory to respect backend configuration (bd-m2jr: SQLite fallback fix) ctx := rootCtx diff --git a/cmd/bd/ready_input.go b/cmd/bd/ready_input.go new file mode 100644 index 000000000..b60c93fee --- /dev/null +++ b/cmd/bd/ready_input.go @@ -0,0 +1,154 @@ +package main + +import ( + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/config" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" +) + +type readyInput struct { + filter types.WorkFilter + limit int + claim bool + gated bool + molID string + explain bool + prettyFormat bool + plainFormat bool + parentID string + jsonOut bool +} + +func gatherReadyInput(cmd *cobra.Command) readyInput { + in := readyInput{} + + in.claim, _ = cmd.Flags().GetBool("claim") + in.gated, _ = cmd.Flags().GetBool("gated") + in.molID, _ = cmd.Flags().GetString("mol") + in.explain, _ = cmd.Flags().GetBool("explain") + in.prettyFormat, _ = cmd.Flags().GetBool("pretty") + in.plainFormat, _ = cmd.Flags().GetBool("plain") + in.jsonOut = jsonOutput + + in.limit, _ = cmd.Flags().GetInt("limit") + assignee, _ := cmd.Flags().GetString("assignee") + unassigned, _ := cmd.Flags().GetBool("unassigned") + sortPolicy, _ := cmd.Flags().GetString("sort") + labels, _ := cmd.Flags().GetStringSlice("label") + labelsAny, _ := cmd.Flags().GetStringSlice("label-any") + excludeLabels, _ := cmd.Flags().GetStringSlice("exclude-label") + issueType, _ := cmd.Flags().GetString("type") + issueType = utils.NormalizeIssueType(issueType) + in.parentID, _ = cmd.Flags().GetString("parent") + molTypeStr, _ := cmd.Flags().GetString("mol-type") + includeDeferred, _ := cmd.Flags().GetBool("include-deferred") + includeEphemeral, _ := cmd.Flags().GetBool("include-ephemeral") + excludeTypeStrs, _ := cmd.Flags().GetStringSlice("exclude-type") + + var molType *types.MolType + if molTypeStr != "" { + mt := types.MolType(molTypeStr) + if !mt.IsValid() { + FatalError("invalid mol-type %q (must be swarm, patrol, or work)", molTypeStr) + } + molType = &mt + } + + if in.claim && assignee != "" { + FatalErrorRespectJSON("--claim cannot be combined with --assignee") + } + if in.claim && in.gated { + FatalErrorRespectJSON("--claim cannot be combined with --gated") + } + if in.claim && in.molID != "" { + FatalErrorRespectJSON("--claim cannot be combined with --mol") + } + if in.claim && in.explain { + FatalErrorRespectJSON("--claim cannot be combined with --explain") + } + + labels = utils.NormalizeLabels(labels) + labelsAny = utils.NormalizeLabels(labelsAny) + excludeLabels = utils.NormalizeLabels(excludeLabels) + + if len(labels) == 0 && len(labelsAny) == 0 { + if dirLabels := config.GetDirectoryLabels(); len(dirLabels) > 0 { + labelsAny = dirLabels + } + } + + var excludeTypes []types.IssueType + for _, raw := range excludeTypeStrs { + for _, t := range strings.Split(raw, ",") { + t = strings.TrimSpace(t) + if t != "" { + excludeTypes = append(excludeTypes, types.IssueType(utils.NormalizeIssueType(t))) + } + } + } + + in.filter = types.WorkFilter{ + Status: "open", + Type: issueType, + Limit: in.limit, + Unassigned: unassigned, + SortPolicy: types.SortPolicy(sortPolicy), + Labels: labels, + LabelsAny: labelsAny, + ExcludeLabels: excludeLabels, + IncludeDeferred: includeDeferred, + IncludeEphemeral: includeEphemeral, + ExcludeTypes: excludeTypes, + } + if cmd.Flags().Changed("priority") { + priority, _ := cmd.Flags().GetInt("priority") + in.filter.Priority = &priority + } + if assignee != "" && !unassigned { + in.filter.Assignee = &assignee + } + if in.parentID != "" { + in.filter.ParentID = &in.parentID + } + if molType != nil { + in.filter.MolType = molType + } + + metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field") + if len(metadataFieldFlags) > 0 { + in.filter.MetadataFields = make(map[string]string, len(metadataFieldFlags)) + for _, mf := range metadataFieldFlags { + k, v, ok := strings.Cut(mf, "=") + if !ok || k == "" { + fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field: expected key=value, got %q\n", mf) + os.Exit(1) + } + if err := storage.ValidateMetadataKey(k); err != nil { + fmt.Fprintf(os.Stderr, "Error: invalid --metadata-field key: %v\n", err) + os.Exit(1) + } + in.filter.MetadataFields[k] = v + } + } + hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key") + if hasMetadataKey != "" { + if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil { + fmt.Fprintf(os.Stderr, "Error: invalid --has-metadata-key: %v\n", err) + os.Exit(1) + } + in.filter.HasMetadataKey = hasMetadataKey + } + + if !in.filter.SortPolicy.IsValid() { + FatalError("invalid sort policy '%s'. Valid values: hybrid, priority, oldest", sortPolicy) + } + + return in +} diff --git a/cmd/bd/ready_proxied_integration_test.go b/cmd/bd/ready_proxied_integration_test.go new file mode 100644 index 000000000..874653804 --- /dev/null +++ b/cmd/bd/ready_proxied_integration_test.go @@ -0,0 +1,713 @@ +//go:build cgo + +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os/exec" + "strings" + "sync" + "testing" + + "github.com/steveyegge/beads/internal/storage/depid" + "github.com/steveyegge/beads/internal/types" +) + +func bdProxiedClaimCmd(bd, dir, actor string) *exec.Cmd { + cmd := exec.Command(bd, "ready", "--claim", "--json", "--label", "atomic") + cmd.Dir = dir + env := bdProxiedEnv(dir) + env = append(env, "BEADS_ACTOR="+actor) + cmd.Env = env + return cmd +} + +func bdProxiedReadyJSON(t *testing.T, bd string, p proxiedProject, args ...string) []*types.IssueWithCounts { + t.Helper() + fullArgs := append([]string{"ready", "--json"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...) + if err != nil { + t.Fatalf("bd ready --json %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "[") + if start < 0 { + t.Fatalf("no JSON array in ready --json output:\n%s", stdout) + } + var issues []*types.IssueWithCounts + if err := json.Unmarshal([]byte(s[start:]), &issues); err != nil { + t.Fatalf("parse ready JSON: %v\n%s", err, s[start:]) + } + return issues +} + +func bdProxiedReadyCapture(t *testing.T, bd string, p proxiedProject, args ...string) (string, string) { + t.Helper() + fullArgs := append([]string{"ready"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...) + if err != nil { + t.Fatalf("bd ready %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + return stdout, stderr +} + +func bdProxiedReadyFail(t *testing.T, bd string, p proxiedProject, args ...string) string { + t.Helper() + fullArgs := append([]string{"ready"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, fullArgs...) + if err == nil { + t.Fatalf("bd ready %s should have failed; stdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), stdout, stderr) + } + return stdout + stderr +} + +func TestProxiedServerReady(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("json_round_trips_issue_with_counts", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdj1") + issue := bdProxiedCreate(t, bd, p.dir, "Zero deps", "--label", "rdj1-only") + ready := bdProxiedReadyJSON(t, bd, p, "--label", "rdj1-only") + if len(ready) != 1 { + t.Fatalf("ready count = %d, want 1", len(ready)) + } + if ready[0].ID != issue.ID { + t.Fatalf("ready[0].ID = %s, want %s", ready[0].ID, issue.ID) + } + if ready[0].DependencyCount != 0 { + t.Errorf("DependencyCount = %d, want 0", ready[0].DependencyCount) + } + }) + + t.Run("default_text_output", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdt") + bdProxiedCreate(t, bd, p.dir, "Ready title here") + stdout, _ := bdProxiedReadyCapture(t, bd, p) + if !strings.Contains(stdout, "Ready title here") { + t.Errorf("expected issue title in output, got: %s", stdout) + } + }) + + t.Run("json_validity", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdv") + bdProxiedCreate(t, bd, p.dir, "JSON test") + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--json") + if err != nil { + t.Fatalf("bd ready --json failed: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.IndexAny(s, "[{") + if start < 0 { + t.Fatalf("no JSON in output: %s", s) + } + if !json.Valid([]byte(s[start:])) { + t.Errorf("invalid JSON: %s", s[start:]) + } + }) + + t.Run("limit_truncation_hint_on_stderr", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdl") + for i := 0; i < 4; i++ { + bdProxiedCreate(t, bd, p.dir, fmt.Sprintf("Ready item %d", i)) + } + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--json", "--limit", "2") + if err != nil { + t.Fatalf("bd ready --json --limit 2 failed: %v\nstderr: %s\nstdout: %s", err, stderr, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "[") + if start < 0 || !json.Valid([]byte(s[start:])) { + t.Fatalf("stdout JSON should remain parseable, got: %s", stdout) + } + if !strings.Contains(stderr, "Use --limit 0 for all") { + t.Fatalf("expected truncation hint on stderr, got: %q", stderr) + } + }) + + t.Run("claim_json_no_match_returns_empty_array", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rcn") + bdProxiedCreate(t, bd, p.dir, "Has wrong label", "--label", "real") + out, err := bdProxiedRun(t, bd, p.dir, "ready", "--claim", "--json", "--label", "missing-label") + if err != nil { + t.Fatalf("bd ready --claim --json with no match failed: %v\n%s", err, out) + } + var empty []types.IssueWithCounts + if err := json.Unmarshal(bytes.TrimSpace(out), &empty); err != nil { + t.Fatalf("parse empty claim JSON: %v\n%s", err, out) + } + if len(empty) != 0 { + t.Fatalf("expected no claimed issues, got %d: %s", len(empty), out) + } + }) + + t.Run("claim_json_marks_in_progress_and_assignee", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rcm") + issue := bdProxiedCreate(t, bd, p.dir, "Claim me", "--label", "claim-me") + out, err := bdProxiedRun(t, bd, p.dir, "ready", "--claim", "--json", "--label", "claim-me") + if err != nil { + t.Fatalf("bd ready --claim --json failed: %v\n%s", err, out) + } + var claimed []types.IssueWithCounts + if err := json.Unmarshal(bytes.TrimSpace(out), &claimed); err != nil { + t.Fatalf("parse claim JSON: %v\n%s", err, out) + } + if len(claimed) != 1 { + t.Fatalf("expected one claimed issue, got %d: %s", len(claimed), out) + } + if claimed[0].ID != issue.ID { + t.Fatalf("claimed ID = %s, want %s", claimed[0].ID, issue.ID) + } + if claimed[0].Status != types.StatusInProgress { + t.Errorf("Status = %s, want %s", claimed[0].Status, types.StatusInProgress) + } + if claimed[0].Assignee == "" { + t.Error("Assignee should be set after claim") + } + shown := bdProxiedShow(t, bd, p.dir, issue.ID) + if shown.Status != types.StatusInProgress { + t.Errorf("after re-fetch: Status = %s, want %s", shown.Status, types.StatusInProgress) + } + if shown.Assignee == "" { + t.Error("after re-fetch: Assignee empty (commit may not have persisted)") + } + }) + + t.Run("blocked_issues_excluded_from_default_output", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdb") + blocker := bdProxiedCreate(t, bd, p.dir, "Blocker issue") + bdProxiedCreate(t, bd, p.dir, "Should be hidden because blocked", "--deps", "depends-on:"+blocker.ID) + stdout, _ := bdProxiedReadyCapture(t, bd, p) + if strings.Contains(stdout, "Should be hidden because blocked") { + t.Errorf("blocked issue must not appear in ready output: %s", stdout) + } + }) + + t.Run("exclude_label_filter", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdex") + bdProxiedCreate(t, bd, p.dir, "Triage pending item", "--label", "triage:pending") + bdProxiedCreate(t, bd, p.dir, "Normal ready item") + stdout, _ := bdProxiedReadyCapture(t, bd, p, "--exclude-label", "triage:pending") + if strings.Contains(stdout, "Triage pending item") { + t.Errorf("triage:pending issue must be excluded: %s", stdout) + } + if !strings.Contains(stdout, "Normal ready item") { + t.Errorf("normal issue must appear: %s", stdout) + } + }) + + t.Run("explain_json_round_trip", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rde") + bdProxiedCreate(t, bd, p.dir, "Plain ready") + blocker := bdProxiedCreate(t, bd, p.dir, "Live blocker") + bdProxiedCreate(t, bd, p.dir, "Blocked dependent", "--deps", "depends-on:"+blocker.ID) + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--explain", "--json") + if err != nil { + t.Fatalf("bd ready --explain --json failed: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "{") + if start < 0 { + t.Fatalf("no JSON in --explain output: %s", stdout) + } + var exp types.ReadyExplanation + if err := json.Unmarshal([]byte(s[start:]), &exp); err != nil { + t.Fatalf("parse ReadyExplanation: %v\n%s", err, s[start:]) + } + if exp.Summary.TotalReady < 1 { + t.Errorf("Summary.TotalReady = %d, want >=1", exp.Summary.TotalReady) + } + if exp.Summary.TotalBlocked < 1 { + t.Errorf("Summary.TotalBlocked = %d, want >=1", exp.Summary.TotalBlocked) + } + }) + + t.Run("explain_text_header", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdet") + bdProxiedCreate(t, bd, p.dir, "Smoke") + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--explain") + if err != nil { + t.Fatalf("bd ready --explain failed: %v\n%s", err, stdout) + } + if !strings.Contains(stdout, "Ready Work Explanation") { + t.Errorf("expected explain heading, got: %s", stdout) + } + }) + + t.Run("explain_detects_cycles", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdc") + a := bdProxiedCreate(t, bd, p.dir, "Cycle node A") + b := bdProxiedCreate(t, bd, p.dir, "Cycle node B") + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) VALUES (?, ?, ?, ?, NOW(), 'test')", + depid.New(a.ID, b.ID), a.ID, b.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant a->b edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) VALUES (?, ?, ?, ?, NOW(), 'test')", + depid.New(b.ID, a.ID), b.ID, a.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant b->a edge: %v", err) + } + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--explain", "--json") + if err != nil { + t.Fatalf("bd ready --explain --json after cycle plant: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "{") + if start < 0 { + t.Fatalf("no JSON in --explain output: %s", stdout) + } + var exp types.ReadyExplanation + if err := json.Unmarshal([]byte(s[start:]), &exp); err != nil { + t.Fatalf("parse ReadyExplanation: %v\n%s", err, s[start:]) + } + if len(exp.Cycles) == 0 { + t.Errorf("expected non-empty Cycles after planting a->b->a, got: %+v", exp) + } + }) + + t.Run("gated_empty_case", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdge") + bdProxiedCreate(t, bd, p.dir, "No gates anywhere") + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--gated", "--json") + if err != nil { + t.Fatalf("bd ready --gated --json failed: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "{") + if start < 0 { + t.Fatalf("no JSON in gated output: %s", stdout) + } + var out GatedReadyOutput + if err := json.Unmarshal([]byte(s[start:]), &out); err != nil { + t.Fatalf("parse GatedReadyOutput: %v\n%s", err, s[start:]) + } + if len(out.Molecules) != 0 { + t.Errorf("expected empty molecules array, got %d", len(out.Molecules)) + } + + text, _ := bdProxiedReadyCapture(t, bd, p, "--gated") + if !strings.Contains(text, "No closed gates found") { + t.Errorf("expected 'No closed gates found' text, got: %s", text) + } + }) + + t.Run("gated_json_shape_with_open_gate", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdgw") + bdProxiedCreate(t, bd, p.dir, "Open gate", "--type", "gate") + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--gated", "--json") + if err != nil { + t.Fatalf("bd ready --gated --json failed: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "{") + if start < 0 { + t.Fatalf("no JSON in gated output: %s", stdout) + } + var out GatedReadyOutput + if err := json.Unmarshal([]byte(s[start:]), &out); err != nil { + t.Fatalf("parse GatedReadyOutput: %v\n%s", err, s[start:]) + } + if len(out.Molecules) != 0 { + t.Errorf("open (non-closed) gate must not appear in gated output, got %d", len(out.Molecules)) + } + }) + + t.Run("mol_text_and_json", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdm") + mol := bdProxiedCreate(t, bd, p.dir, "Mol parent", "--type", "molecule") + s1 := bdProxiedCreate(t, bd, p.dir, "Step one", "--parent", mol.ID) + bdProxiedCreate(t, bd, p.dir, "Step two", "--parent", mol.ID, "--deps", "depends-on:"+s1.ID) + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--mol", mol.ID, "--json") + if err != nil { + t.Fatalf("bd ready --mol --json failed: %v\n%s", err, stdout) + } + sj := strings.TrimSpace(stdout) + start := strings.Index(sj, "{") + if start < 0 { + t.Fatalf("no JSON in --mol output: %s", stdout) + } + var out MoleculeReadyOutput + if err := json.Unmarshal([]byte(sj[start:]), &out); err != nil { + t.Fatalf("parse MoleculeReadyOutput: %v\n%s", err, sj[start:]) + } + if out.TotalSteps < 2 { + t.Errorf("TotalSteps = %d, want >=2", out.TotalSteps) + } + if out.ReadySteps < 1 { + t.Errorf("ReadySteps = %d, want >=1", out.ReadySteps) + } + + text, _ := bdProxiedReadyCapture(t, bd, p, "--mol", mol.ID) + if !strings.Contains(text, "Mol parent") { + t.Errorf("expected molecule title in text output, got: %s", text) + } + }) + + t.Run("empty_state_no_open_issues", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdei") + stdout, _ := bdProxiedReadyCapture(t, bd, p) + if !strings.Contains(stdout, "No open issues") { + t.Errorf("expected 'No open issues', got: %s", stdout) + } + }) + + t.Run("empty_state_no_ready_with_blockers", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdeb") + blocker := bdProxiedCreate(t, bd, p.dir, "Self-blocker") + bdProxiedCreate(t, bd, p.dir, "Only issue, blocked", "--deps", "blocks:"+blocker.ID) + if _, err := bdProxiedRun(t, bd, p.dir, "ready", "--claim", "--json"); err == nil { + } + if _, err := bdProxiedRun(t, bd, p.dir, "update", blocker.ID, "--claim"); err != nil { + t.Fatalf("update --claim blocker: %v", err) + } + stdout, _ := bdProxiedReadyCapture(t, bd, p, "--label", "no-such-label") + if !strings.Contains(stdout, "No ready work found") && !strings.Contains(stdout, "No open issues") { + t.Errorf("expected empty-state hint, got: %s", stdout) + } + }) + + t.Run("filter_priority_pass_through", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rfp") + hi := bdProxiedCreate(t, bd, p.dir, "Hi pri", "-p", "0") + lo := bdProxiedCreate(t, bd, p.dir, "Lo pri", "-p", "3") + ready := bdProxiedReadyJSON(t, bd, p, "-p", "0") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[hi.ID] { + t.Errorf("expected %s in priority=0 filter result", hi.ID) + } + if ids[lo.ID] { + t.Errorf("did not expect %s in priority=0 result", lo.ID) + } + }) + + t.Run("filter_assignee_pass_through", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rfa") + mine := bdProxiedCreate(t, bd, p.dir, "Alice work", "--assignee", "alice") + bdProxiedCreate(t, bd, p.dir, "Bob work", "--assignee", "bob") + ready := bdProxiedReadyJSON(t, bd, p, "--assignee", "alice") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[mine.ID] { + t.Errorf("expected %s for assignee=alice", mine.ID) + } + for _, r := range ready { + if r.Assignee != "alice" { + t.Errorf("got non-alice assignee %q for %s", r.Assignee, r.ID) + } + } + }) + + t.Run("filter_unassigned_pass_through", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rfu") + un := bdProxiedCreate(t, bd, p.dir, "Free agent") + bdProxiedCreate(t, bd, p.dir, "Taken", "--assignee", "alice") + ready := bdProxiedReadyJSON(t, bd, p, "--unassigned") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[un.ID] { + t.Errorf("expected %s in --unassigned result", un.ID) + } + for _, r := range ready { + if r.Assignee != "" { + t.Errorf("got assignee %q for %s under --unassigned", r.Assignee, r.ID) + } + } + }) + + t.Run("filter_type_pass_through", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rft") + bug := bdProxiedCreate(t, bd, p.dir, "A bug", "--type", "bug") + bdProxiedCreate(t, bd, p.dir, "A task", "--type", "task") + ready := bdProxiedReadyJSON(t, bd, p, "--type", "bug") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[bug.ID] { + t.Errorf("expected %s for --type=bug", bug.ID) + } + for _, r := range ready { + if r.IssueType != types.TypeBug { + t.Errorf("got type %s for %s under --type=bug", r.IssueType, r.ID) + } + } + }) + + t.Run("filter_parent_pass_through", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rfpar") + epic := bdProxiedCreate(t, bd, p.dir, "Epic", "--type", "epic") + child := bdProxiedCreate(t, bd, p.dir, "Inside", "--parent", epic.ID) + outside := bdProxiedCreate(t, bd, p.dir, "Outside") + ready := bdProxiedReadyJSON(t, bd, p, "--parent", epic.ID) + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[child.ID] { + t.Errorf("expected %s under --parent=%s", child.ID, epic.ID) + } + if ids[outside.ID] { + t.Errorf("outside-of-parent issue %s leaked into --parent result", outside.ID) + } + }) + + t.Run("metadata_field_match", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rmd1") + match := bdProxiedCreate(t, bd, p.dir, "Has team", "--metadata", `{"team":"platform"}`) + bdProxiedCreate(t, bd, p.dir, "Other team", "--metadata", `{"team":"frontend"}`) + ready := bdProxiedReadyJSON(t, bd, p, "--metadata-field", "team=platform") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[match.ID] { + t.Errorf("expected %s for team=platform filter", match.ID) + } + }) + + t.Run("metadata_has_key", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rmd2") + withMeta := bdProxiedCreate(t, bd, p.dir, "With meta", "--metadata", `{"team":"x"}`) + bdProxiedCreate(t, bd, p.dir, "No meta") + ready := bdProxiedReadyJSON(t, bd, p, "--has-metadata-key", "team") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[withMeta.ID] { + t.Errorf("expected %s in --has-metadata-key=team result", withMeta.ID) + } + }) + + t.Run("metadata_field_invalid_key_errors", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rmd3") + out := bdProxiedReadyFail(t, bd, p, "--metadata-field", "bad$key=x") + if !strings.Contains(out, "metadata-field") { + t.Errorf("expected validation error about metadata-field, got: %s", out) + } + }) + + t.Run("include_deferred_toggle", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdd") + issue := bdProxiedCreate(t, bd, p.dir, "Will defer") + db := openProxiedDB(t, p) + if _, err := db.ExecContext(context.Background(), + "UPDATE issues SET defer_until = DATE_ADD(UTC_TIMESTAMP(), INTERVAL 1 DAY) WHERE id = ?", issue.ID); err != nil { + t.Fatalf("plant defer_until: %v", err) + } + ready := bdProxiedReadyJSON(t, bd, p) + for _, r := range ready { + if r.ID == issue.ID { + t.Errorf("future-deferred issue %s should be hidden by default", issue.ID) + } + } + ready2 := bdProxiedReadyJSON(t, bd, p, "--include-deferred") + found := false + for _, r := range ready2 { + if r.ID == issue.ID { + found = true + break + } + } + if !found { + t.Errorf("expected deferred %s under --include-deferred", issue.ID) + } + }) + + t.Run("include_ephemeral_surfaces_wisps", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rdie") + reg := bdProxiedCreate(t, bd, p.dir, "Regular") + wisp := bdProxiedCreate(t, bd, p.dir, "Wispy", "--ephemeral") + def := bdProxiedReadyJSON(t, bd, p) + ids := map[string]bool{} + for _, r := range def { + ids[r.ID] = true + } + if !ids[reg.ID] { + t.Errorf("expected regular %s in default result", reg.ID) + } + if ids[wisp.ID] { + t.Errorf("wisp %s must not appear by default", wisp.ID) + } + eph := bdProxiedReadyJSON(t, bd, p, "--include-ephemeral") + ids2 := map[string]bool{} + for _, r := range eph { + ids2[r.ID] = true + } + if !ids2[wisp.ID] { + t.Errorf("expected wisp %s under --include-ephemeral", wisp.ID) + } + }) + + t.Run("mol_type_validation_rejects_invalid", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rmtv") + out := bdProxiedReadyFail(t, bd, p, "--mol-type", "garbage") + if !strings.Contains(out, "invalid mol-type") { + t.Errorf("expected 'invalid mol-type' error, got: %s", out) + } + }) + + t.Run("claim_combo_guards", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rcc") + bdProxiedCreate(t, bd, p.dir, "Seed") + cases := []struct { + name string + args []string + }{ + {"claim_gated", []string{"--claim", "--gated"}}, + {"claim_mol", []string{"--claim", "--mol", "x"}}, + {"claim_explain", []string{"--claim", "--explain"}}, + {"claim_assignee", []string{"--claim", "--assignee", "alice"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + out := bdProxiedReadyFail(t, bd, p, c.args...) + if !strings.Contains(out, "--claim cannot be combined") { + t.Errorf("expected '--claim cannot be combined' error, got: %s", out) + } + }) + } + }) + + t.Run("exclude_type_csv_and_repeated", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rxt") + task := bdProxiedCreate(t, bd, p.dir, "Task work", "--type", "task") + bdProxiedCreate(t, bd, p.dir, "Bug work", "--type", "bug") + bdProxiedCreate(t, bd, p.dir, "Epic work", "--type", "epic") + + csv := bdProxiedReadyJSON(t, bd, p, "--exclude-type", "bug,epic") + csvIDs := map[string]bool{} + for _, r := range csv { + csvIDs[r.ID] = true + } + if !csvIDs[task.ID] { + t.Errorf("expected task %s in CSV result", task.ID) + } + for _, r := range csv { + if r.IssueType == types.TypeBug || r.IssueType == types.TypeEpic { + t.Errorf("excluded type %s leaked: %s", r.IssueType, r.ID) + } + } + + rep := bdProxiedReadyJSON(t, bd, p, "--exclude-type", "bug", "--exclude-type", "epic") + repIDs := map[string]bool{} + for _, r := range rep { + repIDs[r.ID] = true + } + if !repIDs[task.ID] { + t.Errorf("expected task %s in repeated-flag result", task.ID) + } + for _, r := range rep { + if r.IssueType == types.TypeBug || r.IssueType == types.TypeEpic { + t.Errorf("excluded type %s leaked under repeated flag: %s", r.IssueType, r.ID) + } + } + }) +} + +func TestProxiedServerReadyConcurrent(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + p := bdProxiedInit(t, bd, "rxc") + bdProxiedCreate(t, bd, p.dir, "Concurrent read target") + + const numWorkers = 8 + errs := make([]error, numWorkers) + var wg sync.WaitGroup + wg.Add(numWorkers) + for w := 0; w < numWorkers; w++ { + go func(worker int) { + defer wg.Done() + _, err := bdProxiedRun(t, bd, p.dir, "ready") + errs[worker] = err + }(w) + } + wg.Wait() + for i, err := range errs { + if err != nil { + t.Errorf("worker %d: %v", i, err) + } + } +} + +func TestProxiedServerReadyClaimConcurrent(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + p := bdProxiedInit(t, bd, "rcx") + issue := bdProxiedCreate(t, bd, p.dir, "Atomic claim target", "--label", "atomic") + + const numWorkers = 8 + type result struct { + stdout string + stderr string + err error + } + results := make([]result, numWorkers) + var wg sync.WaitGroup + wg.Add(numWorkers) + for w := 0; w < numWorkers; w++ { + go func(worker int) { + defer wg.Done() + cmd := bdProxiedClaimCmd(bd, p.dir, fmt.Sprintf("worker-%d@test", worker)) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err := cmd.Run() + results[worker] = result{stdout: stdout.String(), stderr: stderr.String(), err: err} + }(w) + } + wg.Wait() + + winners := 0 + for i, r := range results { + s := strings.TrimSpace(r.stdout) + start := strings.Index(s, "[") + if start < 0 { + continue + } + var claimed []types.IssueWithCounts + if err := json.Unmarshal([]byte(s[start:]), &claimed); err != nil { + t.Errorf("worker %d: parse JSON: %v\nstdout: %s\nstderr: %s", i, err, r.stdout, r.stderr) + continue + } + if len(claimed) > 1 { + t.Errorf("worker %d claimed multiple: %s", i, r.stdout) + continue + } + if len(claimed) == 1 { + winners++ + if claimed[0].ID != issue.ID { + t.Errorf("worker %d claimed %s, want %s", i, claimed[0].ID, issue.ID) + } + } + } + if winners != 1 { + for i, r := range results { + t.Logf("worker %d: err=%v\nstdout=%s\nstderr=%s", i, r.err, r.stdout, r.stderr) + } + t.Fatalf("expected exactly one winning claim, got %d", winners) + } + final := bdProxiedShow(t, bd, p.dir, issue.ID) + if final.Status != types.StatusInProgress { + t.Errorf("final Status = %s, want in_progress", final.Status) + } + if final.Assignee == "" { + t.Error("final Assignee empty") + } +} diff --git a/cmd/bd/ready_proxied_server.go b/cmd/bd/ready_proxied_server.go new file mode 100644 index 000000000..3643bb894 --- /dev/null +++ b/cmd/bd/ready_proxied_server.go @@ -0,0 +1,607 @@ +package main + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/debug" + "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" +) + +func runReadyProxiedServer(cmd *cobra.Command, ctx context.Context) { + in := gatherReadyInput(cmd) + + if uowProvider == nil { + FatalError("proxied-server UOW provider not initialized") + } + uw, err := uowProvider.NewUOW(ctx) + if err != nil { + FatalErrorRespectJSON("open unit of work: %v", err) + } + defer uw.Close(ctx) + + switch { + case in.gated: + runReadyProxiedGated(ctx, uw, in) + case in.molID != "": + runReadyProxiedMolecule(ctx, uw, in) + case in.explain: + runReadyProxiedExplain(ctx, uw, in) + case in.claim: + runReadyProxiedClaim(ctx, uw, in) + default: + runReadyProxiedList(ctx, uw, in) + } +} + +func runBlockedProxiedServer(cmd *cobra.Command, ctx context.Context) { + if uowProvider == nil { + FatalError("proxied-server UOW provider not initialized") + } + uw, err := uowProvider.NewUOW(ctx) + if err != nil { + FatalErrorRespectJSON("open unit of work: %v", err) + } + defer uw.Close(ctx) + + var filter types.WorkFilter + if parentID, _ := cmd.Flags().GetString("parent"); parentID != "" { + filter.ParentID = &parentID + } + + blocked, err := uw.IssueUseCase().GetBlockedIssues(ctx, filter) + if err != nil { + FatalErrorRespectJSON("%v", err) + } + + if jsonOutput { + if blocked == nil { + blocked = []*types.BlockedIssue{} + } + outputJSON(blocked) + return + } + if len(blocked) == 0 { + fmt.Printf("\n%s No blocked issues\n\n", ui.RenderPass("โœจ")) + return + } + fmt.Printf("\n%s Blocked issues (%d):\n\n", ui.RenderFail("๐Ÿšซ"), len(blocked)) + for _, issue := range blocked { + fmt.Printf("[%s] %s: %s\n", + ui.RenderPriority(issue.Priority), + ui.RenderID(issue.ID), issue.Title) + blockedBy := issue.BlockedBy + if blockedBy == nil { + blockedBy = []string{} + } + fmt.Printf(" Blocked by %d open dependencies: %v\n", + issue.BlockedByCount, blockedBy) + fmt.Println() + } +} + +func runReadyProxiedList(ctx context.Context, uw uow.UnitOfWork, in readyInput) { + if in.jsonOut { + page, err := uw.IssueUseCase().GetReadyWorkWithCounts(ctx, in.filter) + if err != nil { + FatalError("%v", err) + } + results := page.Items + totalReady := len(results) + truncated := false + if in.filter.Limit > 0 && len(results) == in.filter.Limit { + countFilter := in.filter + countFilter.Limit = 0 + all, countErr := uw.IssueUseCase().GetReadyWorkWithCounts(ctx, countFilter) + if countErr == nil && len(all.Items) > len(results) { + totalReady = len(all.Items) + truncated = true + } + } + if results == nil { + results = []*types.IssueWithCounts{} + } + outputJSON(results) + if truncated { + fmt.Fprintf(os.Stderr, "Showing %d of %d ready issues. Use --limit 0 for all, or --limit N to raise the cap.\n", len(results), totalReady) + } + return + } + + page, err := uw.IssueUseCase().GetReadyWork(ctx, in.filter) + if err != nil { + FatalError("%v", err) + } + issues := page.Items + + totalReady := len(issues) + truncated := false + if in.filter.Limit > 0 && len(issues) == in.filter.Limit { + countFilter := in.filter + countFilter.Limit = 0 + allPage, countErr := uw.IssueUseCase().GetReadyWork(ctx, countFilter) + if countErr == nil && len(allPage.Items) > len(issues) { + totalReady = len(allPage.Items) + truncated = true + } + } + + maybeShowUpgradeNotification() + + if len(issues) == 0 { + hasOpenIssues := false + if stats, statsErr := uw.IssueUseCase().GetStatistics(ctx); statsErr == nil { + hasOpenIssues = stats.OpenIssues > 0 || stats.InProgressIssues > 0 + } + if hasOpenIssues { + fmt.Printf("\n%s No ready work found (all issues have blocking dependencies)\n\n", + ui.RenderWarn("โœจ")) + } else { + fmt.Printf("\n%s No open issues\n\n", ui.RenderPass("โœจ")) + } + return + } + + parentEpicMap := buildParentEpicMapProxied(ctx, uw, issues) + usePlain := in.plainFormat || !in.prettyFormat + if usePlain { + fmt.Printf("\n%s Ready work (%d issues with no active blockers):\n\n", ui.RenderAccent("๐Ÿ“‹"), len(issues)) + for i, issue := range issues { + fmt.Printf("%d. [%s] [%s] %s: %s\n", i+1, + ui.RenderPriority(issue.Priority), + ui.RenderType(string(issue.IssueType)), + ui.RenderID(issue.ID), issue.Title) + if issue.EstimatedMinutes != nil { + fmt.Printf(" Estimate: %d min\n", *issue.EstimatedMinutes) + } + if issue.Assignee != "" { + fmt.Printf(" Assignee: %s\n", issue.Assignee) + } + } + fmt.Println() + } else { + displayReadyList(issues, parentEpicMap) + } + + if truncated { + fmt.Printf("%s\n\n", ui.RenderMuted(fmt.Sprintf("Showing %d of %d ready issues. Use -n to show more.", len(issues), totalReady))) + } +} + +func runReadyProxiedClaim(ctx context.Context, uw uow.UnitOfWork, in readyInput) { + CheckReadonly("ready --claim") + + res, err := uw.IssueUseCase().ClaimReadyIssue(ctx, in.filter, actor) + if err != nil { + FatalErrorRespectJSON("%v", err) + } + if !res.Claimed { + if in.jsonOut { + outputJSON([]*types.IssueWithCounts{}) + } else { + fmt.Printf("\n%s No ready work to claim\n\n", ui.RenderWarn("โ—‹")) + } + return + } + + var jsonPayload []*types.IssueWithCounts + if in.jsonOut { + jsonPayload = buildReadyIssueOutputProxied(ctx, uw, []*types.Issue{res.Issue}) + } + + if err := uw.Commit(ctx, fmt.Sprintf("bd: ready --claim %s", res.Issue.ID)); err != nil && !isDoltNothingToCommit(err) { + FatalErrorRespectJSON("failed to commit: %v", err) + } + SetLastTouchedID(res.Issue.ID) + + if in.jsonOut { + outputJSON(jsonPayload) + } else { + fmt.Printf("%s Claimed issue: %s\n", ui.RenderPass("โœ“"), formatFeedbackID(res.Issue.ID, res.Issue.Title)) + } +} + +func runReadyProxiedExplain(ctx context.Context, uw uow.UnitOfWork, _ readyInput) { + filter := types.WorkFilter{ + Status: types.StatusOpen, + SortPolicy: types.SortPolicyPriority, + } + readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, filter) + if err != nil { + FatalErrorRespectJSON("%v", err) + } + readyIssues := readyPage.Items + + blockedIssues, err := uw.IssueUseCase().GetBlockedIssues(ctx, types.WorkFilter{}) + if err != nil { + FatalErrorRespectJSON("%v", err) + } + + readyIDs := make([]string, len(readyIssues)) + for i, issue := range readyIssues { + readyIDs[i] = issue.ID + } + depCountsMap, err := uw.DependencyUseCase().CountsByIssueIDs(ctx, readyIDs) + if err != nil { + debug.Logf("warning: failed to get dependency counts: %v", err) + } + depCounts := make(map[string]*types.DependencyCounts, len(depCountsMap)) + for k, v := range depCountsMap { + depCounts[k] = v + } + allDeps, err := uw.DependencyUseCase().GetForIssueIDs(ctx, readyIDs) + if err != nil { + debug.Logf("warning: failed to get dependency records: %v", err) + } + + cycles, err := uw.DependencyUseCase().DetectCycles(ctx) + if err != nil { + debug.Logf("warning: failed to detect cycles: %v", err) + } + + allBlockerIDs := make(map[string]bool) + for _, bi := range blockedIssues { + for _, blockerID := range bi.BlockedBy { + allBlockerIDs[blockerID] = true + } + } + blockerIDList := make([]string, 0, len(allBlockerIDs)) + for id := range allBlockerIDs { + blockerIDList = append(blockerIDList, id) + } + blockerIssues, err := uw.IssueUseCase().GetIssuesByIDs(ctx, blockerIDList) + if err != nil { + debug.Logf("warning: failed to get blocker issues: %v", err) + } + blockerWisps, err := uw.IssueUseCase().GetWispsByIDs(ctx, blockerIDList) + if err != nil { + debug.Logf("warning: failed to get blocker wisps: %v", err) + } + blockerMap := make(map[string]*types.Issue, len(blockerIssues)+len(blockerWisps)) + for _, issue := range blockerIssues { + blockerMap[issue.ID] = issue + } + for _, wisp := range blockerWisps { + blockerMap[wisp.ID] = wisp + } + + explanation := types.BuildReadyExplanation(readyIssues, blockedIssues, depCounts, allDeps, blockerMap, cycles) + + if jsonOutput { + outputJSON(explanation) + return + } + + fmt.Printf("\n%s Ready Work Explanation\n\n", ui.RenderAccent("๐Ÿ“Š")) + if len(explanation.Ready) > 0 { + fmt.Printf("%s Ready (%d issues):\n\n", ui.RenderPass("โ—"), len(explanation.Ready)) + for _, item := range explanation.Ready { + fmt.Printf(" %s [%s] %s\n", + ui.RenderID(item.ID), + ui.RenderPriority(item.Priority), + item.Title) + fmt.Printf(" Reason: %s\n", item.Reason) + if len(item.ResolvedBlockers) > 0 { + fmt.Printf(" Resolved blockers: %s\n", strings.Join(item.ResolvedBlockers, ", ")) + } + if item.DependentCount > 0 { + fmt.Printf(" Unblocks: %d issue(s)\n", item.DependentCount) + } + fmt.Println() + } + } else { + fmt.Printf("%s No ready work\n\n", ui.RenderWarn("โ—‹")) + } + if len(explanation.Blocked) > 0 { + fmt.Printf("%s Blocked (%d issues):\n\n", ui.RenderFail("โ—"), len(explanation.Blocked)) + for _, item := range explanation.Blocked { + fmt.Printf(" %s [%s] %s\n", + ui.RenderID(item.ID), + ui.RenderPriority(item.Priority), + item.Title) + for _, blocker := range item.BlockedBy { + fmt.Printf(" โ† blocked by %s: %s [%s]\n", + ui.RenderID(blocker.ID), blocker.Title, blocker.Status) + } + fmt.Println() + } + } + if len(explanation.Cycles) > 0 { + fmt.Printf("%s Cycles detected (%d):\n\n", ui.RenderFail("โš "), len(explanation.Cycles)) + for _, cycle := range explanation.Cycles { + fmt.Printf(" %s โ†’ %s\n", strings.Join(cycle, " โ†’ "), cycle[0]) + } + fmt.Println() + } + fmt.Printf("%s Summary: %d ready, %d blocked", + ui.RenderMuted("โ”€"), + explanation.Summary.TotalReady, + explanation.Summary.TotalBlocked) + if explanation.Summary.CycleCount > 0 { + fmt.Printf(", %d cycle(s)", explanation.Summary.CycleCount) + } + fmt.Printf("\n\n") +} + +func runReadyProxiedMolecule(ctx context.Context, uw uow.UnitOfWork, in readyInput) { + moleculeID := in.molID + subgraph, err := proxiedLoadTemplateSubgraph(ctx, uw, moleculeID) + if err != nil { + FatalError("loading molecule: %v", err) + } + + analysis := analyzeMoleculeParallel(subgraph) + + var readySteps []*MoleculeReadyStep + for _, issue := range subgraph.Issues { + info := analysis.Steps[issue.ID] + if info != nil && info.IsReady { + readySteps = append(readySteps, &MoleculeReadyStep{ + Issue: issue, + ParallelInfo: info, + ParallelGroup: info.ParallelGroup, + }) + } + } + + if in.jsonOut { + output := MoleculeReadyOutput{ + MoleculeID: moleculeID, + MoleculeTitle: subgraph.Root.Title, + TotalSteps: analysis.TotalSteps, + ReadySteps: len(readySteps), + Steps: readySteps, + ParallelGroups: analysis.ParallelGroups, + } + outputJSON(output) + return + } + + fmt.Printf("\n%s Ready steps in molecule: %s\n", ui.RenderAccent("๐Ÿงช"), subgraph.Root.Title) + fmt.Printf(" ID: %s\n", moleculeID) + fmt.Printf(" Total: %d steps, %d ready\n", analysis.TotalSteps, len(readySteps)) + if len(readySteps) == 0 { + fmt.Printf("\n%s No ready steps (all blocked or completed)\n\n", ui.RenderWarn("โœจ")) + return + } + if len(analysis.ParallelGroups) > 0 { + fmt.Printf("\n%s Parallel Groups:\n", ui.RenderPass("โšก")) + for groupName, members := range analysis.ParallelGroups { + readyInGroup := 0 + for _, id := range members { + if info := analysis.Steps[id]; info != nil && info.IsReady { + readyInGroup++ + } + } + if readyInGroup > 0 { + fmt.Printf(" %s: %d ready\n", groupName, readyInGroup) + } + } + } + fmt.Printf("\n%s Ready steps:\n\n", ui.RenderPass("๐Ÿ“‹")) + for i, step := range readySteps { + groupAnnotation := "" + if step.ParallelGroup != "" { + groupAnnotation = fmt.Sprintf(" [%s]", ui.RenderAccent(step.ParallelGroup)) + } + fmt.Printf("%d. [%s] [%s] %s: %s%s\n", i+1, + ui.RenderPriority(step.Issue.Priority), + ui.RenderType(string(step.Issue.IssueType)), + ui.RenderID(step.Issue.ID), + step.Issue.Title, + groupAnnotation) + if len(step.ParallelInfo.CanParallel) > 0 { + readyParallel := []string{} + for _, pID := range step.ParallelInfo.CanParallel { + if pInfo := analysis.Steps[pID]; pInfo != nil && pInfo.IsReady { + readyParallel = append(readyParallel, pID) + } + } + if len(readyParallel) > 0 { + fmt.Printf(" Can run with: %v\n", readyParallel) + } + } + } + fmt.Println() +} + +func runReadyProxiedGated(ctx context.Context, uw uow.UnitOfWork, _ readyInput) { + gateType := types.IssueType("gate") + closedStatus := types.StatusClosed + gatePage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{ + IssueType: &gateType, + Status: &closedStatus, + }) + if err != nil { + FatalErrorRespectJSON("error searching for closed gates: %v", err) + } + if len(gatePage.Items) == 0 { + emitGatedEmpty() + return + } + + readyPage, err := uw.IssueUseCase().GetReadyWork(ctx, types.WorkFilter{}) + if err != nil { + FatalErrorRespectJSON("error getting ready work: %v", err) + } + readySet := make(map[string]*types.Issue, len(readyPage.Items)) + for _, issue := range readyPage.Items { + readySet[issue.ID] = issue + } + + hookedStatus := types.StatusHooked + hookedPage, err := uw.IssueUseCase().SearchIssues(ctx, "", types.IssueFilter{Status: &hookedStatus}) + if err != nil { + FatalErrorRespectJSON("error searching for hooked issues: %v", err) + } + hookedSet := make(map[string]*types.Issue, len(hookedPage.Items)) + for _, issue := range hookedPage.Items { + hookedSet[issue.ID] = issue + } + + moleculeMap := make(map[string]*GatedMolecule) + for _, gate := range gatePage.Items { + dependents, err := uw.DependencyUseCase().ListWithIssueMetadata(ctx, gate.ID, domain.DepListFilter{ + Direction: domain.DepDirectionIn, + }) + if err != nil { + continue + } + for _, dep := range dependents { + depIssue := dep.Issue + ready, isReady := readySet[depIssue.ID] + hooked, isHooked := hookedSet[depIssue.ID] + if !isReady && !isHooked { + continue + } + var step *types.Issue + if isReady { + step = ready + } else { + step = hooked + } + moleculeID := proxiedFindParentMolecule(ctx, uw, depIssue.ID) + if moleculeID == "" { + continue + } + if _, seen := moleculeMap[moleculeID]; seen { + continue + } + moleculeIssue, err := uw.IssueUseCase().GetIssue(ctx, moleculeID) + if err != nil || moleculeIssue == nil { + continue + } + moleculeMap[moleculeID] = &GatedMolecule{ + MoleculeID: moleculeID, + MoleculeTitle: moleculeIssue.Title, + ClosedGate: gate, + ReadyStep: step, + } + } + } + + molecules := make([]*GatedMolecule, 0, len(moleculeMap)) + for _, m := range moleculeMap { + molecules = append(molecules, m) + } + + if jsonOutput { + output := GatedReadyOutput{Molecules: molecules, Count: len(molecules)} + if output.Molecules == nil { + output.Molecules = []*GatedMolecule{} + } + outputJSON(output) + return + } + if len(molecules) == 0 { + fmt.Printf("\n%s No molecules ready for gate-resume dispatch\n\n", ui.RenderPass("โœจ")) + return + } + fmt.Printf("\n%s Molecules ready for gate-resume dispatch (%d):\n\n", ui.RenderAccent("๐Ÿšช"), len(molecules)) + for _, m := range molecules { + fmt.Printf(" %s: %s\n", ui.RenderID(m.MoleculeID), m.MoleculeTitle) + fmt.Printf(" Closed gate: %s (%s)\n", ui.RenderID(m.ClosedGate.ID), m.ClosedGate.Title) + fmt.Printf(" Ready step: %s (%s)\n", ui.RenderID(m.ReadyStep.ID), m.ReadyStep.Title) + fmt.Println() + } +} + +func emitGatedEmpty() { + if jsonOutput { + outputJSON(GatedReadyOutput{Molecules: []*GatedMolecule{}}) + return + } + fmt.Printf("\n%s No closed gates found โ€” nothing to dispatch\n\n", ui.RenderPass("โœจ")) +} + +func buildReadyIssueOutputProxied(ctx context.Context, uw uow.UnitOfWork, issues []*types.Issue) []*types.IssueWithCounts { + if issues == nil { + issues = []*types.Issue{} + } + ids := make([]string, len(issues)) + for i, issue := range issues { + ids[i] = issue.ID + } + + depCounts, _ := uw.DependencyUseCase().CountsByIssueIDs(ctx, ids) + allDeps, _ := uw.DependencyUseCase().GetForIssueIDs(ctx, ids) + commentCounts, _ := uw.CommentUseCase().GetCommentCounts(ctx, ids) + + for _, issue := range issues { + issue.Dependencies = allDeps[issue.ID] + } + + out := make([]*types.IssueWithCounts, len(issues)) + for i, issue := range issues { + counts := depCounts[issue.ID] + if counts == nil { + counts = &types.DependencyCounts{} + } + var parent *string + for _, dep := range allDeps[issue.ID] { + if dep.Type == types.DepParentChild { + parent = &dep.DependsOnID + break + } + } + out[i] = &types.IssueWithCounts{ + Issue: issue, + DependencyCount: counts.DependencyCount, + DependentCount: counts.DependentCount, + CommentCount: commentCounts[issue.ID], + Parent: parent, + } + } + return out +} + +func buildParentEpicMapProxied(ctx context.Context, uw uow.UnitOfWork, issues []*types.Issue) map[string]string { + if len(issues) == 0 { + return nil + } + ids := make([]string, len(issues)) + for i, issue := range issues { + ids[i] = issue.ID + } + allDeps, err := uw.DependencyUseCase().GetForIssueIDs(ctx, ids) + if err != nil { + return nil + } + parentIDs := make(map[string]bool) + childToParent := make(map[string]string) + for issueID, deps := range allDeps { + for _, dep := range deps { + if dep.Type == types.DepParentChild { + parentIDs[dep.DependsOnID] = true + childToParent[issueID] = dep.DependsOnID + } + } + } + if len(parentIDs) == 0 { + return nil + } + epicTitles := make(map[string]string) + for parentID := range parentIDs { + parent, err := uw.IssueUseCase().GetIssue(ctx, parentID) + if err != nil || parent == nil { + continue + } + if parent.IssueType == "epic" { + epicTitles[parentID] = parent.Title + } + } + result := make(map[string]string) + for childID, parentID := range childToParent { + if title, ok := epicTitles[parentID]; ok { + result[childID] = title + } + } + return result +} diff --git a/cmd/bd/ready_wisp_proxied_integration_test.go b/cmd/bd/ready_wisp_proxied_integration_test.go new file mode 100644 index 000000000..af47b4867 --- /dev/null +++ b/cmd/bd/ready_wisp_proxied_integration_test.go @@ -0,0 +1,363 @@ +//go:build cgo + +package main + +import ( + "bytes" + "context" + "encoding/json" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/storage/depid" + "github.com/steveyegge/beads/internal/types" +) + +func TestProxiedServerReadyWisp(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("claim_include_ephemeral_claims_wisp", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwc") + wisp := bdProxiedCreate(t, bd, p.dir, "Wisp to claim", "--ephemeral", "--label", "wclaim") + + out, err := bdProxiedRun(t, bd, p.dir, + "ready", "--claim", "--json", "--include-ephemeral", "--label", "wclaim") + if err != nil { + t.Fatalf("bd ready --claim --include-ephemeral failed: %v\n%s", err, out) + } + var claimed []types.IssueWithCounts + if err := json.Unmarshal(bytes.TrimSpace(out), &claimed); err != nil { + t.Fatalf("parse claim JSON: %v\n%s", err, out) + } + if len(claimed) != 1 { + t.Fatalf("expected one claimed wisp, got %d: %s", len(claimed), out) + } + if claimed[0].ID != wisp.ID { + t.Fatalf("claimed ID = %s, want %s", claimed[0].ID, wisp.ID) + } + if claimed[0].Status != types.StatusInProgress { + t.Errorf("Status = %s, want %s", claimed[0].Status, types.StatusInProgress) + } + if claimed[0].Assignee == "" { + t.Error("Assignee should be set after claim") + } + + db := openProxiedDB(t, p) + var status, assignee string + if err := db.QueryRowContext(context.Background(), + "SELECT status, assignee FROM wisps WHERE id = ?", wisp.ID).Scan(&status, &assignee); err != nil { + t.Fatalf("re-fetch wisp from wisps table: %v", err) + } + if status != string(types.StatusInProgress) { + t.Errorf("persisted wisp status = %s, want in_progress", status) + } + if assignee == "" { + t.Error("persisted wisp assignee empty") + } + }) + + t.Run("mol_on_wisp_molecule_currently_errors", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwm") + mol := bdProxiedCreate(t, bd, p.dir, "Wisp mol", "--ephemeral", "--type", "molecule") + bdProxiedCreate(t, bd, p.dir, "Wisp step", "--ephemeral", "--parent", mol.ID) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--mol", mol.ID, "--json") + if err == nil { + t.Skipf("--mol on wisp molecule succeeded โ€” implementation may now support this. stdout: %s", stdout) + } + combined := stdout + stderr + if !strings.Contains(combined, "not found") && !strings.Contains(combined, "loading molecule") { + t.Errorf("expected 'not found'/'loading molecule' error for wisp mol, got stdout:%s stderr:%s", stdout, stderr) + } + }) + + t.Run("wisp_blocked_by_wisp_hidden_and_listed_in_blocked", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwwb") + blocker := bdProxiedCreate(t, bd, p.dir, "Wisp blocker", "--ephemeral") + dependent := bdProxiedCreate(t, bd, p.dir, "Wisp dependent", "--ephemeral") + + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')", + dependent.ID, blocker.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant wisp blocks wisp edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "UPDATE wisps SET is_blocked = 1 WHERE id = ?", dependent.ID); err != nil { + t.Fatalf("mark wisp is_blocked: %v", err) + } + + ready := bdProxiedReadyJSON(t, bd, p, "--include-ephemeral") + ids := map[string]bool{} + for _, r := range ready { + ids[r.ID] = true + } + if !ids[blocker.ID] { + t.Errorf("expected blocker wisp %s to be ready", blocker.ID) + } + if ids[dependent.ID] { + t.Errorf("blocked wisp %s must not appear in ready --include-ephemeral", dependent.ID) + } + + blocked := bdProxiedBlockedJSON(t, bd, p) + blockedIDs := map[string]bool{} + for _, bi := range blocked { + blockedIDs[bi.ID] = true + } + if !blockedIDs[dependent.ID] { + t.Errorf("expected wisp %s in bd blocked output, got: %+v", dependent.ID, blockedIDs) + } + }) + + t.Run("cross_table_issue_blocked_by_wisp", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwci") + wispBlocker := bdProxiedCreate(t, bd, p.dir, "Wisp blocker for issue", "--ephemeral") + issue := bdProxiedCreate(t, bd, p.dir, "Issue blocked by wisp") + + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (?, ?, ?, ?, NOW(), 'test')", + depid.New(issue.ID, wispBlocker.ID), issue.ID, wispBlocker.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant issue->wisp blocks edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "UPDATE issues SET is_blocked = 1 WHERE id = ?", issue.ID); err != nil { + t.Fatalf("mark issue is_blocked: %v", err) + } + + ready := bdProxiedReadyJSON(t, bd, p) + for _, r := range ready { + if r.ID == issue.ID { + t.Errorf("issue %s should be hidden (blocked by wisp)", issue.ID) + } + } + + blocked := bdProxiedBlockedJSON(t, bd, p) + var entry *types.BlockedIssue + for _, bi := range blocked { + if bi.ID == issue.ID { + entry = bi + break + } + } + if entry == nil { + t.Fatalf("expected issue %s in bd blocked output", issue.ID) + } + foundBlocker := false + for _, b := range entry.BlockedBy { + if b == wispBlocker.ID { + foundBlocker = true + break + } + } + if !foundBlocker { + t.Errorf("expected wisp blocker %s in BlockedBy, got: %v", wispBlocker.ID, entry.BlockedBy) + } + }) + + t.Run("cross_table_wisp_blocked_by_issue", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwcw") + issueBlocker := bdProxiedCreate(t, bd, p.dir, "Issue blocker for wisp") + wisp := bdProxiedCreate(t, bd, p.dir, "Wisp blocked by issue", "--ephemeral") + + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')", + wisp.ID, issueBlocker.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant wisp->issue blocks edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "UPDATE wisps SET is_blocked = 1 WHERE id = ?", wisp.ID); err != nil { + t.Fatalf("mark wisp is_blocked: %v", err) + } + + ready := bdProxiedReadyJSON(t, bd, p, "--include-ephemeral") + for _, r := range ready { + if r.ID == wisp.ID { + t.Errorf("wisp %s should be hidden (blocked by issue)", wisp.ID) + } + } + + blocked := bdProxiedBlockedJSON(t, bd, p) + var entry *types.BlockedIssue + for _, bi := range blocked { + if bi.ID == wisp.ID { + entry = bi + break + } + } + if entry == nil { + t.Fatalf("expected wisp %s in bd blocked output", wisp.ID) + } + foundBlocker := false + for _, b := range entry.BlockedBy { + if b == issueBlocker.ID { + foundBlocker = true + break + } + } + if !foundBlocker { + t.Errorf("expected issue blocker %s in BlockedBy, got: %v", issueBlocker.ID, entry.BlockedBy) + } + }) + + t.Run("blocked_lists_blocked_wisp", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwbl") + blocker := bdProxiedCreate(t, bd, p.dir, "Blocker wisp", "--ephemeral") + dependent := bdProxiedCreate(t, bd, p.dir, "Dependent wisp", "--ephemeral") + + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')", + dependent.ID, blocker.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant wisp blocks wisp edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "UPDATE wisps SET is_blocked = 1 WHERE id = ?", dependent.ID); err != nil { + t.Fatalf("mark wisp is_blocked: %v", err) + } + + blocked := bdProxiedBlockedJSON(t, bd, p) + var entry *types.BlockedIssue + for _, bi := range blocked { + if bi.ID == dependent.ID { + entry = bi + break + } + } + if entry == nil { + t.Fatalf("expected wisp %s in bd blocked output", dependent.ID) + } + if entry.BlockedByCount != 1 || len(entry.BlockedBy) != 1 || entry.BlockedBy[0] != blocker.ID { + t.Errorf("BlockedBy = %v (count=%d), want [%s]", entry.BlockedBy, entry.BlockedByCount, blocker.ID) + } + }) + + t.Run("explain_enriches_wisp_blocker_details", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwexb") + wispBlocker := bdProxiedCreate(t, bd, p.dir, + "Wisp blocker title", "--ephemeral", "-p", "1") + issue := bdProxiedCreate(t, bd, p.dir, "Blocked issue") + + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (?, ?, ?, ?, NOW(), 'test')", + depid.New(issue.ID, wispBlocker.ID), issue.ID, wispBlocker.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant issue->wisp blocks edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "UPDATE issues SET is_blocked = 1 WHERE id = ?", issue.ID); err != nil { + t.Fatalf("mark issue is_blocked: %v", err) + } + + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--explain", "--json") + if err != nil { + t.Fatalf("bd ready --explain --json failed: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "{") + if start < 0 { + t.Fatalf("no JSON in --explain output: %s", stdout) + } + var exp types.ReadyExplanation + if err := json.Unmarshal([]byte(s[start:]), &exp); err != nil { + t.Fatalf("parse ReadyExplanation: %v\n%s", err, s[start:]) + } + + var blockedItem *types.BlockedItem + for i := range exp.Blocked { + if exp.Blocked[i].ID == issue.ID { + blockedItem = &exp.Blocked[i] + break + } + } + if blockedItem == nil { + t.Fatalf("blocked issue %s not in explain output: %+v", issue.ID, exp.Blocked) + } + + var blocker *types.BlockerInfo + for i := range blockedItem.BlockedBy { + if blockedItem.BlockedBy[i].ID == wispBlocker.ID { + blocker = &blockedItem.BlockedBy[i] + break + } + } + if blocker == nil { + t.Fatalf("wisp blocker %s not in BlockedBy: %+v", wispBlocker.ID, blockedItem.BlockedBy) + } + if blocker.Title != "Wisp blocker title" { + t.Errorf("wisp blocker Title = %q, want %q (GetIssuesByIDs doesn't read wisps)", + blocker.Title, "Wisp blocker title") + } + if blocker.Status != types.StatusOpen { + t.Errorf("wisp blocker Status = %q, want %q", blocker.Status, types.StatusOpen) + } + if blocker.Priority != 1 { + t.Errorf("wisp blocker Priority = %d, want 1", blocker.Priority) + } + }) + + t.Run("explain_detects_cycle_in_wisp_dependencies", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwcy") + a := bdProxiedCreate(t, bd, p.dir, "Wisp cycle A", "--ephemeral") + b := bdProxiedCreate(t, bd, p.dir, "Wisp cycle B", "--ephemeral") + + db := openProxiedDB(t, p) + ctx := context.Background() + if _, err := db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')", + a.ID, b.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant a->b wisp edge: %v", err) + } + if _, err := db.ExecContext(ctx, + "INSERT INTO wisp_dependencies (id, issue_id, depends_on_wisp_id, type, created_at, created_by) VALUES (UUID(), ?, ?, ?, NOW(), 'test')", + b.ID, a.ID, string(types.DepBlocks)); err != nil { + t.Fatalf("plant b->a wisp edge: %v", err) + } + + stdout, _, err := bdProxiedRunBuffers(t, bd, p.dir, "ready", "--explain", "--json") + if err != nil { + t.Fatalf("bd ready --explain --json failed: %v\n%s", err, stdout) + } + s := strings.TrimSpace(stdout) + start := strings.Index(s, "{") + if start < 0 { + t.Fatalf("no JSON in --explain output: %s", stdout) + } + var exp types.ReadyExplanation + if err := json.Unmarshal([]byte(s[start:]), &exp); err != nil { + t.Fatalf("parse ReadyExplanation: %v\n%s", err, s[start:]) + } + if len(exp.Cycles) == 0 { + t.Fatalf("expected non-empty Cycles for wisp_dependencies cycle, got: %+v", exp) + } + found := false + for _, cycle := range exp.Cycles { + cycleSet := map[string]bool{} + for _, id := range cycle { + cycleSet[id] = true + } + if cycleSet[a.ID] && cycleSet[b.ID] { + found = true + break + } + } + if !found { + t.Errorf("expected cycle containing %s and %s, got: %+v", a.ID, b.ID, exp.Cycles) + } + }) + + t.Run("empty_state_hint_when_only_wisps_exist", func(t *testing.T) { + p := bdProxiedInit(t, bd, "rwes") + bdProxiedCreate(t, bd, p.dir, "Lonely wisp", "--ephemeral") + stdout, _ := bdProxiedReadyCapture(t, bd, p) + if !strings.Contains(stdout, "No open issues") { + t.Errorf("expected 'No open issues' (stats ignores wisps), got: %s", stdout) + } + }) +} diff --git a/internal/storage/domain/db/dependency.go b/internal/storage/domain/db/dependency.go index 736e4d61e..47bb52fbe 100644 --- a/internal/storage/domain/db/dependency.go +++ b/internal/storage/domain/db/dependency.go @@ -758,3 +758,11 @@ func (r *dependencySQLRepositoryImpl) IsBlocked(ctx context.Context, issueID str } return blocked, blockers, nil } + +func (r *dependencySQLRepositoryImpl) DetectCycles(ctx context.Context) ([][]*types.Issue, error) { + out, err := issueops.DetectCyclesInTx(ctx, r.runner) + if err != nil { + return nil, fmt.Errorf("db: DependencySQLRepository.DetectCycles: %w", err) + } + return out, nil +} diff --git a/internal/storage/domain/db/issue.go b/internal/storage/domain/db/issue.go index 10360c403..ddc58980f 100644 --- a/internal/storage/domain/db/issue.go +++ b/internal/storage/domain/db/issue.go @@ -744,4 +744,48 @@ func (r *issueSQLRepositoryImpl) GetNewlyUnblockedByClose(ctx context.Context, c return out, nil } +func (r *issueSQLRepositoryImpl) ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) { + out, err := issueops.ClaimReadyIssueInTx(ctx, r.runner, filter, actor) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.ClaimReadyIssue: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) ClaimReadyWisp(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) { + out, err := issueops.ClaimReadyIssueInTx(ctx, r.runner, filter, actor) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.ClaimReadyWisp: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) { + out, err := issueops.GetBlockedIssuesInTx(ctx, r.runner, filter) + if err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.GetBlockedIssues: %w", err) + } + return out, nil +} + +func (r *issueSQLRepositoryImpl) GetStatistics(ctx context.Context) (*types.Statistics, error) { + stats := &types.Statistics{} + if err := issueops.ScanIssueCountsInTx(ctx, r.runner, stats); err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.GetStatistics: scan counts: %w", err) + } + var blocked int + if err := r.runner.QueryRowContext(ctx, ` + SELECT COUNT(*) FROM issues + WHERE is_blocked = 1 AND status <> 'closed' AND status <> 'pinned' + `).Scan(&blocked); err != nil { + return nil, fmt.Errorf("db: IssueSQLRepository.GetStatistics: count blocked: %w", err) + } + stats.BlockedIssues = blocked + stats.ReadyIssues = stats.OpenIssues - blocked + if stats.ReadyIssues < 0 { + stats.ReadyIssues = 0 + } + return stats, nil +} + const deleteBatchSize = 200 diff --git a/internal/storage/domain/db/ready_helpers_test.go b/internal/storage/domain/db/ready_helpers_test.go new file mode 100644 index 000000000..ed4d4bf94 --- /dev/null +++ b/internal/storage/domain/db/ready_helpers_test.go @@ -0,0 +1,546 @@ +package db + +import ( + "context" + "sort" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func (s *testSuite) resetDB() { + ctx := context.Background() + _, err := s.db.ExecContext(ctx, "CALL DOLT_RESET('--hard', ?)", s.baselineCommit) + s.Require().NoError(err) + for _, table := range []string{"wisp_dependencies", "wisp_labels", "wisp_events", "wisp_child_counters", "wisp_comments", "wisps"} { + if _, err := s.db.ExecContext(ctx, "DELETE FROM "+table); err != nil { + s.T().Logf("clear %s: %v", table, err) + } + } +} + +func (s *testSuite) TestIssueClaimReadyIssue() { + s.Run("ClaimsFirstReady", s.claimReadyClaimsFirst) + s.Run("MarksInProgressAndAssigns", s.claimReadySetsState) + s.Run("NoReadyReturnsNil", s.claimReadyEmpty) + s.Run("SkipsAlreadyClaimedByOther", s.claimReadySkipsForeign) + s.Run("RespectsPriorityFilter", s.claimReadyPriorityFilter) + s.Run("ExcludesBlocked", s.claimReadyExcludesBlocked) +} + +func (s *testSuite) TestIssueClaimReadyWisp() { + s.Run("ClaimsFirstReady", s.claimReadyWispClaimsFirst) + s.Run("NoReadyReturnsNil", s.claimReadyWispEmpty) +} + +func (s *testSuite) TestIssueGetBlockedIssues() { + s.Run("EmptyDBReturnsNil", s.blockedEmpty) + s.Run("ReturnsBlockedWithBlockers", s.blockedReturnsBlockers) + s.Run("ExcludesClosed", s.blockedExcludesClosed) + s.Run("UnblocksWhenBlockerCloses", s.blockedUnblocksOnClose) + s.Run("MultipleBlockersAggregated", s.blockedMultipleAggregated) + s.Run("InheritedThroughParentChild", s.blockedInheritedThroughParent) + s.Run("ParentIDFilterRestrictsToDescendants", s.blockedParentIDFilter) +} + +func (s *testSuite) TestIssueGetStatistics() { + s.Run("EmptyDBReturnsZeroes", s.statsEmpty) + s.Run("CountsByStatus", s.statsCountsByStatus) + s.Run("CountsBlocked", s.statsCountsBlocked) + s.Run("CountsPinned", s.statsCountsPinned) + s.Run("ReadyDerivedFromOpenMinusBlocked", s.statsReadyDerived) + s.Run("ReadyClampedAtZero", s.statsReadyClamped) +} + +func (s *testSuite) TestDependencyDetectCycles() { + s.Run("NoEdgesReturnsEmpty", s.cyclesEmpty) + s.Run("AcyclicReturnsEmpty", s.cyclesAcyclic) + s.Run("TwoNodeCycleDetected", s.cyclesTwoNode) + s.Run("ThreeNodeCycleDetected", s.cyclesThreeNode) + s.Run("IgnoresNonBlockingDepTypes", s.cyclesIgnoresParentChild) + s.Run("ConditionalBlocksFormsCycle", s.cyclesConditionalBlocks) +} + +// ---------- ClaimReadyIssue ---------- + +func (s *testSuite) claimReadyClaimsFirst() { + r := s.issueRepo() + a := newTestIssue("bd-clr-a", "alpha") + a.Priority = 1 + s.Require().NoError(r.Insert(s.Ctx(), a, "tester", domain.InsertIssueOpts{})) + b := newTestIssue("bd-clr-b", "bravo") + b.Priority = 2 + s.Require().NoError(r.Insert(s.Ctx(), b, "tester", domain.InsertIssueOpts{})) + + out, err := r.ClaimReadyIssue(s.Ctx(), types.WorkFilter{SortPolicy: types.SortPolicyPriority}, "alice") + s.Require().NoError(err) + s.Require().NotNil(out) + s.Equal("bd-clr-a", out.ID, "first ready by priority should be claimed") +} + +func (s *testSuite) claimReadySetsState() { + s.resetDB() + r := s.issueRepo() + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-clr-state", "x"), "tester", domain.InsertIssueOpts{})) + + out, err := r.ClaimReadyIssue(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.Require().NotNil(out) + s.Equal("bd-clr-state", out.ID) + + got, err := r.Get(s.Ctx(), "bd-clr-state", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Equal(types.StatusInProgress, got.Status) + s.Equal("alice", got.Assignee) + s.NotNil(got.StartedAt, "started_at must be set on first claim") +} + +func (s *testSuite) claimReadyEmpty() { + s.resetDB() + r := s.issueRepo() + out, err := r.ClaimReadyIssue(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.Nil(out) +} + +func (s *testSuite) claimReadySkipsForeign() { + r := s.issueRepo() + taken := newTestIssue("bd-clr-skip-taken", "taken") + taken.Status = types.StatusInProgress + taken.Assignee = "bob" + s.Require().NoError(r.Insert(s.Ctx(), taken, "tester", domain.InsertIssueOpts{})) + free := newTestIssue("bd-clr-skip-free", "free") + free.Priority = 2 + s.Require().NoError(r.Insert(s.Ctx(), free, "tester", domain.InsertIssueOpts{})) + + out, err := r.ClaimReadyIssue(s.Ctx(), types.WorkFilter{SortPolicy: types.SortPolicyPriority}, "alice") + s.Require().NoError(err) + s.Require().NotNil(out) + s.Equal("bd-clr-skip-free", out.ID, "must pass over in-progress issue owned by another actor") +} + +func (s *testSuite) claimReadyPriorityFilter() { + r := s.issueRepo() + low := newTestIssue("bd-clr-pri-low", "low") + low.Priority = 3 + s.Require().NoError(r.Insert(s.Ctx(), low, "tester", domain.InsertIssueOpts{})) + high := newTestIssue("bd-clr-pri-high", "high") + high.Priority = 1 + s.Require().NoError(r.Insert(s.Ctx(), high, "tester", domain.InsertIssueOpts{})) + + p := 1 + out, err := r.ClaimReadyIssue(s.Ctx(), types.WorkFilter{Priority: &p}, "alice") + s.Require().NoError(err) + s.Require().NotNil(out) + s.Equal("bd-clr-pri-high", out.ID) +} + +func (s *testSuite) claimReadyExcludesBlocked() { + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-clr-blk-src", "blocked-src") + src.Priority = 1 + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + tgt := newTestIssue("bd-clr-blk-tgt", "blocker") + tgt.Priority = 2 + s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-clr-blk-src", "bd-clr-blk-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := r.ClaimReadyIssue(s.Ctx(), types.WorkFilter{SortPolicy: types.SortPolicyPriority}, "alice") + s.Require().NoError(err) + s.Require().NotNil(out) + s.Equal("bd-clr-blk-tgt", out.ID, "blocked issue must be skipped even if higher priority") +} + +// ---------- ClaimReadyWisp ---------- +// ClaimReadyWisp currently delegates to ClaimReadyIssueInTx (which already spans +// issues + wisps via GetReadyWorkInTx). These smoke tests guard the delegation. + +func (s *testSuite) claimReadyWispClaimsFirst() { + r := s.issueRepo() + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-clrw-a", "alpha"), "tester", domain.InsertIssueOpts{})) + out, err := r.ClaimReadyWisp(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.Require().NotNil(out) + s.Equal("bd-clrw-a", out.ID) +} + +func (s *testSuite) claimReadyWispEmpty() { + r := s.issueRepo() + out, err := r.ClaimReadyWisp(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.Nil(out) +} + +// ---------- GetBlockedIssues ---------- + +func (s *testSuite) blockedEmpty() { + r := s.issueRepo() + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + s.Empty(out) +} + +func (s *testSuite) blockedReturnsBlockers() { + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-bli-src", "blocked") + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + tgt := newTestIssue("bd-bli-tgt", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-bli-src", "bd-bli-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + s.Require().Len(out, 1) + s.Equal("bd-bli-src", out[0].ID) + s.Equal(1, out[0].BlockedByCount) + s.Equal([]string{"bd-bli-tgt"}, out[0].BlockedBy) +} + +func (s *testSuite) blockedExcludesClosed() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-blc-src", "closed-blocked") + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + tgt := newTestIssue("bd-blc-tgt", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blc-src", "bd-blc-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(r.Update(s.Ctx(), "bd-blc-src", + map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + s.NotContains(blockedIDs(out), "bd-blc-src", + "closed issues must never appear in blocked listing") +} + +func (s *testSuite) blockedUnblocksOnClose() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-bluc-src", "blocked") + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + tgt := newTestIssue("bd-bluc-tgt", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-bluc-src", "bd-bluc-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + s.Require().NoError(r.Update(s.Ctx(), "bd-bluc-tgt", + map[string]any{"status": string(types.StatusClosed)}, "tester", domain.IssueTableOpts{})) + + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + s.NotContains(blockedIDs(out), "bd-bluc-src", + "closing the blocker must clear the blocked listing") +} + +func (s *testSuite) blockedMultipleAggregated() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-blm-src", "double-blocked") + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + a := newTestIssue("bd-blm-a", "blocker-a") + s.Require().NoError(r.Insert(s.Ctx(), a, "tester", domain.InsertIssueOpts{})) + b := newTestIssue("bd-blm-b", "blocker-b") + s.Require().NoError(r.Insert(s.Ctx(), b, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blm-src", "bd-blm-a", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blm-src", "bd-blm-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + var entry *types.BlockedIssue + for _, bi := range out { + if bi.ID == "bd-blm-src" { + entry = bi + break + } + } + s.Require().NotNil(entry) + s.Equal(2, entry.BlockedByCount) + got := append([]string(nil), entry.BlockedBy...) + sort.Strings(got) + s.Equal([]string{"bd-blm-a", "bd-blm-b"}, got) +} + +func (s *testSuite) blockedInheritedThroughParent() { + r := s.issueRepo() + dr := s.depRepo() + parent := newTestIssue("bd-blp-parent", "parent") + s.Require().NoError(r.Insert(s.Ctx(), parent, "tester", domain.InsertIssueOpts{})) + child := newTestIssue("bd-blp-child", "child") + s.Require().NoError(r.Insert(s.Ctx(), child, "tester", domain.InsertIssueOpts{})) + blocker := newTestIssue("bd-blp-blocker", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), blocker, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blp-parent", "bd-blp-blocker", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blp-child", "bd-blp-parent", types.DepParentChild), "tester", domain.DepInsertOpts{})) + + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + gotIDs := blockedIDs(out) + s.Contains(gotIDs, "bd-blp-parent") + s.Contains(gotIDs, "bd-blp-child", "child inherits its blocked state from its parent") + + for _, bi := range out { + if bi.ID == "bd-blp-child" { + s.Equal([]string{"bd-blp-parent"}, bi.BlockedBy, + "inherited blocker should be the parent itself") + } + } +} + +func (s *testSuite) blockedParentIDFilter() { + r := s.issueRepo() + dr := s.depRepo() + parent := newTestIssue("bd-blf-parent", "parent") + s.Require().NoError(r.Insert(s.Ctx(), parent, "tester", domain.InsertIssueOpts{})) + insideChild := newTestIssue("bd-blf-parent.1", "inside") + s.Require().NoError(r.Insert(s.Ctx(), insideChild, "tester", domain.InsertIssueOpts{})) + outside := newTestIssue("bd-blf-out", "outside") + s.Require().NoError(r.Insert(s.Ctx(), outside, "tester", domain.InsertIssueOpts{})) + blocker := newTestIssue("bd-blf-blocker", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), blocker, "tester", domain.InsertIssueOpts{})) + + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blf-parent.1", "bd-blf-parent", types.DepParentChild), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blf-parent.1", "bd-blf-blocker", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-blf-out", "bd-blf-blocker", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + pid := "bd-blf-parent" + out, err := r.GetBlockedIssues(s.Ctx(), types.WorkFilter{ParentID: &pid}) + s.Require().NoError(err) + gotIDs := blockedIDs(out) + s.Contains(gotIDs, "bd-blf-parent.1") + s.NotContains(gotIDs, "bd-blf-out", "ParentID filter must restrict to descendants") +} + +// ---------- GetStatistics ---------- + +func (s *testSuite) statsEmpty() { + s.resetDB() + r := s.issueRepo() + out, err := r.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(0, out.TotalIssues) + s.Equal(0, out.OpenIssues) + s.Equal(0, out.InProgressIssues) + s.Equal(0, out.ClosedIssues) + s.Equal(0, out.BlockedIssues) + s.Equal(0, out.DeferredIssues) + s.Equal(0, out.PinnedIssues) + s.Equal(0, out.ReadyIssues) +} + +func (s *testSuite) statsCountsByStatus() { + s.resetDB() + r := s.issueRepo() + mk := func(id string, status types.Status) { + iss := newTestIssue(id, string(status)) + iss.Status = status + s.Require().NoError(r.Insert(s.Ctx(), iss, "tester", domain.InsertIssueOpts{})) + } + mk("bd-st-o1", types.StatusOpen) + mk("bd-st-o2", types.StatusOpen) + mk("bd-st-ip", types.StatusInProgress) + mk("bd-st-c", types.StatusClosed) + mk("bd-st-d", types.StatusDeferred) + + out, err := r.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(5, out.TotalIssues) + s.Equal(2, out.OpenIssues) + s.Equal(1, out.InProgressIssues) + s.Equal(1, out.ClosedIssues) + s.Equal(1, out.DeferredIssues) +} + +func (s *testSuite) statsCountsBlocked() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-stb-src", "blocked") + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + tgt := newTestIssue("bd-stb-tgt", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-stb-src", "bd-stb-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := r.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(1, out.BlockedIssues) +} + +func (s *testSuite) statsCountsPinned() { + s.resetDB() + r := s.issueRepo() + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-stp-1", "x"), "tester", domain.InsertIssueOpts{})) + _, err := s.Runner().ExecContext(s.Ctx(), "UPDATE issues SET pinned = 1 WHERE id = ?", "bd-stp-1") + s.Require().NoError(err) + + out, err := r.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(1, out.PinnedIssues) +} + +func (s *testSuite) statsReadyDerived() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-srd-a", "bd-srd-b", "bd-srd-c"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-srd-a", "bd-srd-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := r.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(3, out.OpenIssues) + s.Equal(1, out.BlockedIssues) + s.Equal(2, out.ReadyIssues, "ready = open - blocked") +} + +func (s *testSuite) statsReadyClamped() { + s.resetDB() + r := s.issueRepo() + iss := newTestIssue("bd-src-c", "closed but somehow flagged") + iss.Status = types.StatusClosed + s.Require().NoError(r.Insert(s.Ctx(), iss, "tester", domain.InsertIssueOpts{})) + _, err := s.Runner().ExecContext(s.Ctx(), "UPDATE issues SET is_blocked = 1 WHERE id = ?", "bd-src-c") + s.Require().NoError(err) + + out, err := r.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.GreaterOrEqual(out.ReadyIssues, 0, "ready must never go negative") +} + +// ---------- DetectCycles ---------- + +func (s *testSuite) cyclesEmpty() { + s.resetDB() + out, err := s.depRepo().DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Empty(out) +} + +func (s *testSuite) cyclesAcyclic() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-cyA-a", "bd-cyA-b", "bd-cyA-c"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cyA-a", "bd-cyA-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cyA-b", "bd-cyA-c", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := dr.DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Empty(out) +} + +func (s *testSuite) cyclesTwoNode() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-cy2-a", "bd-cy2-b"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + // Repo-level Insert bypasses the use-case cycle check, so we can plant a cycle directly. + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cy2-a", "bd-cy2-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cy2-b", "bd-cy2-a", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := dr.DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Require().GreaterOrEqual(len(out), 1, "two-node cycle must be detected") + ids := cycleNodeIDs(out[0]) + s.Contains(ids, "bd-cy2-a") + s.Contains(ids, "bd-cy2-b") +} + +func (s *testSuite) cyclesThreeNode() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-cy3-a", "bd-cy3-b", "bd-cy3-c"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cy3-a", "bd-cy3-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cy3-b", "bd-cy3-c", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cy3-c", "bd-cy3-a", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := dr.DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Require().GreaterOrEqual(len(out), 1) + ids := cycleNodeIDs(out[0]) + for _, want := range []string{"bd-cy3-a", "bd-cy3-b", "bd-cy3-c"} { + s.Contains(ids, want) + } +} + +func (s *testSuite) cyclesIgnoresParentChild() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-cypc-a", "bd-cypc-b"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + // Parent-child is not a blocking dep type โ€” must not register as a cycle. + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cypc-a", "bd-cypc-b", types.DepParentChild), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cypc-b", "bd-cypc-a", types.DepParentChild), "tester", domain.DepInsertOpts{})) + + out, err := dr.DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Empty(out, "parent-child edges must be excluded from cycle detection") +} + +func (s *testSuite) cyclesConditionalBlocks() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-cycb-a", "bd-cycb-b"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cycb-a", "bd-cycb-b", types.DepConditionalBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-cycb-b", "bd-cycb-a", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := dr.DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Require().GreaterOrEqual(len(out), 1, "conditional-blocks must participate in cycle detection") +} + +func blockedIDs(in []*types.BlockedIssue) []string { + out := make([]string, 0, len(in)) + for _, bi := range in { + out = append(out, bi.ID) + } + return out +} + +func cycleNodeIDs(cycle []*types.Issue) []string { + out := make([]string, 0, len(cycle)) + for _, iss := range cycle { + out = append(out, iss.ID) + } + return out +} diff --git a/internal/storage/domain/db/ready_helpers_usecase_test.go b/internal/storage/domain/db/ready_helpers_usecase_test.go new file mode 100644 index 000000000..84f9260d1 --- /dev/null +++ b/internal/storage/domain/db/ready_helpers_usecase_test.go @@ -0,0 +1,275 @@ +package db + +import ( + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func (s *testSuite) TestIssueUseCase_ClaimReadyIssue() { + s.Run("WrapsClaimedTrueOnSuccess", s.ucClaimReadyWrapsClaimed) + s.Run("NoReadyReturnsClaimedFalse", s.ucClaimReadyEmpty) + s.Run("AppliesAssigneeAndStatus", s.ucClaimReadyAppliesState) + s.Run("PropagatesFilter", s.ucClaimReadyFilter) +} + +func (s *testSuite) TestIssueUseCase_ClaimReadyWisp() { + s.Run("DelegatesToSharedReadyClaim", s.ucClaimReadyWispDelegates) + s.Run("NoReadyReturnsClaimedFalse", s.ucClaimReadyWispEmpty) +} + +func (s *testSuite) TestIssueUseCase_GetBlockedIssues() { + s.Run("PassesThroughBlockedListing", s.ucBlockedPassesThrough) + s.Run("EmptyDBReturnsEmpty", s.ucBlockedEmpty) + s.Run("ParentIDFilterHonored", s.ucBlockedParentFilter) +} + +func (s *testSuite) TestIssueUseCase_GetStatistics() { + s.Run("EmptyDBReturnsZeroes", s.ucStatsEmpty) + s.Run("AggregatesAcrossStatuses", s.ucStatsAggregates) + s.Run("ReadyDerived", s.ucStatsReadyDerived) +} + +func (s *testSuite) TestDependencyUseCase_DetectCycles() { + s.Run("NoEdgesReturnsEmpty", s.ucCyclesEmpty) + s.Run("CycleDetected", s.ucCyclesDetected) + s.Run("AcyclicReturnsEmpty", s.ucCyclesAcyclic) +} + +// ---------- ClaimReadyIssue UC ---------- + +func (s *testSuite) ucClaimReadyWrapsClaimed() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-uccr-a", "alpha"), "tester", domain.InsertIssueOpts{})) + + res, err := uc.ClaimReadyIssue(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.True(res.Claimed, "Claimed must be true when an issue was claimed") + s.Require().NotNil(res.Issue) + s.Equal("bd-uccr-a", res.Issue.ID) +} + +func (s *testSuite) ucClaimReadyEmpty() { + s.resetDB() + uc := s.issueUseCase() + + res, err := uc.ClaimReadyIssue(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.False(res.Claimed, "Claimed must be false when nothing was claimable") + s.Nil(res.Issue, "Issue must be nil when nothing was claimable") +} + +func (s *testSuite) ucClaimReadyAppliesState() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-uccr-st", "x"), "tester", domain.InsertIssueOpts{})) + + res, err := uc.ClaimReadyIssue(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.Require().True(res.Claimed) + + got, err := r.Get(s.Ctx(), "bd-uccr-st", domain.IssueTableOpts{}) + s.Require().NoError(err) + s.Equal(types.StatusInProgress, got.Status) + s.Equal("alice", got.Assignee) +} + +func (s *testSuite) ucClaimReadyFilter() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + low := newTestIssue("bd-uccr-lo", "lo") + low.Priority = 3 + s.Require().NoError(r.Insert(s.Ctx(), low, "tester", domain.InsertIssueOpts{})) + high := newTestIssue("bd-uccr-hi", "hi") + high.Priority = 1 + s.Require().NoError(r.Insert(s.Ctx(), high, "tester", domain.InsertIssueOpts{})) + + p := 1 + res, err := uc.ClaimReadyIssue(s.Ctx(), types.WorkFilter{Priority: &p}, "alice") + s.Require().NoError(err) + s.Require().True(res.Claimed) + s.Equal("bd-uccr-hi", res.Issue.ID, "UC must pass the filter through to the repo") +} + +// ---------- ClaimReadyWisp UC ---------- + +func (s *testSuite) ucClaimReadyWispDelegates() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue("bd-uccrw-a", "alpha"), "tester", domain.InsertIssueOpts{})) + + res, err := uc.ClaimReadyWisp(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.True(res.Claimed) + s.Require().NotNil(res.Issue) + s.Equal("bd-uccrw-a", res.Issue.ID) +} + +func (s *testSuite) ucClaimReadyWispEmpty() { + s.resetDB() + uc := s.issueUseCase() + + res, err := uc.ClaimReadyWisp(s.Ctx(), types.WorkFilter{}, "alice") + s.Require().NoError(err) + s.False(res.Claimed) + s.Nil(res.Issue) +} + +// ---------- GetBlockedIssues UC ---------- + +func (s *testSuite) ucBlockedPassesThrough() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + dr := s.depRepo() + src := newTestIssue("bd-ucbl-src", "blocked") + s.Require().NoError(r.Insert(s.Ctx(), src, "tester", domain.InsertIssueOpts{})) + tgt := newTestIssue("bd-ucbl-tgt", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), tgt, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-ucbl-src", "bd-ucbl-tgt", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := uc.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + s.Require().Len(out, 1) + s.Equal("bd-ucbl-src", out[0].ID) + s.Equal([]string{"bd-ucbl-tgt"}, out[0].BlockedBy) +} + +func (s *testSuite) ucBlockedEmpty() { + s.resetDB() + uc := s.issueUseCase() + out, err := uc.GetBlockedIssues(s.Ctx(), types.WorkFilter{}) + s.Require().NoError(err) + s.Empty(out) +} + +func (s *testSuite) ucBlockedParentFilter() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + dr := s.depRepo() + parent := newTestIssue("bd-ucblp-parent", "parent") + s.Require().NoError(r.Insert(s.Ctx(), parent, "tester", domain.InsertIssueOpts{})) + inside := newTestIssue("bd-ucblp-parent.1", "inside") + s.Require().NoError(r.Insert(s.Ctx(), inside, "tester", domain.InsertIssueOpts{})) + outside := newTestIssue("bd-ucblp-out", "outside") + s.Require().NoError(r.Insert(s.Ctx(), outside, "tester", domain.InsertIssueOpts{})) + blocker := newTestIssue("bd-ucblp-blocker", "blocker") + s.Require().NoError(r.Insert(s.Ctx(), blocker, "tester", domain.InsertIssueOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-ucblp-parent.1", "bd-ucblp-parent", types.DepParentChild), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-ucblp-parent.1", "bd-ucblp-blocker", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-ucblp-out", "bd-ucblp-blocker", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + pid := "bd-ucblp-parent" + out, err := uc.GetBlockedIssues(s.Ctx(), types.WorkFilter{ParentID: &pid}) + s.Require().NoError(err) + ids := blockedIDs(out) + s.Contains(ids, "bd-ucblp-parent.1") + s.NotContains(ids, "bd-ucblp-out", "UC must forward ParentID filter") +} + +// ---------- GetStatistics UC ---------- + +func (s *testSuite) ucStatsEmpty() { + s.resetDB() + uc := s.issueUseCase() + stats, err := uc.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(0, stats.TotalIssues) + s.Equal(0, stats.ReadyIssues) + s.Equal(0, stats.BlockedIssues) +} + +func (s *testSuite) ucStatsAggregates() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + mk := func(id string, status types.Status) { + iss := newTestIssue(id, string(status)) + iss.Status = status + s.Require().NoError(r.Insert(s.Ctx(), iss, "tester", domain.InsertIssueOpts{})) + } + mk("bd-ucst-o1", types.StatusOpen) + mk("bd-ucst-o2", types.StatusOpen) + mk("bd-ucst-ip", types.StatusInProgress) + mk("bd-ucst-c", types.StatusClosed) + + stats, err := uc.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(4, stats.TotalIssues) + s.Equal(2, stats.OpenIssues) + s.Equal(1, stats.InProgressIssues) + s.Equal(1, stats.ClosedIssues) +} + +func (s *testSuite) ucStatsReadyDerived() { + s.resetDB() + uc := s.issueUseCase() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-ucsr-a", "bd-ucsr-b"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-ucsr-a", "bd-ucsr-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + stats, err := uc.GetStatistics(s.Ctx()) + s.Require().NoError(err) + s.Equal(2, stats.OpenIssues) + s.Equal(1, stats.BlockedIssues) + s.Equal(1, stats.ReadyIssues, "UC must surface ready = open - blocked") +} + +// ---------- DetectCycles UC ---------- + +func (s *testSuite) ucCyclesEmpty() { + s.resetDB() + out, err := s.depUseCase().DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Empty(out) +} + +func (s *testSuite) ucCyclesDetected() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-uccy-a", "bd-uccy-b"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-uccy-a", "bd-uccy-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-uccy-b", "bd-uccy-a", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := s.depUseCase().DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Require().GreaterOrEqual(len(out), 1) + ids := cycleNodeIDs(out[0]) + s.Contains(ids, "bd-uccy-a") + s.Contains(ids, "bd-uccy-b") +} + +func (s *testSuite) ucCyclesAcyclic() { + s.resetDB() + r := s.issueRepo() + dr := s.depRepo() + for _, id := range []string{"bd-uccya-a", "bd-uccya-b", "bd-uccya-c"} { + s.Require().NoError(r.Insert(s.Ctx(), newTestIssue(id, id), "tester", domain.InsertIssueOpts{})) + } + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-uccya-a", "bd-uccya-b", types.DepBlocks), "tester", domain.DepInsertOpts{})) + s.Require().NoError(dr.Insert(s.Ctx(), + newDep("bd-uccya-b", "bd-uccya-c", types.DepBlocks), "tester", domain.DepInsertOpts{})) + + out, err := s.depUseCase().DetectCycles(s.Ctx()) + s.Require().NoError(err) + s.Empty(out) +} diff --git a/internal/storage/domain/dependency.go b/internal/storage/domain/dependency.go index 18cbee62a..ba7040308 100644 --- a/internal/storage/domain/dependency.go +++ b/internal/storage/domain/dependency.go @@ -69,6 +69,7 @@ type DependencySQLRepository interface { DeleteAllForIDs(ctx context.Context, ids []string, opts DepInsertOpts) (int, error) CountAllForIDs(ctx context.Context, ids []string, opts DepCountsOpts) (int, error) + DetectCycles(ctx context.Context) ([][]*types.Issue, error) } type DependencyUseCase interface { @@ -83,6 +84,7 @@ type DependencyUseCase interface { GetBlockingInfo(ctx context.Context, issueIDs []string) (BlockingInfo, error) IsBlocked(ctx context.Context, issueID string) (bool, []string, error) GetForIssueIDs(ctx context.Context, ids []string) (map[string][]*types.Dependency, error) + DetectCycles(ctx context.Context) ([][]*types.Issue, error) AddWispDependency(ctx context.Context, dep *types.Dependency, actor string) error RemoveWispDependency(ctx context.Context, wispID, dependsOnID, actor string) error @@ -385,3 +387,11 @@ func (u *dependencyUseCaseImpl) isBlocked(ctx context.Context, id string, useWis } return blocked, blockers, nil } + +func (u *dependencyUseCaseImpl) DetectCycles(ctx context.Context) ([][]*types.Issue, error) { + out, err := u.depRepo.DetectCycles(ctx) + if err != nil { + return nil, fmt.Errorf("DetectCycles: %w", err) + } + return out, nil +} diff --git a/internal/storage/domain/issue.go b/internal/storage/domain/issue.go index 2edc5a3f8..30d4b1864 100644 --- a/internal/storage/domain/issue.go +++ b/internal/storage/domain/issue.go @@ -54,6 +54,10 @@ type IssueSQLRepository interface { Close(ctx context.Context, id string, params CloseRowParams, actor string, opts IssueTableOpts) (CloseRowResult, error) Reopen(ctx context.Context, id string, params ReopenRowParams, actor string, opts IssueTableOpts) (ReopenRowResult, error) GetNewlyUnblockedByClose(ctx context.Context, closedID string) ([]*types.Issue, error) + ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) + 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) } type CloseRowParams struct { @@ -175,6 +179,11 @@ type ClaimResult struct { PriorAssignee string } +type ClaimReadyResult struct { + Issue *types.Issue + Claimed bool +} + type UpdateSpec struct { Fields map[string]any Claim bool @@ -192,6 +201,9 @@ type IssueUseCase interface { GetReadyWork(ctx context.Context, filter types.WorkFilter) (SearchPage, error) GetReadyWorkWithCounts(ctx context.Context, filter types.WorkFilter) (SearchCountsPage, error) GetDescendants(ctx context.Context, rootID string, filter types.IssueFilter) ([]*types.Issue, error) + 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) CreateIssue(ctx context.Context, params CreateIssueParams, actor string) (CreateIssueResult, error) CreateIssues(ctx context.Context, params []CreateIssueParams, actor string) (CreateIssuesResult, error) @@ -224,6 +236,7 @@ type IssueUseCase interface { CountOpenWispChildren(ctx context.Context, id string) (int, error) GetNewlyUnblockedByCloseWisp(ctx context.Context, closedID string) ([]*types.Issue, error) ApplyWispGraph(ctx context.Context, plan GraphPlan, actor string) (GraphApplyResult, error) + ClaimReadyWisp(ctx context.Context, filter types.WorkFilter, actor string) (ClaimReadyResult, error) } type CloseIssueParams struct { @@ -1279,3 +1292,46 @@ func (u *issueUseCaseImpl) getNewlyUnblockedByClose(ctx context.Context, closedI } return out, nil } + +func (u *issueUseCaseImpl) ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (ClaimReadyResult, error) { + return u.claimReady(ctx, filter, actor, false) +} + +func (u *issueUseCaseImpl) ClaimReadyWisp(ctx context.Context, filter types.WorkFilter, actor string) (ClaimReadyResult, error) { + return u.claimReady(ctx, filter, actor, true) +} + +func (u *issueUseCaseImpl) claimReady(ctx context.Context, filter types.WorkFilter, actor string, useWisp bool) (ClaimReadyResult, error) { + var ( + issue *types.Issue + err error + ) + if useWisp { + issue, err = u.issueRepo.ClaimReadyWisp(ctx, filter, actor) + } else { + issue, err = u.issueRepo.ClaimReadyIssue(ctx, filter, actor) + } + if err != nil { + if useWisp { + return ClaimReadyResult{}, fmt.Errorf("ClaimReadyWisp: %w", err) + } + return ClaimReadyResult{}, fmt.Errorf("ClaimReadyIssue: %w", err) + } + return ClaimReadyResult{Issue: issue, Claimed: issue != nil}, nil +} + +func (u *issueUseCaseImpl) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) { + out, err := u.issueRepo.GetBlockedIssues(ctx, filter) + if err != nil { + return nil, fmt.Errorf("GetBlockedIssues: %w", err) + } + return out, nil +} + +func (u *issueUseCaseImpl) GetStatistics(ctx context.Context) (*types.Statistics, error) { + out, err := u.issueRepo.GetStatistics(ctx) + if err != nil { + return nil, fmt.Errorf("GetStatistics: %w", err) + } + return out, nil +} diff --git a/internal/storage/issueops/blocked.go b/internal/storage/issueops/blocked.go index 5ebd61ba9..64eed234a 100644 --- a/internal/storage/issueops/blocked.go +++ b/internal/storage/issueops/blocked.go @@ -19,7 +19,7 @@ func optionalBlockedTable(table string) bool { return table == "wisps" || table == "wisp_dependencies" } -func loadBlockingDepsForIssueIDsInTx(ctx context.Context, tx *sql.Tx, depTables []string, issueIDs []string) ([]blockingDepRecord, error) { +func loadBlockingDepsForIssueIDsInTx(ctx context.Context, tx DBTX, depTables []string, issueIDs []string) ([]blockingDepRecord, error) { var deps []blockingDepRecord for _, depTable := range depTables { //nolint:gosec // G201: depTable is a hardcoded constant. @@ -53,7 +53,7 @@ func loadBlockingDepsForIssueIDsInTx(ctx context.Context, tx *sql.Tx, depTables return deps, nil } -func loadParentIDsForChildrenInTx(ctx context.Context, tx *sql.Tx, depTables []string, childIDs []string) (map[string]string, error) { +func loadParentIDsForChildrenInTx(ctx context.Context, tx DBTX, depTables []string, childIDs []string) (map[string]string, error) { childParents := make(map[string]string) for _, depTable := range depTables { //nolint:gosec // G201: depTable is a hardcoded constant. @@ -88,7 +88,7 @@ func loadParentIDsForChildrenInTx(ctx context.Context, tx *sql.Tx, depTables []s } //nolint:gosec // G201: tables are hardcoded -func GetChildrenWithParentsInTx(ctx context.Context, tx *sql.Tx, parentIDs []string) (map[string]string, error) { +func GetChildrenWithParentsInTx(ctx context.Context, tx DBTX, parentIDs []string) (map[string]string, error) { if len(parentIDs) == 0 { return nil, nil } @@ -124,7 +124,7 @@ func GetChildrenWithParentsInTx(ctx context.Context, tx *sql.Tx, parentIDs []str } //nolint:gosec // G201: tables are hardcoded -func GetChildrenOfIssuesInTx(ctx context.Context, tx *sql.Tx, parentIDs []string) ([]string, error) { +func GetChildrenOfIssuesInTx(ctx context.Context, tx DBTX, parentIDs []string) ([]string, error) { if len(parentIDs) == 0 { return nil, nil } @@ -159,7 +159,7 @@ func GetChildrenOfIssuesInTx(ctx context.Context, tx *sql.Tx, parentIDs []string return children, nil } -func GetDescendantIDsInTx(ctx context.Context, tx *sql.Tx, rootID string, maxDepth int) ([]string, error) { +func GetDescendantIDsInTx(ctx context.Context, tx DBTX, rootID string, maxDepth int) ([]string, error) { if rootID == "" { return nil, nil } @@ -237,7 +237,7 @@ func GetDescendantIDsInTx(ctx context.Context, tx *sql.Tx, rootID string, maxDep } //nolint:gosec // G201: tables are hardcoded -func GetBlockedIssuesInTx(ctx context.Context, tx *sql.Tx, filter types.WorkFilter) ([]*types.BlockedIssue, error) { +func GetBlockedIssuesInTx(ctx context.Context, tx DBTX, filter types.WorkFilter) ([]*types.BlockedIssue, error) { var blockedIDList []string blockedSet := make(map[string]bool) for _, table := range []string{"issues", "wisps"} { diff --git a/internal/storage/issueops/claim.go b/internal/storage/issueops/claim.go index 84bb8bf1b..f5e87f5c9 100644 --- a/internal/storage/issueops/claim.go +++ b/internal/storage/issueops/claim.go @@ -28,7 +28,7 @@ type ClaimResult struct { // The caller is responsible for Dolt versioning (DOLT_ADD/COMMIT) if needed. // //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func ClaimIssueInTx(ctx context.Context, tx *sql.Tx, id string, actor string) (*ClaimResult, error) { +func ClaimIssueInTx(ctx context.Context, tx DBTX, id string, actor string) (*ClaimResult, error) { isWisp := IsActiveWispInTx(ctx, tx, id) issueTable, _, eventTable, _ := WispTableRouting(isWisp) @@ -113,7 +113,7 @@ func ClaimIssueInTx(ctx context.Context, tx *sql.Tx, id string, actor string) (* // ready issue can be claimed. func ClaimReadyIssueInTx( ctx context.Context, - tx *sql.Tx, + tx DBTX, filter types.WorkFilter, actor string, ) (*types.Issue, error) { diff --git a/internal/storage/issueops/config_helpers.go b/internal/storage/issueops/config_helpers.go index d10cf6594..f765bddb0 100644 --- a/internal/storage/issueops/config_helpers.go +++ b/internal/storage/issueops/config_helpers.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "encoding/json" "fmt" "strings" @@ -47,7 +46,7 @@ func ParseCommaSeparatedList(value string) []string { return result } -func ResolveCustomConfigInTx(ctx context.Context, tx *sql.Tx) (statuses []types.CustomStatus, customTypes []string, err error) { +func ResolveCustomConfigInTx(ctx context.Context, tx DBTX) (statuses []types.CustomStatus, customTypes []string, err error) { statuses, statusesFromTable, err := resolveCustomStatusesFromTableInTx(ctx, tx) if err != nil { return nil, nil, err @@ -99,7 +98,7 @@ func ResolveCustomConfigInTx(ctx context.Context, tx *sql.Tx) (statuses []types. return statuses, customTypes, nil } -func resolveCustomStatusesFromTableInTx(ctx context.Context, tx *sql.Tx) ([]types.CustomStatus, bool, error) { +func resolveCustomStatusesFromTableInTx(ctx context.Context, tx DBTX) ([]types.CustomStatus, bool, error) { rows, err := tx.QueryContext(ctx, "SELECT name, category FROM custom_statuses ORDER BY name") if err != nil { return nil, false, nil @@ -122,7 +121,7 @@ func resolveCustomStatusesFromTableInTx(ctx context.Context, tx *sql.Tx) ([]type return result, len(result) > 0, nil } -func resolveCustomTypesFromTableInTx(ctx context.Context, tx *sql.Tx) ([]string, bool, error) { +func resolveCustomTypesFromTableInTx(ctx context.Context, tx DBTX) ([]string, bool, error) { rows, err := tx.QueryContext(ctx, "SELECT name FROM custom_types ORDER BY name") if err != nil { return nil, false, nil @@ -142,7 +141,7 @@ func resolveCustomTypesFromTableInTx(ctx context.Context, tx *sql.Tx) ([]string, return result, len(result) > 0, nil } -func getConfigKeysInTx(ctx context.Context, tx *sql.Tx, keys ...string) (map[string]string, error) { +func getConfigKeysInTx(ctx context.Context, tx DBTX, keys ...string) (map[string]string, error) { if len(keys) == 0 { return map[string]string{}, nil } @@ -175,7 +174,7 @@ func getConfigKeysInTx(ctx context.Context, tx *sql.Tx, keys ...string) (map[str // doesn't exist (pre-migration databases). // Returns nil on parse errors (degraded mode). Does not cache or log โ€” // callers layer those concerns on top. -func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx *sql.Tx) ([]types.CustomStatus, error) { +func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx DBTX) ([]types.CustomStatus, error) { // Try the normalized table first rows, err := tx.QueryContext(ctx, "SELECT name, category FROM custom_statuses ORDER BY name") if err == nil { @@ -239,7 +238,7 @@ func ResolveCustomStatusesDetailedInTx(ctx context.Context, tx *sql.Tx) ([]types // whose type is in none still fails cleanly. // // Does not cache โ€” callers layer caching on top. -func ResolveCustomTypesInTx(ctx context.Context, tx *sql.Tx) ([]string, error) { +func ResolveCustomTypesInTx(ctx context.Context, tx DBTX) ([]string, error) { var fromDB []string // Try the normalized table first. @@ -367,7 +366,7 @@ func dedupePreservingOrder(in []string) []string { // SyncCustomStatusesTable replaces all rows in custom_statuses with parsed config value. // Used by both DoltStore and EmbeddedDoltStore when "status.custom" config changes. -func SyncCustomStatusesTable(ctx context.Context, tx *sql.Tx, value string) error { +func SyncCustomStatusesTable(ctx context.Context, tx DBTX, value string) error { if _, err := tx.ExecContext(ctx, "DELETE FROM custom_statuses"); err != nil { return err } @@ -389,7 +388,7 @@ func SyncCustomStatusesTable(ctx context.Context, tx *sql.Tx, value string) erro // SyncCustomTypesTable replaces all rows in custom_types with parsed config value. // Used by both DoltStore and EmbeddedDoltStore when "types.custom" config changes. -func SyncCustomTypesTable(ctx context.Context, tx *sql.Tx, value string) error { +func SyncCustomTypesTable(ctx context.Context, tx DBTX, value string) error { if _, err := tx.ExecContext(ctx, "DELETE FROM custom_types"); err != nil { return err } @@ -426,7 +425,7 @@ func parseTypesValue(value string) []string { // formula system creates implicitly (e.g. "gate" for async coordination // beads) so that operators don't have to run bd config set types.custom // manually before pouring a formula with gate steps. See GH#3213. -func EnsureCustomTypeInTx(ctx context.Context, tx *sql.Tx, name string) error { +func EnsureCustomTypeInTx(ctx context.Context, tx DBTX, name string) error { if types.IssueType(name).IsValid() { return nil } @@ -447,7 +446,7 @@ func EnsureCustomTypeInTx(ctx context.Context, tx *sql.Tx, name string) error { // falling back to config.yaml then to hardcoded defaults. // Returns a map[string]bool for O(1) lookups. // Does not cache โ€” callers layer caching on top. -func ResolveInfraTypesInTx(ctx context.Context, tx *sql.Tx) map[string]bool { +func ResolveInfraTypesInTx(ctx context.Context, tx DBTX) map[string]bool { var typeList []string value, err := GetConfigInTx(ctx, tx, "types.infra") diff --git a/internal/storage/issueops/config_metadata.go b/internal/storage/issueops/config_metadata.go index 0b917c7e3..0942ed9ee 100644 --- a/internal/storage/issueops/config_metadata.go +++ b/internal/storage/issueops/config_metadata.go @@ -9,7 +9,7 @@ import ( // SetConfigInTx sets a configuration value within an existing transaction. // Normalizes issue_prefix by stripping trailing hyphens. -func SetConfigInTx(ctx context.Context, tx *sql.Tx, key, value string) error { +func SetConfigInTx(ctx context.Context, tx DBTX, key, value string) error { if key == "issue_prefix" { value = strings.TrimSuffix(value, "-") } @@ -22,7 +22,7 @@ func SetConfigInTx(ctx context.Context, tx *sql.Tx, key, value string) error { // GetConfigInTx retrieves a configuration value within an existing transaction. // Returns ("", nil) if the key does not exist. -func GetConfigInTx(ctx context.Context, tx *sql.Tx, key string) (string, error) { +func GetConfigInTx(ctx context.Context, tx DBTX, key string) (string, error) { var value string err := tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", key).Scan(&value) if err == sql.ErrNoRows { @@ -35,7 +35,7 @@ func GetConfigInTx(ctx context.Context, tx *sql.Tx, key string) (string, error) } // GetAllConfigInTx retrieves all configuration key-value pairs within an existing transaction. -func GetAllConfigInTx(ctx context.Context, tx *sql.Tx) (map[string]string, error) { +func GetAllConfigInTx(ctx context.Context, tx DBTX) (map[string]string, error) { rows, err := tx.QueryContext(ctx, "SELECT `key`, value FROM config") if err != nil { return nil, fmt.Errorf("get all config: %w", err) @@ -54,7 +54,7 @@ func GetAllConfigInTx(ctx context.Context, tx *sql.Tx) (map[string]string, error } // SetMetadataInTx sets a metadata value within an existing transaction. -func SetMetadataInTx(ctx context.Context, tx *sql.Tx, key, value string) error { +func SetMetadataInTx(ctx context.Context, tx DBTX, key, value string) error { _, err := tx.ExecContext(ctx, "REPLACE INTO metadata (`key`, value) VALUES (?, ?)", key, value) if err != nil { return fmt.Errorf("set metadata %s: %w", key, err) @@ -64,7 +64,7 @@ func SetMetadataInTx(ctx context.Context, tx *sql.Tx, key, value string) error { // GetMetadataInTx retrieves a metadata value within an existing transaction. // Returns ("", nil) if the key does not exist. -func GetMetadataInTx(ctx context.Context, tx *sql.Tx, key string) (string, error) { +func GetMetadataInTx(ctx context.Context, tx DBTX, key string) (string, error) { var value string err := tx.QueryRowContext(ctx, "SELECT value FROM metadata WHERE `key` = ?", key).Scan(&value) if err == sql.ErrNoRows { @@ -79,7 +79,7 @@ func GetMetadataInTx(ctx context.Context, tx *sql.Tx, key string) (string, error // SetLocalMetadataInTx sets a value in the dolt-ignored local_metadata table // within an existing transaction. Used for clone-local state that should not // generate merge conflicts (tip timestamps, version stamps, sync cursors). -func SetLocalMetadataInTx(ctx context.Context, tx *sql.Tx, key, value string) error { +func SetLocalMetadataInTx(ctx context.Context, tx DBTX, key, value string) error { _, err := tx.ExecContext(ctx, "REPLACE INTO local_metadata (`key`, value) VALUES (?, ?)", key, value) if err != nil { return fmt.Errorf("set local metadata %s: %w", key, err) @@ -89,7 +89,7 @@ func SetLocalMetadataInTx(ctx context.Context, tx *sql.Tx, key, value string) er // GetLocalMetadataInTx retrieves a value from the dolt-ignored local_metadata // table within an existing transaction. Returns ("", nil) if the key does not exist. -func GetLocalMetadataInTx(ctx context.Context, tx *sql.Tx, key string) (string, error) { +func GetLocalMetadataInTx(ctx context.Context, tx DBTX, key string) (string, error) { var value string err := tx.QueryRowContext(ctx, "SELECT value FROM local_metadata WHERE `key` = ?", key).Scan(&value) if err == sql.ErrNoRows { diff --git a/internal/storage/issueops/cycles.go b/internal/storage/issueops/cycles.go index 023d48612..dbc920bb7 100644 --- a/internal/storage/issueops/cycles.go +++ b/internal/storage/issueops/cycles.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "strings" @@ -12,7 +11,7 @@ import ( // DetectCyclesInTx finds dependency cycles across both the dependencies and // wisp_dependencies tables. Returns slices of issues forming each cycle. // Only considers "blocks" and "conditional-blocks" dependencies for cycle detection. -func DetectCyclesInTx(ctx context.Context, tx *sql.Tx) ([][]*types.Issue, error) { +func DetectCyclesInTx(ctx context.Context, tx DBTX) ([][]*types.Issue, error) { // Build adjacency list from both dependency tables. graph := make(map[string][]string) if err := AppendBlockingGraphInTx(ctx, tx, []string{"dependencies", "wisp_dependencies"}, graph); err != nil { @@ -82,7 +81,7 @@ func DetectCyclesInTx(ctx context.Context, tx *sql.Tx) ([][]*types.Issue, error) // separate ignored tx). // //nolint:gosec // G201: depTable is hardcoded to "dependencies" or "wisp_dependencies" -func AppendBlockingGraphInTx(ctx context.Context, tx *sql.Tx, depTables []string, graph map[string][]string) error { +func AppendBlockingGraphInTx(ctx context.Context, tx DBTX, depTables []string, graph map[string][]string) error { for _, depTable := range depTables { rows, err := tx.QueryContext(ctx, fmt.Sprintf(` SELECT issue_id, %s AS depends_on_id, type diff --git a/internal/storage/issueops/dependency_queries.go b/internal/storage/issueops/dependency_queries.go index 5d93dc4d6..29c466838 100644 --- a/internal/storage/issueops/dependency_queries.go +++ b/internal/storage/issueops/dependency_queries.go @@ -13,7 +13,7 @@ import ( // GetAllDependencyRecordsInTx returns all dependency records from permanent and // wisp dependency tables. -func GetAllDependencyRecordsInTx(ctx context.Context, tx *sql.Tx) (map[string][]*types.Dependency, error) { +func GetAllDependencyRecordsInTx(ctx context.Context, tx DBTX) (map[string][]*types.Dependency, error) { result := make(map[string][]*types.Dependency) for _, depTable := range []string{"dependencies", "wisp_dependencies"} { if err := getAllDependencyRecordsIntoFromTable(ctx, tx, depTable, result); err != nil { @@ -27,7 +27,7 @@ func GetAllDependencyRecordsInTx(ctx context.Context, tx *sql.Tx) (map[string][] } //nolint:gosec // G201: depTable is "dependencies" or "wisp_dependencies" (hardcoded by caller). -func getAllDependencyRecordsIntoFromTable(ctx context.Context, tx *sql.Tx, depTable string, result map[string][]*types.Dependency) error { +func getAllDependencyRecordsIntoFromTable(ctx context.Context, tx DBTX, depTable string, result map[string][]*types.Dependency) error { rows, err := tx.QueryContext(ctx, fmt.Sprintf(` SELECT issue_id, %s AS depends_on_id, type, created_at, created_by, metadata, thread_id FROM %s @@ -56,7 +56,7 @@ func getAllDependencyRecordsIntoFromTable(ctx context.Context, tx *sql.Tx, depTa // Uses a single batched wisp-partition query + batched IN clauses, so cost is // O(1 + N/queryBatchSize) round-trips rather than O(N) โ€” important on remote // backends (see GH#3414). -func GetDependencyRecordsForIssuesInTx(ctx context.Context, tx *sql.Tx, issueIDs []string) (map[string][]*types.Dependency, error) { +func GetDependencyRecordsForIssuesInTx(ctx context.Context, tx DBTX, issueIDs []string) (map[string][]*types.Dependency, error) { if len(issueIDs) == 0 { return make(map[string][]*types.Dependency), nil } @@ -83,7 +83,7 @@ func GetDependencyRecordsForIssuesInTx(ctx context.Context, tx *sql.Tx, issueIDs // GetDependencyRecordsForIssuesFromTableInTx is a fast-path variant used by // callers that already know every ID belongs to a single dep table (e.g. // searchTableInTx). Skips the wisp-partition round-trip. -func GetDependencyRecordsForIssuesFromTableInTx(ctx context.Context, tx *sql.Tx, depTable string, issueIDs []string) (map[string][]*types.Dependency, error) { +func GetDependencyRecordsForIssuesFromTableInTx(ctx context.Context, tx DBTX, depTable string, issueIDs []string) (map[string][]*types.Dependency, error) { if len(issueIDs) == 0 { return make(map[string][]*types.Dependency), nil } @@ -95,7 +95,7 @@ func GetDependencyRecordsForIssuesFromTableInTx(ctx context.Context, tx *sql.Tx, } //nolint:gosec // G201: depTable is "dependencies" or "wisp_dependencies" (hardcoded by callers). -func getDependencyRecordsIntoFromTable(ctx context.Context, tx *sql.Tx, depTable string, ids []string, result map[string][]*types.Dependency) error { +func getDependencyRecordsIntoFromTable(ctx context.Context, tx DBTX, depTable string, ids []string, result map[string][]*types.Dependency) error { for start := 0; start < len(ids); start += queryBatchSize { end := start + queryBatchSize if end > len(ids) { @@ -131,7 +131,7 @@ func getDependencyRecordsIntoFromTable(ctx context.Context, tx *sql.Tx, depTable return nil } -func GetDependencyCountsInTx(ctx context.Context, tx *sql.Tx, issueIDs []string) (map[string]*types.DependencyCounts, error) { +func GetDependencyCountsInTx(ctx context.Context, tx DBTX, issueIDs []string) (map[string]*types.DependencyCounts, error) { if len(issueIDs) == 0 { return make(map[string]*types.DependencyCounts), nil } @@ -232,7 +232,7 @@ func GetDependencyCountsInTx(ctx context.Context, tx *sql.Tx, issueIDs []string) // - blockedByMap: issueID -> list of IDs blocking it // - blocksMap: issueID -> list of IDs it blocks // - parentMap: childID -> parentID (parent-child deps) -func GetBlockingInfoForIssuesInTx(ctx context.Context, tx *sql.Tx, issueIDs []string) ( +func GetBlockingInfoForIssuesInTx(ctx context.Context, tx DBTX, issueIDs []string) ( blockedByMap map[string][]string, blocksMap map[string][]string, parentMap map[string]string, @@ -286,7 +286,7 @@ type blockingInfoRow struct { // cross-class closed blockers do not appear active. // Uses batched IN clauses (queryBatchSize) to avoid query-planner spikes. func queryBlockedByInfo( - ctx context.Context, tx *sql.Tx, + ctx context.Context, tx DBTX, issueIDs []string, depTable string, blockedByMap map[string][]string, @@ -359,7 +359,7 @@ func queryBlockedByInfo( // queryBlocksInfo queries inbound blocking info across dependency tables. func queryBlocksInfo( - ctx context.Context, tx *sql.Tx, + ctx context.Context, tx DBTX, issueIDs []string, depTables []string, blocksMap map[string][]string, diff --git a/internal/storage/issueops/labels.go b/internal/storage/issueops/labels.go index 29d613c3a..49aabf86f 100644 --- a/internal/storage/issueops/labels.go +++ b/internal/storage/issueops/labels.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "strings" @@ -44,7 +43,7 @@ func GetLabelsInTx(ctx context.Context, tx DBTX, table, issueID string) ([]strin // // Callers hydrating multiple batches inside one tx may pass a precomputed // active-wisp set scoped to issueIDs to avoid rebuilding it. -func GetLabelsForIssuesInTx(ctx context.Context, tx *sql.Tx, issueIDs []string, wispSetOpt ...map[string]struct{}) (map[string][]string, error) { +func GetLabelsForIssuesInTx(ctx context.Context, tx DBTX, issueIDs []string, wispSetOpt ...map[string]struct{}) (map[string][]string, error) { if len(issueIDs) == 0 { return make(map[string][]string), nil } @@ -79,7 +78,7 @@ func GetLabelsForIssuesInTx(ctx context.Context, tx *sql.Tx, issueIDs []string, // which queries either the issues or wisps table exclusively). It skips the // wisp-partition round-trip entirely. labelTable must be "labels" or // "wisp_labels"; callers route via FilterTables. -func GetLabelsForIssuesFromTableInTx(ctx context.Context, tx *sql.Tx, labelTable string, issueIDs []string) (map[string][]string, error) { +func GetLabelsForIssuesFromTableInTx(ctx context.Context, tx DBTX, labelTable string, issueIDs []string) (map[string][]string, error) { if len(issueIDs) == 0 { return make(map[string][]string), nil } @@ -94,7 +93,7 @@ func GetLabelsForIssuesFromTableInTx(ctx context.Context, tx *sql.Tx, labelTable // and accumulates results into the provided map. // //nolint:gosec // G201: labelTable is "labels" or "wisp_labels" (hardcoded by callers). -func getLabelsIntoFromTable(ctx context.Context, tx *sql.Tx, labelTable string, ids []string, result map[string][]string) error { +func getLabelsIntoFromTable(ctx context.Context, tx DBTX, labelTable string, ids []string, result map[string][]string) error { for start := 0; start < len(ids); start += queryBatchSize { end := start + queryBatchSize if end > len(ids) { @@ -132,7 +131,7 @@ func getLabelsIntoFromTable(ctx context.Context, tx *sql.Tx, labelTable string, // AddLabelInTx adds a label to an issue and records an event within an existing // transaction. Automatically routes to wisp tables if the ID is an active wisp. // Uses INSERT IGNORE for idempotency. -func AddLabelInTx(ctx context.Context, tx *sql.Tx, labelTable, eventTable, issueID, label, actor string) error { +func AddLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string) error { if labelTable == "" || eventTable == "" { isWisp := IsActiveWispInTx(ctx, tx, issueID) _, lt, et, _ := WispTableRouting(isWisp) @@ -161,7 +160,7 @@ func AddLabelInTx(ctx context.Context, tx *sql.Tx, labelTable, eventTable, issue // an active wisp. // //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func RemoveLabelInTx(ctx context.Context, tx *sql.Tx, labelTable, eventTable, issueID, label, actor string) error { +func RemoveLabelInTx(ctx context.Context, tx DBTX, labelTable, eventTable, issueID, label, actor string) error { if labelTable == "" || eventTable == "" { isWisp := IsActiveWispInTx(ctx, tx, issueID) _, lt, et, _ := WispTableRouting(isWisp) diff --git a/internal/storage/issueops/ready_work.go b/internal/storage/issueops/ready_work.go index f3c548798..6320fb3fc 100644 --- a/internal/storage/issueops/ready_work.go +++ b/internal/storage/issueops/ready_work.go @@ -39,7 +39,7 @@ func buildReadyWorkOrder(policy types.SortPolicy) sqlbuild.ReadyWorkOrder { // buildReadyWorkPredicates computes the ID sets the ready-work WHERE clause // needs (children of deferred parents, parent descendants), then delegates // the clause text to sqlbuild so both stacks share ready semantics. -func buildReadyWorkPredicates(ctx context.Context, tx *sql.Tx, filter types.WorkFilter, tables FilterTables) (*readyWorkPredicates, error) { +func buildReadyWorkPredicates(ctx context.Context, tx DBTX, filter types.WorkFilter, tables FilterTables) (*readyWorkPredicates, error) { var inputs sqlbuild.ReadyWorkWhereInputs if !filter.IncludeDeferred { deferredChildIDs, dcErr := getChildrenOfDeferredParentsInTx(ctx, tx) @@ -85,7 +85,7 @@ func buildReadyWorkPredicates(ctx context.Context, tx *sql.Tx, filter types.Work //nolint:gosec // G201: whereSQL/orderBySQL built from hardcoded strings and ? placeholders func GetReadyWorkInTx( ctx context.Context, - tx *sql.Tx, + tx DBTX, filter types.WorkFilter, ) ([]*types.Issue, error) { preds, err := buildReadyWorkPredicates(ctx, tx, filter, IssuesFilterTables) @@ -153,7 +153,7 @@ func mergeReadyWisps(ordered []*types.Issue, wisps []*types.Issue, filter types. return ordered, nil } -func getReadyWispsInTx(ctx context.Context, tx *sql.Tx, filter types.WorkFilter, deferredChildIDs []string) ([]*types.Issue, error) { +func getReadyWispsInTx(ctx context.Context, tx DBTX, filter types.WorkFilter, deferredChildIDs []string) ([]*types.Issue, error) { empty, err := wispsTableEmptyOrMissingInTx(ctx, tx) if err != nil { return nil, fmt.Errorf("search wisps (ready work): probe: %w", err) @@ -211,7 +211,7 @@ func getReadyWispsInTx(ctx context.Context, tx *sql.Tx, filter types.WorkFilter, return ready, nil } -func queryReadyWispIssueIDPage(ctx context.Context, tx *sql.Tx, filter types.IssueFilter, excludeDeferred bool, orderBy sqlbuild.ReadyWorkOrder, limit, offset int) ([]string, error) { +func queryReadyWispIssueIDPage(ctx context.Context, tx DBTX, filter types.IssueFilter, excludeDeferred bool, orderBy sqlbuild.ReadyWorkOrder, limit, offset int) ([]string, error) { plan := sqlbuild.BuildLabelDrivenSearch(filter, WispsFilterTables) whereClauses, args, err := BuildIssueFilterClauses("", plan.Filter, WispsFilterTables) if err != nil { @@ -256,7 +256,7 @@ func queryReadyWispIssueIDPage(ctx context.Context, tx *sql.Tx, filter types.Iss return ids, nil } -func getWispIssuesByIDsInOrderInTx(ctx context.Context, tx *sql.Tx, ids []string) ([]*types.Issue, error) { +func getWispIssuesByIDsInOrderInTx(ctx context.Context, tx DBTX, ids []string) ([]*types.Issue, error) { if len(ids) == 0 { return nil, nil } @@ -327,7 +327,7 @@ func readyWorkWispIssueFilter(filter types.WorkFilter) types.IssueFilter { return wispFilter } -func filterReadyWispsInTx(ctx context.Context, tx *sql.Tx, filter types.WorkFilter, wisps []*types.Issue, deferredChildIDs []string) ([]*types.Issue, error) { +func filterReadyWispsInTx(ctx context.Context, tx DBTX, filter types.WorkFilter, wisps []*types.Issue, deferredChildIDs []string) ([]*types.Issue, error) { if len(wisps) == 0 { return wisps, nil } @@ -459,7 +459,7 @@ func issueCreatedBefore(a, b *types.Issue) bool { return a.ID < b.ID } -func queryReadyIssueIDPage(ctx context.Context, tx *sql.Tx, query string, args []interface{}) ([]string, error) { +func queryReadyIssueIDPage(ctx context.Context, tx DBTX, query string, args []interface{}) ([]string, error) { rows, err := tx.QueryContext(ctx, query, args...) if err != nil { return nil, fmt.Errorf("failed to get ready work: %w", err) @@ -485,7 +485,7 @@ func queryReadyIssueIDPage(ctx context.Context, tx *sql.Tx, query string, args [ // future defer_until. Works within an existing transaction. // //nolint:gosec // G201: depTable is selected from a hardcoded list below. -func getChildrenOfDeferredParentsInTx(ctx context.Context, tx *sql.Tx) ([]string, error) { +func getChildrenOfDeferredParentsInTx(ctx context.Context, tx DBTX) ([]string, error) { hasDeferredParent := false for _, issueTable := range []string{"issues", "wisps"} { //nolint:gosec // G201: issueTable is hardcoded to "issues" or "wisps" @@ -554,7 +554,7 @@ func getChildrenOfDeferredParentsInTx(ctx context.Context, tx *sql.Tx) ([]string } //nolint:gosec // G201: depTable is hardcoded to "dependencies" or "wisp_dependencies" -func getParentedIDSetInTx(ctx context.Context, tx *sql.Tx, issueIDs []string) (map[string]struct{}, error) { +func getParentedIDSetInTx(ctx context.Context, tx DBTX, issueIDs []string) (map[string]struct{}, error) { parented := make(map[string]struct{}) if len(issueIDs) == 0 { return parented, nil diff --git a/internal/storage/issueops/search.go b/internal/storage/issueops/search.go index dcaa55712..e6620313f 100644 --- a/internal/storage/issueops/search.go +++ b/internal/storage/issueops/search.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "strings" @@ -16,7 +15,7 @@ import ( // // Set filter.SkipWisps=true for callers that never need ephemeral results; this // avoids the unconditional full-table wisps scan (Q2 perf opt). -func SearchIssuesInTx(ctx context.Context, tx *sql.Tx, query string, filter types.IssueFilter) ([]*types.Issue, error) { +func SearchIssuesInTx(ctx context.Context, tx DBTX, query string, filter types.IssueFilter) ([]*types.Issue, error) { // Route ephemeral-only queries to wisps table. if filter.Ephemeral != nil && *filter.Ephemeral { results, err := searchTableInTx(ctx, tx, query, filter, WispsFilterTables) @@ -81,7 +80,7 @@ func SearchIssuesInTx(ctx context.Context, tx *sql.Tx, query string, filter type // SELECT id scan + batch hydration instead of a full 47-column projection scan. // Pattern B is equivalent to Pattern A but faster on large corpora where most rows // are never needed (mirrors the pattern in scanIssueIDs and GetStaleIssuesInTx). -func searchTableInTx(ctx context.Context, tx *sql.Tx, query string, filter types.IssueFilter, tables FilterTables) ([]*types.Issue, error) { +func searchTableInTx(ctx context.Context, tx DBTX, query string, filter types.IssueFilter, tables FilterTables) ([]*types.Issue, error) { plan := sqlbuild.BuildLabelDrivenSearch(filter, tables) whereClauses, args, err := BuildIssueFilterClauses(query, plan.Filter, tables) if err != nil { @@ -147,7 +146,7 @@ func searchTableInTx(ctx context.Context, tx *sql.Tx, query string, filter types // searchTablePatternB runs Pattern B: SELECT id LIMIT n โ†’ batch hydrate. // Equivalent result to Pattern A but avoids streaming all 47 columns for rows // that won't survive the LIMIT cut. Mirrors the approach in GetStaleIssuesInTx. -func searchTablePatternB(ctx context.Context, tx *sql.Tx, fromSQL, whereSQL string, args []interface{}, filter types.IssueFilter, tables FilterTables, labelDriven bool) ([]*types.Issue, error) { +func searchTablePatternB(ctx context.Context, tx DBTX, fromSQL, whereSQL string, args []interface{}, filter types.IssueFilter, tables FilterTables, labelDriven bool) ([]*types.Issue, error) { idSelect := "SELECT " if labelDriven { idSelect = "SELECT DISTINCT " @@ -228,7 +227,7 @@ func searchTablePatternB(ctx context.Context, tx *sql.Tx, fromSQL, whereSQL stri // hydrateIssues populates labels (and optionally dependencies) on a slice of issues. // All issues must belong to tables.Main; labels come from tables.Labels. // When skipLabels is true, label hydration is suppressed (Issue.Labels is left nil). -func hydrateIssues(ctx context.Context, tx *sql.Tx, issues []*types.Issue, tables FilterTables, includeDeps bool, skipLabels bool) error { +func hydrateIssues(ctx context.Context, tx DBTX, issues []*types.Issue, tables FilterTables, includeDeps bool, skipLabels bool) error { if len(issues) == 0 { return nil } diff --git a/internal/storage/issueops/statistics.go b/internal/storage/issueops/statistics.go index 0e36a1617..31f199cfd 100644 --- a/internal/storage/issueops/statistics.go +++ b/internal/storage/issueops/statistics.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "fmt" "github.com/steveyegge/beads/internal/types" @@ -12,7 +11,7 @@ import ( // InProgressIssues, ClosedIssues, DeferredIssues, PinnedIssues) of stats from // the issues table. It does NOT compute BlockedIssues or ReadyIssues โ€” callers // fill those in using their own blocked-ID computation strategy. -func ScanIssueCountsInTx(ctx context.Context, tx *sql.Tx, stats *types.Statistics) error { +func ScanIssueCountsInTx(ctx context.Context, tx DBTX, stats *types.Statistics) error { if err := tx.QueryRowContext(ctx, ` SELECT COUNT(*) AS total, diff --git a/internal/storage/issueops/update.go b/internal/storage/issueops/update.go index 618f3ea20..6eed49e9e 100644 --- a/internal/storage/issueops/update.go +++ b/internal/storage/issueops/update.go @@ -2,7 +2,6 @@ package issueops import ( "context" - "database/sql" "encoding/json" "fmt" "strings" @@ -125,18 +124,18 @@ type UpdateResult struct { // The caller is responsible for Dolt versioning (DOLT_ADD/COMMIT) if needed. // //nolint:gosec // G201: table names come from WispTableRouting (hardcoded constants) -func UpdateIssueInTx(ctx context.Context, tx *sql.Tx, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) { +func UpdateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) { return updateIssueInTx(ctx, tx, id, updates, actor, true) } // UpdateIssueWithoutEventInTx applies normal update semantics without recording // an intermediate event. Demotion uses this to preserve the historical event // stream: create/update history is copied, then a single demotion event is added. -func UpdateIssueWithoutEventInTx(ctx context.Context, tx *sql.Tx, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) { +func UpdateIssueWithoutEventInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string) (*UpdateResult, error) { return updateIssueInTx(ctx, tx, id, updates, actor, false) } -func updateIssueInTx(ctx context.Context, tx *sql.Tx, id string, updates map[string]interface{}, actor string, recordEvent bool) (*UpdateResult, error) { +func updateIssueInTx(ctx context.Context, tx DBTX, id string, updates map[string]interface{}, actor string, recordEvent bool) (*UpdateResult, error) { // Route to correct table. isWisp := IsActiveWispInTx(ctx, tx, id) issueTable, _, eventTable, _ := WispTableRouting(isWisp) @@ -267,7 +266,7 @@ func updateIssueInTx(ctx context.Context, tx *sql.Tx, id string, updates map[str // RecordFullEventInTable records an event with both old and new values. // //nolint:gosec // G201: table is from WispTableRouting ("events" or "wisp_events") -func RecordFullEventInTable(ctx context.Context, tx *sql.Tx, table, issueID string, eventType types.EventType, actor, oldValue, newValue string) error { +func RecordFullEventInTable(ctx context.Context, tx DBTX, table, issueID string, eventType types.EventType, actor, oldValue, newValue string) error { _, err := tx.ExecContext(ctx, fmt.Sprintf(` INSERT INTO %s (id, issue_id, event_type, actor, old_value, new_value) VALUES (?, ?, ?, ?, ?, ?)