From 33bf01144a690e94548e0cb3a9e5932520f9df7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?coffeegoddd=E2=98=95=EF=B8=8F=E2=9C=A8?= Date: Tue, 14 Jul 2026 16:01:20 -0700 Subject: [PATCH] /cmd/bd: support more commands --- cmd/bd/assign.go | 13 +- cmd/bd/children.go | 3 - cmd/bd/edit.go | 7 +- cmd/bd/edit_proxied_server.go | 140 +++++++ ...field_mutation_proxied_integration_test.go | 176 ++++++++ cmd/bd/gate.go | 7 +- cmd/bd/gate_proxied_server.go | 67 ++++ cmd/bd/link.go | 7 +- cmd/bd/link_proxied_server.go | 67 ++++ cmd/bd/mutate_proxied_server.go | 140 +++++++ cmd/bd/note.go | 7 +- cmd/bd/priority.go | 7 +- cmd/bd/quick.go | 7 +- cmd/bd/quick_proxied_server.go | 60 +++ cmd/bd/quick_todo_proxied_integration_test.go | 119 ++++++ cmd/bd/relational_proxied_integration_test.go | 112 ++++++ cmd/bd/search.go | 7 +- cmd/bd/search_proxied_integration_test.go | 379 ++++++++++++++++++ cmd/bd/search_proxied_server.go | 218 ++++++++++ cmd/bd/state.go | 14 +- cmd/bd/state_proxied_integration_test.go | 102 +++++ cmd/bd/state_proxied_server.go | 110 +++++ cmd/bd/tag.go | 7 +- cmd/bd/todo.go | 36 +- cmd/bd/todo_proxied_server.go | 132 ++++++ 25 files changed, 1890 insertions(+), 54 deletions(-) create mode 100644 cmd/bd/edit_proxied_server.go create mode 100644 cmd/bd/field_mutation_proxied_integration_test.go create mode 100644 cmd/bd/gate_proxied_server.go create mode 100644 cmd/bd/link_proxied_server.go create mode 100644 cmd/bd/mutate_proxied_server.go create mode 100644 cmd/bd/quick_proxied_server.go create mode 100644 cmd/bd/quick_todo_proxied_integration_test.go create mode 100644 cmd/bd/relational_proxied_integration_test.go create mode 100644 cmd/bd/search_proxied_integration_test.go create mode 100644 cmd/bd/search_proxied_server.go create mode 100644 cmd/bd/state_proxied_integration_test.go create mode 100644 cmd/bd/state_proxied_server.go create mode 100644 cmd/bd/todo_proxied_server.go diff --git a/cmd/bd/assign.go b/cmd/bd/assign.go index 1cd0a23ef..1e1e15214 100644 --- a/cmd/bd/assign.go +++ b/cmd/bd/assign.go @@ -24,14 +24,8 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("assign is not supported in proxied-server mode") - } CheckReadonly("assign") - id := args[0] - assignee := args[1] - evt := metrics.NewCommandEvent("assign") defer func() { if c := metrics.Global(); c != nil { @@ -39,6 +33,13 @@ Examples: } }() + if usesProxiedServer() { + return runAssignProxiedServer(rootCtx, args) + } + + id := args[0] + assignee := args[1] + ctx := rootCtx result, err := resolveAndGetIssueForMutation(ctx, store, id) diff --git a/cmd/bd/children.go b/cmd/bd/children.go index 754ab430e..434230f6b 100644 --- a/cmd/bd/children.go +++ b/cmd/bd/children.go @@ -24,9 +24,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("children is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("children") defer func() { if c := metrics.Global(); c != nil { diff --git a/cmd/bd/edit.go b/cmd/bd/edit.go index 4c5a3c651..786927550 100644 --- a/cmd/bd/edit.go +++ b/cmd/bd/edit.go @@ -30,9 +30,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("edit is not supported in proxied-server mode") - } CheckReadonly("edit") evt := metrics.NewCommandEvent("edit") @@ -42,6 +39,10 @@ Examples: } }() + if usesProxiedServer() { + return runEditProxiedServer(cmd, rootCtx, args) + } + id := args[0] ctx := rootCtx diff --git a/cmd/bd/edit_proxied_server.go b/cmd/bd/edit_proxied_server.go new file mode 100644 index 000000000..10bd681fb --- /dev/null +++ b/cmd/bd/edit_proxied_server.go @@ -0,0 +1,140 @@ +package main + +import ( + "context" + "fmt" + "os" + "os/exec" + "strings" + + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/ui" +) + +func runEditProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + id := args[0] + + fieldToEdit := "description" + switch { + case cmd.Flags().Changed("title"): + fieldToEdit = "title" + case cmd.Flags().Changed("design"): + fieldToEdit = "design" + case cmd.Flags().Changed("notes"): + fieldToEdit = "notes" + case cmd.Flags().Changed("acceptance"): + fieldToEdit = "acceptance_criteria" + } + + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return err + } + issue, _, err := proxiedGetIssueOrWisp(ctx, uw, id) + if err != nil { + uw.Close(ctx) + return HandleErrorRespectJSON("resolving %s: %v", id, err) + } + if issue == nil { + uw.Close(ctx) + return HandleErrorRespectJSON("issue %s not found", id) + } + uw.Close(ctx) + id = issue.ID + + var currentValue string + switch fieldToEdit { + case "title": + currentValue = issue.Title + case "description": + currentValue = issue.Description + case "design": + currentValue = issue.Design + case "notes": + currentValue = issue.Notes + case "acceptance_criteria": + currentValue = issue.AcceptanceCriteria + } + + editor := os.Getenv("EDITOR") + if editor == "" { + editor = os.Getenv("VISUAL") + } + if editor == "" { + for _, defaultEditor := range []string{"vim", "vi", "nano", "emacs"} { + if _, err := exec.LookPath(defaultEditor); err == nil { + editor = defaultEditor + break + } + } + } + if editor == "" { + return HandleErrorRespectJSON("no editor found. Set $EDITOR or $VISUAL environment variable") + } + + tmpFile, err := os.CreateTemp("", fmt.Sprintf("bd-edit-%s-*.txt", fieldToEdit)) + if err != nil { + return HandleErrorRespectJSON("creating temp file: %v", err) + } + tmpPath := tmpFile.Name() + editSaved := false + defer func() { + if editSaved { + _ = os.Remove(tmpPath) + } + }() + + if _, err := tmpFile.WriteString(currentValue); err != nil { + _ = tmpFile.Close() + return HandleErrorRespectJSON("writing to temp file: %v", err) + } + _ = tmpFile.Close() + + editorParts := strings.Fields(editor) + editorArgs := append(editorParts[1:], tmpPath) + editorCmd := exec.Command(editorParts[0], editorArgs...) //nolint:gosec // G204: editor from trusted $EDITOR/$VISUAL env or known defaults + editorCmd.Stdin = os.Stdin + editorCmd.Stdout = os.Stdout + editorCmd.Stderr = os.Stderr + if err := editorCmd.Run(); err != nil { + return HandleErrorRespectJSON("running editor: %v", err) + } + + // #nosec G304 -- tmpPath was created earlier in this function + editedContent, err := os.ReadFile(tmpPath) + if err != nil { + return HandleErrorRespectJSON("reading edited file: %v", err) + } + + newValue := strings.TrimSpace(string(editedContent)) + + if newValue == currentValue { + editSaved = true + fmt.Println("No changes made") + return nil + } + + if fieldToEdit == "title" && newValue == "" { + return HandleErrorRespectJSON("title cannot be empty") + } + + updated, err := proxiedUpdateIssueFields(ctx, id, "bd: edit "+id, map[string]any{fieldToEdit: newValue}) + if err != nil { + fmt.Fprintf(os.Stderr, "Your edits are preserved in: %s\n", tmpPath) //nolint:gosec // G705: stderr, not a browser context + return HandleErrorRespectJSON("updating issue: %v", err) + } + editSaved = true + + displayTitle := issue.Title + if fieldToEdit == "title" { + displayTitle = newValue + } + if updated != nil { + displayTitle = updated.Title + } + + fieldName := strings.ReplaceAll(fieldToEdit, "_", " ") + fmt.Printf("%s Updated %s for issue: %s\n", ui.RenderPass("✓"), fieldName, formatFeedbackID(id, displayTitle)) + return nil +} diff --git a/cmd/bd/field_mutation_proxied_integration_test.go b/cmd/bd/field_mutation_proxied_integration_test.go new file mode 100644 index 000000000..2f9dca79a --- /dev/null +++ b/cmd/bd/field_mutation_proxied_integration_test.go @@ -0,0 +1,176 @@ +//go:build cgo + +package main + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func bdProxiedRunEnv(t *testing.T, bd, dir string, extraEnv []string, args ...string) (string, string, error) { + t.Helper() + cmd := exec.Command(bd, args...) + cmd.Dir = dir + cmd.Env = append(bdProxiedEnv(dir), extraEnv...) + var stdout, stderr bytes.Buffer + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err := cmd.Run() + return stdout.String(), stderr.String(), err +} + +func TestProxiedServerAssign(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("assign_then_unassign", func(t *testing.T) { + p := bdProxiedInit(t, bd, "as") + issue := bdProxiedCreate(t, bd, p.dir, "Assign target") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "assign", issue.ID, "alice") + if err != nil { + t.Fatalf("assign failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, "Assigned") { + t.Errorf("expected 'Assigned' confirmation, got:\n%s", out) + } + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Assignee != "alice" { + t.Errorf("assignee = %q, want alice", got.Assignee) + } + + out, _, err = bdProxiedRunBuffers(t, bd, p.dir, "assign", issue.ID, "") + if err != nil { + t.Fatalf("unassign failed: %v", err) + } + if !strings.Contains(out, "Unassigned") { + t.Errorf("expected 'Unassigned' confirmation, got:\n%s", out) + } + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Assignee != "" { + t.Errorf("assignee after unassign = %q, want empty", got.Assignee) + } + }) + + t.Run("assign_missing_issue_fails", func(t *testing.T) { + p := bdProxiedInit(t, bd, "am") + _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "assign", "as-nope99", "alice") + if err == nil { + t.Error("expected assign of missing issue to fail") + } + }) +} + +func TestProxiedServerPriority(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + p := bdProxiedInit(t, bd, "pr") + issue := bdProxiedCreate(t, bd, p.dir, "Priority target", "--priority", "3") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "priority", issue.ID, "0") + if err != nil { + t.Fatalf("priority failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, "P0") { + t.Errorf("expected 'P0' in output, got:\n%s", out) + } + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Priority != 0 { + t.Errorf("priority = %d, want 0", got.Priority) + } +} + +func TestProxiedServerNote(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + p := bdProxiedInit(t, bd, "nt") + issue := bdProxiedCreate(t, bd, p.dir, "Note target") + + if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "note", issue.ID, "first note"); err != nil { + t.Fatalf("note failed: %v\nstderr:\n%s", err, stderr) + } + if _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "note", issue.ID, "second note"); err != nil { + t.Fatalf("second note failed: %v", err) + } + + got := bdProxiedShow(t, bd, p.dir, issue.ID) + if !strings.Contains(got.Notes, "first note") || !strings.Contains(got.Notes, "second note") { + t.Errorf("notes = %q, want both notes appended", got.Notes) + } + if strings.Index(got.Notes, "first note") > strings.Index(got.Notes, "second note") { + t.Errorf("notes appended out of order: %q", got.Notes) + } +} + +func TestProxiedServerTag(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("tag_issue", func(t *testing.T) { + p := bdProxiedInit(t, bd, "tg") + issue := bdProxiedCreate(t, bd, p.dir, "Tag target") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "tag", issue.ID, "needs-review") + if err != nil { + t.Fatalf("tag failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, "needs-review") { + t.Errorf("expected label in output, got:\n%s", out) + } + + db := openProxiedDB(t, p) + labels := getProxiedLabels(t, db, issue.ID) + if len(labels) != 1 || labels[0] != "needs-review" { + t.Errorf("persisted labels = %v, want [needs-review]", labels) + } + }) + + t.Run("tag_wisp_routes_to_wisp_labels", func(t *testing.T) { + p := bdProxiedInit(t, bd, "tw") + wisp := bdProxiedCreate(t, bd, p.dir, "Tag wisp", "--ephemeral") + + if _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "tag", wisp.ID, "wtag"); err != nil { + t.Fatalf("tag wisp failed: %v", err) + } + + db := openProxiedDB(t, p) + var wispCount, permCount int + if err := db.QueryRow("SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ?", wisp.ID).Scan(&wispCount); err != nil { + t.Fatalf("count wisp_labels: %v", err) + } + if err := db.QueryRow("SELECT COUNT(*) FROM labels WHERE issue_id = ?", wisp.ID).Scan(&permCount); err != nil { + t.Fatalf("count labels: %v", err) + } + if wispCount != 1 || permCount != 0 { + t.Errorf("wisp tag routing: wisp_labels=%d labels=%d, want 1/0", wispCount, permCount) + } + }) +} + +func TestProxiedServerEdit(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + p := bdProxiedInit(t, bd, "ed") + issue := bdProxiedCreate(t, bd, p.dir, "Edit target", "--description", "original body") + + editorScript := filepath.Join(p.dir, "editor.sh") + if err := os.WriteFile(editorScript, []byte("#!/bin/sh\nprintf 'edited via proxied editor' > \"$1\"\n"), 0o755); err != nil { + t.Fatalf("write editor script: %v", err) + } + env := []string{"EDITOR=" + editorScript, "VISUAL="} + + out, stderr, err := bdProxiedRunEnv(t, bd, p.dir, env, "edit", issue.ID) + if err != nil { + t.Fatalf("edit failed: %v\nstdout:\n%s\nstderr:\n%s", err, out, stderr) + } + if !strings.Contains(out, "Updated description") { + t.Errorf("expected 'Updated description' output, got:\n%s", out) + } + if got := bdProxiedShow(t, bd, p.dir, issue.ID); got.Description != "edited via proxied editor" { + t.Errorf("description = %q, want edited value", got.Description) + } +} diff --git a/cmd/bd/gate.go b/cmd/bd/gate.go index 57073a10c..9b9585f5d 100644 --- a/cmd/bd/gate.go +++ b/cmd/bd/gate.go @@ -58,9 +58,6 @@ By default, shows only open gates. Use --all to include closed gates.`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("gate list is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("gate-list") defer func() { if c := metrics.Global(); c != nil { @@ -68,6 +65,10 @@ By default, shows only open gates. Use --all to include closed gates.`, } }() + if usesProxiedServer() { + return runGateListProxiedServer(cmd, rootCtx, args) + } + allFlag, _ := cmd.Flags().GetBool("all") limit, _ := cmd.Flags().GetInt("limit") diff --git a/cmd/bd/gate_proxied_server.go b/cmd/bd/gate_proxied_server.go new file mode 100644 index 000000000..d91b08c48 --- /dev/null +++ b/cmd/bd/gate_proxied_server.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + + "github.com/spf13/cobra" + + "github.com/steveyegge/beads/internal/storage/domain" + "github.com/steveyegge/beads/internal/types" +) + +func runGateListProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + allFlag, _ := cmd.Flags().GetBool("all") + limit, _ := cmd.Flags().GetInt("limit") + + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return err + } + defer uw.Close(ctx) + + if len(args) == 1 { + target, isWisp, err := proxiedGetIssueOrWisp(ctx, uw, args[0]) + if err != nil || target == nil { + return HandleErrorRespectJSON("issue not found: %s", args[0]) + } + var metas []*types.IssueWithDependencyMetadata + if isWisp { + metas, err = uw.DependencyUseCase().ListWispWithIssueMetadata(ctx, target.ID, domain.DepListFilter{Direction: domain.DepDirectionOut}) + } else { + metas, err = uw.DependencyUseCase().ListWithIssueMetadata(ctx, target.ID, domain.DepListFilter{Direction: domain.DepDirectionOut}) + } + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + deps := make([]*types.Issue, 0, len(metas)) + for _, m := range metas { + if m != nil { + deps = append(deps, &m.Issue) + } + } + gates := filterIssueGates(deps, allFlag, limit) + if jsonOutput { + return outputJSON(gates) + } + displayGates(gates, allFlag) + return nil + } + + gateType := types.IssueType("gate") + filter := types.IssueFilter{ + IssueType: &gateType, + Limit: limit, + } + if !allFlag { + filter.ExcludeStatus = []types.Status{types.StatusClosed} + } + page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + if jsonOutput { + return outputJSON(page.Items) + } + displayGates(page.Items, allFlag) + return nil +} diff --git a/cmd/bd/link.go b/cmd/bd/link.go index 1911402cb..e23bd4471 100644 --- a/cmd/bd/link.go +++ b/cmd/bd/link.go @@ -26,9 +26,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("link is not supported in proxied-server mode") - } CheckReadonly("link") evt := metrics.NewCommandEvent("link") @@ -38,6 +35,10 @@ Examples: } }() + if usesProxiedServer() { + return runLinkProxiedServer(cmd, rootCtx, args) + } + id1 := args[0] id2 := args[1] depType, _ := cmd.Flags().GetString("type") diff --git a/cmd/bd/link_proxied_server.go b/cmd/bd/link_proxied_server.go new file mode 100644 index 000000000..a59a6795c --- /dev/null +++ b/cmd/bd/link_proxied_server.go @@ -0,0 +1,67 @@ +package main + +import ( + "context" + "fmt" + + "github.com/spf13/cobra" + + "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 runLinkProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + id1 := args[0] + id2 := args[1] + depType, _ := cmd.Flags().GetString("type") + + if isChildOf(id1, id2) { + return HandleErrorRespectJSON("cannot add dependency: %s is already a child of %s. Children inherit dependency on parent completion via hierarchy. Adding an explicit dependency would create a deadlock", id1, id2) + } + + dt := types.DependencyType(depType) + if !dt.IsValid() { + return HandleErrorRespectJSON("invalid dependency type %q: must be non-empty and at most 50 characters", depType) + } + + if uowProvider == nil { + return HandleErrorRespectJSON("proxied-server UOW provider not initialized") + } + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (depAddResult, string, error) { + dep := &types.Dependency{IssueID: id1, DependsOnID: id2, Type: dt} + if _, err := uw.DependencyUseCase().AddDependencies(ctx, []*types.Dependency{dep}, actor, domain.BulkAddDepsOpts{}); err != nil { + return depAddResult{}, "", err + } + cycles, cycleErr := uw.DependencyUseCase().DetectCycles(ctx) + return depAddResult{ + fromTitle: proxiedLookupTitle(ctx, uw, id1), + toTitle: proxiedLookupTitle(ctx, uw, id2), + cycles: cycles, + cycleErr: cycleErr, + }, fmt.Sprintf("bd: link %s %s", id1, id2), nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + printCycleDetectionError(res.cycleErr) + printCycleWarnings(res.cycles) + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "status": "added", + "issue_id": id1, + "depends_on_id": id2, + "type": depType, + }) + } + fmt.Printf("%s Linked: %s depends on %s (%s)\n", + ui.RenderPass("✓"), + formatFeedbackIDParen(id1, res.fromTitle), + formatFeedbackIDParen(id2, res.toTitle), + depType) + return nil +} diff --git a/cmd/bd/mutate_proxied_server.go b/cmd/bd/mutate_proxied_server.go new file mode 100644 index 000000000..ce43ffa54 --- /dev/null +++ b/cmd/bd/mutate_proxied_server.go @@ -0,0 +1,140 @@ +package main + +import ( + "context" + "fmt" + + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/ui" + "github.com/steveyegge/beads/internal/validation" +) + +func proxiedMutateIssue(ctx context.Context, id, commitMsg string, mutate func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error) (*types.Issue, error) { + if uowProvider == nil { + return nil, fmt.Errorf("proxied-server UOW provider not initialized") + } + var updated *types.Issue + err := uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) { + issue, isWisp := proxiedResolveIssueOrWisp(ctx, uw, id) + if issue == nil { + return "", fmt.Errorf("issue %s not found", id) + } + if err := validateIssueUpdatable(id, issue); err != nil { + return "", err + } + if err := mutate(ctx, uw, issue, isWisp); err != nil { + return "", err + } + if isWisp { + updated, _ = uw.IssueUseCase().GetWisp(ctx, issue.ID) + } else { + updated, _ = uw.IssueUseCase().GetIssue(ctx, issue.ID) + } + return commitMsg, nil + }) + if err != nil { + return nil, err + } + commandDidWrite.Store(true) + return updated, nil +} + +func proxiedUpdateIssueFields(ctx context.Context, id, commitMsg string, updates map[string]any) (*types.Issue, error) { + return proxiedMutateIssue(ctx, id, commitMsg, func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error { + if isWisp { + return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, actor) + } + return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, actor) + }) +} + +func runAssignProxiedServer(ctx context.Context, args []string) error { + id := args[0] + assignee := args[1] + updated, err := proxiedUpdateIssueFields(ctx, id, "bd: assign "+id, map[string]any{"assignee": assignee}) + if err != nil { + return HandleErrorRespectJSON("assign %s: %v", id, err) + } + if jsonOutput { + if updated != nil { + return outputJSON(updated) + } + return nil + } + title := issueTitleOrEmpty(updated) + if assignee == "" { + fmt.Printf("%s Unassigned %s\n", ui.RenderPass("✓"), formatFeedbackID(id, title)) + } else { + fmt.Printf("%s Assigned %s to %s\n", ui.RenderPass("✓"), formatFeedbackID(id, title), assignee) + } + return nil +} + +func runPriorityProxiedServer(ctx context.Context, args []string) error { + id := args[0] + priority, err := validation.ValidatePriority(args[1]) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + updated, err := proxiedUpdateIssueFields(ctx, id, "bd: priority "+id, map[string]any{"priority": priority}) + if err != nil { + return HandleErrorRespectJSON("priority %s: %v", id, err) + } + if jsonOutput { + if updated != nil { + return outputJSON(updated) + } + return nil + } + fmt.Printf("%s Set priority of %s to P%d\n", ui.RenderPass("✓"), formatFeedbackID(id, issueTitleOrEmpty(updated)), priority) + return nil +} + +func runNoteProxiedServer(ctx context.Context, id, noteText string) error { + updated, err := proxiedMutateIssue(ctx, id, "bd: note "+id, func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error { + combined := issue.Notes + if combined != "" { + combined += "\n" + } + combined += noteText + updates := map[string]any{"notes": combined} + if isWisp { + return uw.IssueUseCase().UpdateWisp(ctx, issue.ID, updates, actor) + } + return uw.IssueUseCase().UpdateIssue(ctx, issue.ID, updates, actor) + }) + if err != nil { + return HandleErrorRespectJSON("note %s: %v", id, err) + } + if jsonOutput { + if updated != nil { + return outputJSON(updated) + } + return nil + } + fmt.Printf("%s Note added to %s\n", ui.RenderPass("✓"), formatFeedbackID(id, issueTitleOrEmpty(updated))) + return nil +} + +func runTagProxiedServer(ctx context.Context, args []string) error { + id := args[0] + label := args[1] + updated, err := proxiedMutateIssue(ctx, id, "bd: tag "+id, func(ctx context.Context, uw uow.UnitOfWork, issue *types.Issue, isWisp bool) error { + if isWisp { + return uw.LabelUseCase().AddWispLabel(ctx, issue.ID, label, actor) + } + return uw.LabelUseCase().AddLabel(ctx, issue.ID, label, actor) + }) + if err != nil { + return HandleErrorRespectJSON("tag %s: %v", id, err) + } + if jsonOutput { + if updated != nil { + return outputJSON(updated) + } + return nil + } + fmt.Printf("%s Added label %q to %s\n", ui.RenderPass("✓"), label, formatFeedbackID(id, issueTitleOrEmpty(updated))) + return nil +} diff --git a/cmd/bd/note.go b/cmd/bd/note.go index 396b764ac..2d0a42a13 100644 --- a/cmd/bd/note.go +++ b/cmd/bd/note.go @@ -28,9 +28,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("note is not supported in proxied-server mode") - } CheckReadonly("note") evt := metrics.NewCommandEvent("note") @@ -70,6 +67,10 @@ Examples: return HandleErrorRespectJSON("note text is empty") } + if usesProxiedServer() { + return runNoteProxiedServer(rootCtx, id, noteText) + } + ctx := rootCtx result, err := resolveAndGetIssueForMutation(ctx, store, id) diff --git a/cmd/bd/priority.go b/cmd/bd/priority.go index ef354015c..481afecec 100644 --- a/cmd/bd/priority.go +++ b/cmd/bd/priority.go @@ -31,9 +31,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("priority is not supported in proxied-server mode") - } CheckReadonly("priority") evt := metrics.NewCommandEvent("priority") @@ -43,6 +40,10 @@ Examples: } }() + if usesProxiedServer() { + return runPriorityProxiedServer(rootCtx, args) + } + id := args[0] priorityStr := args[1] diff --git a/cmd/bd/quick.go b/cmd/bd/quick.go index 8c9faf3ac..0273e1a32 100644 --- a/cmd/bd/quick.go +++ b/cmd/bd/quick.go @@ -28,9 +28,6 @@ Example: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("q is not supported in proxied-server mode") - } // Create the event before the readonly guard so the operation label // matches this command ("q", not "create") and the readonly exit path // still flushes queued metrics via CheckReadonly's CloseAndFlush. @@ -43,6 +40,10 @@ Example: CheckReadonly("q") + if usesProxiedServer() { + return runQuickProxiedServer(cmd, rootCtx, args) + } + title := strings.Join(args, " ") priorityStr, _ := cmd.Flags().GetString("priority") diff --git a/cmd/bd/quick_proxied_server.go b/cmd/bd/quick_proxied_server.go new file mode 100644 index 000000000..8763cc9c4 --- /dev/null +++ b/cmd/bd/quick_proxied_server.go @@ -0,0 +1,60 @@ +package main + +import ( + "context" + "fmt" + "strings" + + "github.com/spf13/cobra" + + "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/validation" +) + +func runQuickProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + title := strings.Join(args, " ") + + priorityStr, _ := cmd.Flags().GetString("priority") + issueType, _ := cmd.Flags().GetString("type") + labels, _ := cmd.Flags().GetStringSlice("labels") + parentID, _ := cmd.Flags().GetString("parent") + + priority, err := validation.ValidatePriority(priorityStr) + if err != nil { + return HandleError("%v", err) + } + + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + issue := &types.Issue{ + Title: title, + Status: types.StatusOpen, + Priority: priority, + IssueType: types.IssueType(issueType).Normalize(), + } + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*types.Issue, string, error) { + params := domain.CreateIssueParams{ + Issue: issue, + ParentID: parentID, + Labels: labels, + InheritLabelsFromParent: parentID != "", + } + result, err := uw.IssueUseCase().CreateIssue(ctx, params, actor) + if err != nil { + return nil, "", err + } + return result.Issue, fmt.Sprintf("bd: create %s", result.Issue.ID), nil + }) + if err != nil { + return HandleError("%v", err) + } + commandDidWrite.Store(true) + + fmt.Println(res.ID) + return nil +} diff --git a/cmd/bd/quick_todo_proxied_integration_test.go b/cmd/bd/quick_todo_proxied_integration_test.go new file mode 100644 index 000000000..4e88247ae --- /dev/null +++ b/cmd/bd/quick_todo_proxied_integration_test.go @@ -0,0 +1,119 @@ +//go:build cgo + +package main + +import ( + "strings" + "testing" +) + +func TestProxiedServerQuick(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("q_creates_and_outputs_id", func(t *testing.T) { + p := bdProxiedInit(t, bd, "qk") + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "q", "Quick captured task") + if err != nil { + t.Fatalf("q failed: %v\nstderr:\n%s", err, stderr) + } + id := strings.TrimSpace(stdout) + if id == "" { + t.Fatal("q produced no ID") + } + got := bdProxiedShow(t, bd, p.dir, id) + if got.Title != "Quick captured task" { + t.Errorf("title = %q, want 'Quick captured task'", got.Title) + } + }) + + t.Run("q_with_parent_creates_child", func(t *testing.T) { + p := bdProxiedInit(t, bd, "qp") + parent := bdProxiedCreate(t, bd, p.dir, "Quick parent", "--type", "epic") + bdProxiedLabel(t, bd, p.dir, "add", parent.ID, "inherited") + + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "q", "Quick child", "--parent", parent.ID) + if err != nil { + t.Fatalf("q --parent failed: %v\nstderr:\n%s", err, stderr) + } + childID := strings.TrimSpace(stdout) + if !strings.HasPrefix(childID, parent.ID+".") { + t.Errorf("child ID %q should be hierarchical under %s", childID, parent.ID) + } + + db := openProxiedDB(t, p) + assertProxiedDepExists(t, db, childID, parent.ID) + + labels := getProxiedLabels(t, db, childID) + found := false + for _, l := range labels { + if l == "inherited" { + found = true + } + } + if !found { + t.Errorf("child labels = %v, want inherited label from parent", labels) + } + }) +} + +func TestProxiedServerTodo(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("add_list_done", func(t *testing.T) { + p := bdProxiedInit(t, bd, "td") + + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "add", "Write the tests") + if err != nil { + t.Fatalf("todo add failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(stdout, "Write the tests") { + t.Errorf("expected created title in output, got:\n%s", stdout) + } + + listOut, _, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "list") + if err != nil { + t.Fatalf("todo list failed: %v", err) + } + if !strings.Contains(listOut, "Write the tests") { + t.Errorf("expected todo in list, got:\n%s", listOut) + } + }) + + t.Run("add_json_and_done", func(t *testing.T) { + p := bdProxiedInit(t, bd, "tj") + created := bdProxiedCreate(t, bd, p.dir, "Task to finish", "--type", "task") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "done", created.ID) + if err != nil { + t.Fatalf("todo done failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, "Closed") { + t.Errorf("expected 'Closed' output, got:\n%s", out) + } + if got := bdProxiedShow(t, bd, p.dir, created.ID); got.Status != "closed" { + t.Errorf("status = %q, want closed", got.Status) + } + }) + + t.Run("bare_todo_lists_open_tasks", func(t *testing.T) { + p := bdProxiedInit(t, bd, "tb") + open := bdProxiedCreate(t, bd, p.dir, "Open todo", "--type", "task") + done := bdProxiedCreate(t, bd, p.dir, "Done todo", "--type", "task") + if _, _, err := bdProxiedRunBuffers(t, bd, p.dir, "todo", "done", done.ID); err != nil { + t.Fatalf("todo done failed: %v", err) + } + + out, _, err := bdProxiedRunBuffers(t, bd, p.dir, "todo") + if err != nil { + t.Fatalf("bare todo failed: %v", err) + } + if !strings.Contains(out, open.ID) { + t.Errorf("expected open todo %s in list, got:\n%s", open.ID, out) + } + if strings.Contains(out, done.ID) { + t.Errorf("closed todo %s should not appear in default list:\n%s", done.ID, out) + } + }) +} diff --git a/cmd/bd/relational_proxied_integration_test.go b/cmd/bd/relational_proxied_integration_test.go new file mode 100644 index 000000000..5280e39ef --- /dev/null +++ b/cmd/bd/relational_proxied_integration_test.go @@ -0,0 +1,112 @@ +//go:build cgo + +package main + +import ( + "strings" + "testing" +) + +func TestProxiedServerLink(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("link_default_blocks", func(t *testing.T) { + p := bdProxiedInit(t, bd, "lk") + a := bdProxiedCreate(t, bd, p.dir, "Link from") + b := bdProxiedCreate(t, bd, p.dir, "Link to") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "link", a.ID, b.ID) + if err != nil { + t.Fatalf("link failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, "Linked") { + t.Errorf("expected 'Linked' output, got:\n%s", out) + } + + db := openProxiedDB(t, p) + assertProxiedDepExists(t, db, a.ID, b.ID) + }) + + t.Run("link_with_type", func(t *testing.T) { + p := bdProxiedInit(t, bd, "lt") + a := bdProxiedCreate(t, bd, p.dir, "Rel from") + b := bdProxiedCreate(t, bd, p.dir, "Rel to") + + if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "link", a.ID, b.ID, "--type", "related"); err != nil { + t.Fatalf("link --type related failed: %v\nstderr:\n%s", err, stderr) + } + + db := openProxiedDB(t, p) + assertProxiedDepExistsWithType(t, db, a.ID, b.ID, "related") + }) + + t.Run("link_invalid_type_rejected", func(t *testing.T) { + p := bdProxiedInit(t, bd, "li") + a := bdProxiedCreate(t, bd, p.dir, "Bad from") + b := bdProxiedCreate(t, bd, p.dir, "Bad to") + _, out, err := bdProxiedRunBuffers(t, bd, p.dir, "link", a.ID, b.ID, "--type", "") + if err == nil { + t.Errorf("expected invalid type to fail, got:\n%s", out) + } + }) +} + +func TestProxiedServerChildren(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + p := bdProxiedInit(t, bd, "ch") + parent := bdProxiedCreate(t, bd, p.dir, "Parent", "--type", "epic") + c1 := bdProxiedCreate(t, bd, p.dir, "Child 1", "--parent", parent.ID) + c2 := bdProxiedCreate(t, bd, p.dir, "Child 2", "--parent", parent.ID) + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "children", parent.ID) + if err != nil { + t.Fatalf("children failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, c1.ID) || !strings.Contains(out, c2.ID) { + t.Errorf("expected both children in output, got:\n%s", out) + } +} + +func TestProxiedServerGateList(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("db_wide_lists_gates", func(t *testing.T) { + p := bdProxiedInit(t, bd, "ga") + gate := bdProxiedCreate(t, bd, p.dir, "A gate", "--type", "gate") + bdProxiedCreate(t, bd, p.dir, "Not a gate", "--type", "task") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "list") + if err != nil { + t.Fatalf("gate list failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, gate.ID) { + t.Errorf("expected gate %s in output, got:\n%s", gate.ID, out) + } + }) + + t.Run("bead_scoped_lists_blocking_gates", func(t *testing.T) { + p := bdProxiedInit(t, bd, "gb") + work := bdProxiedCreate(t, bd, p.dir, "Blocked work") + gate := bdProxiedCreate(t, bd, p.dir, "Blocking gate", "--type", "gate") + unrelated := bdProxiedCreate(t, bd, p.dir, "Unrelated gate", "--type", "gate") + + if _, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "link", work.ID, gate.ID); err != nil { + t.Fatalf("link work->gate failed: %v\nstderr:\n%s", err, stderr) + } + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "gate", "list", work.ID) + if err != nil { + t.Fatalf("gate list failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, gate.ID) { + t.Errorf("expected blocking gate %s in bead-scoped output, got:\n%s", gate.ID, out) + } + if strings.Contains(out, unrelated.ID) { + t.Errorf("bead-scoped list must not include unrelated gate %s:\n%s", unrelated.ID, out) + } + }) +} diff --git a/cmd/bd/search.go b/cmd/bd/search.go index 4d864f316..e5ae1ad9f 100644 --- a/cmd/bd/search.go +++ b/cmd/bd/search.go @@ -39,9 +39,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("search is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("search") defer func() { if c := metrics.Global(); c != nil { @@ -49,6 +46,10 @@ Examples: } }() + if usesProxiedServer() { + return runSearchProxiedServer(cmd, rootCtx, args) + } + queryFlag, _ := cmd.Flags().GetString("query") var query string if len(args) > 0 { diff --git a/cmd/bd/search_proxied_integration_test.go b/cmd/bd/search_proxied_integration_test.go new file mode 100644 index 000000000..4ec59167e --- /dev/null +++ b/cmd/bd/search_proxied_integration_test.go @@ -0,0 +1,379 @@ +//go:build cgo + +package main + +import ( + "context" + "encoding/json" + "strings" + "testing" +) + +func bdProxiedSearch(t *testing.T, bd, dir string, args ...string) string { + t.Helper() + fullArgs := append([]string{"search"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...) + if err != nil { + t.Fatalf("bd search %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + return stdout +} + +func bdProxiedSearchFail(t *testing.T, bd, dir string, args ...string) string { + t.Helper() + fullArgs := append([]string{"search"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...) + if err == nil { + t.Fatalf("expected bd search %s to fail, got:\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), stdout, stderr) + } + return stdout + stderr +} + +func bdProxiedSearchJSON(t *testing.T, bd, dir string, args ...string) []map[string]interface{} { + t.Helper() + fullArgs := append([]string{"search", "--json"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...) + if err != nil { + t.Fatalf("bd search --json %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + start := strings.Index(stdout, "[") + if start < 0 { + return nil + } + var results []map[string]interface{} + if err := json.Unmarshal([]byte(stdout[start:]), &results); err != nil { + t.Fatalf("parse search JSON: %v\nraw: %s", err, stdout[start:]) + } + return results +} + +func searchResultIDs(results []map[string]interface{}) map[string]bool { + ids := map[string]bool{} + for _, r := range results { + if id, ok := r["id"].(string); ok { + ids[id] = true + } + } + return ids +} + +func TestProxiedServerSearch(t *testing.T) { + requireProxiedServerEnv(t) + + bd := buildEmbeddedBD(t) + + p := bdProxiedInit(t, bd, "sp") + taskA := bdProxiedCreate(t, bd, p.dir, "Alpha task", "--type", "task", "--priority", "1", "--assignee", "alice", "--description", "Important alpha work", "--label", "urgent") + taskB := bdProxiedCreate(t, bd, p.dir, "Beta bug", "--type", "bug", "--priority", "3", "--assignee", "bob", "--description", "Beta bug description", "--label", "backend") + taskC := bdProxiedCreate(t, bd, p.dir, "Gamma feature", "--type", "feature", "--priority", "2", "--label", "urgent", "--label", "frontend") + taskD := bdProxiedCreate(t, bd, p.dir, "Delta task no desc", "--type", "task") + closedTask := bdProxiedCreate(t, bd, p.dir, "Closed epsilon", "--type", "task") + bdProxiedClose(t, bd, p.dir, closedTask.ID) + + t.Run("positional_query", func(t *testing.T) { + if !searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "Alpha"))[taskA.ID] { + t.Errorf("expected to find %s in search for 'Alpha'", taskA.ID) + } + }) + + t.Run("query_flag", func(t *testing.T) { + if !searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "--query", "Beta"))[taskB.ID] { + t.Errorf("expected to find %s in search for 'Beta'", taskB.ID) + } + }) + + t.Run("no_results", func(t *testing.T) { + if got := bdProxiedSearchJSON(t, bd, p.dir, "nonexistentxyz123"); len(got) != 0 { + t.Errorf("expected 0 results, got %d", len(got)) + } + }) + + t.Run("missing_query_rejected", func(t *testing.T) { + out := bdProxiedSearchFail(t, bd, p.dir) + if !strings.Contains(out, "query is required") { + t.Errorf("expected 'query is required' error, got:\n%s", out) + } + }) + + t.Run("status_open_excludes_closed", func(t *testing.T) { + if searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "task", "--status", "open"))[closedTask.ID] { + t.Error("should not find closed task with --status open") + } + }) + + t.Run("default_excludes_closed", func(t *testing.T) { + if searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-"))[closedTask.ID] { + t.Error("default search should exclude closed issues") + } + }) + + t.Run("status_closed", func(t *testing.T) { + if !searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "epsilon", "--status", "closed"))[closedTask.ID] { + t.Error("expected to find closed task with --status closed") + } + }) + + t.Run("status_all", func(t *testing.T) { + ids := searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--status", "all")) + if !ids[taskA.ID] || !ids[closedTask.ID] { + t.Error("expected both open and closed issues with --status all") + } + }) + + t.Run("assignee", func(t *testing.T) { + ids := searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--assignee", "alice")) + if ids[taskB.ID] { + t.Error("bob's task should not appear with --assignee alice") + } + if !ids[taskA.ID] { + t.Error("expected alice's task in results") + } + }) + + t.Run("no_assignee", func(t *testing.T) { + ids := searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--no-assignee")) + if ids[taskA.ID] || ids[taskB.ID] { + t.Error("assigned tasks should not appear with --no-assignee") + } + }) + + t.Run("type", func(t *testing.T) { + results := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--type", "bug") + if len(results) == 0 { + t.Fatal("expected bug results") + } + for _, r := range results { + if r["issue_type"] != "bug" { + t.Errorf("expected type=bug, got %v", r["issue_type"]) + } + } + }) + + t.Run("label_and", func(t *testing.T) { + results := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--label", "urgent", "--label", "frontend") + if len(results) != 1 || results[0]["id"] != taskC.ID { + t.Errorf("expected only %s with --label urgent --label frontend, got %d results", taskC.ID, len(results)) + } + }) + + t.Run("label_any", func(t *testing.T) { + ids := searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--label-any", "urgent,frontend")) + if !ids[taskA.ID] || !ids[taskC.ID] { + t.Errorf("expected both urgent-labeled tasks with --label-any: %v", ids) + } + }) + + t.Run("no_labels", func(t *testing.T) { + ids := searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--no-labels")) + if ids[taskA.ID] || ids[taskC.ID] { + t.Error("labeled tasks should not appear with --no-labels") + } + }) + + t.Run("limit", func(t *testing.T) { + if got := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--limit", "2"); len(got) > 2 { + t.Errorf("expected at most 2 results with --limit 2, got %d", len(got)) + } + }) + + t.Run("limit_zero_unlimited", func(t *testing.T) { + if got := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--limit", "0", "--status", "all"); len(got) < 5 { + t.Errorf("expected all issues with --limit 0, got %d", len(got)) + } + }) + + t.Run("sort_priority", func(t *testing.T) { + results := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--sort", "priority") + if len(results) < 2 { + t.Skip("need at least 2 results to test sort") + } + if results[0]["priority"].(float64) > results[len(results)-1]["priority"].(float64) { + t.Error("expected ascending priority sort") + } + }) + + t.Run("sort_reverse", func(t *testing.T) { + results := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--sort", "priority", "--reverse") + if len(results) < 2 { + t.Skip("need at least 2 results to test reverse sort") + } + if results[0]["priority"].(float64) < results[len(results)-1]["priority"].(float64) { + t.Error("expected descending priority sort with --reverse") + } + }) + + t.Run("priority_min", func(t *testing.T) { + for _, r := range bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--priority-min", "2") { + if int(r["priority"].(float64)) < 2 { + t.Errorf("expected priority >= 2, got %v for %s", r["priority"], r["id"]) + } + } + }) + + t.Run("priority_max", func(t *testing.T) { + for _, r := range bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--priority-max", "2") { + if int(r["priority"].(float64)) > 2 { + t.Errorf("expected priority <= 2, got %v for %s", r["priority"], r["id"]) + } + } + }) + + t.Run("desc_contains", func(t *testing.T) { + if !searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--desc-contains", "alpha"))[taskA.ID] { + t.Error("expected to find taskA with --desc-contains alpha") + } + }) + + t.Run("empty_description", func(t *testing.T) { + ids := searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--empty-description")) + if !ids[taskD.ID] { + t.Error("expected to find task without description") + } + if ids[taskA.ID] { + t.Error("task with description should not appear with --empty-description") + } + }) + + t.Run("long_text_output", func(t *testing.T) { + out := bdProxiedSearch(t, bd, p.dir, "Alpha", "--long") + if !strings.Contains(out, "Alpha task") { + t.Errorf("expected long output to contain title, got:\n%s", out) + } + }) + + t.Run("created_after", func(t *testing.T) { + if got := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--created-after", "2020-01-01"); len(got) == 0 { + t.Error("expected results with --created-after 2020-01-01") + } + }) + + t.Run("created_before", func(t *testing.T) { + if got := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--created-before", "2020-01-01"); len(got) != 0 { + t.Errorf("expected 0 results with --created-before 2020-01-01, got %d", len(got)) + } + }) + + t.Run("metadata_field", func(t *testing.T) { + mdIssue := bdProxiedCreate(t, bd, p.dir, "Metadata issue", "--type", "task", "--metadata", `{"team":"platform"}`) + if !searchResultIDs(bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--metadata-field", "team=platform"))[mdIssue.ID] { + t.Errorf("expected to find %s with --metadata-field team=platform", mdIssue.ID) + } + }) + + t.Run("has_metadata_key", func(t *testing.T) { + if got := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--has-metadata-key", "team"); len(got) == 0 { + t.Error("expected results with --has-metadata-key team") + } + }) + + t.Run("invalid_metadata_field_rejected", func(t *testing.T) { + out := bdProxiedSearchFail(t, bd, p.dir, "sp-", "--metadata-field", "noequalsign") + if !strings.Contains(out, "metadata-field") { + t.Errorf("expected metadata-field error, got:\n%s", out) + } + }) + + t.Run("combined_filters", func(t *testing.T) { + results := bdProxiedSearchJSON(t, bd, p.dir, "sp-", "--type", "task", "--assignee", "alice", "--label", "urgent") + if len(results) != 1 || results[0]["id"] != taskA.ID { + t.Errorf("expected only %s with combined filters, got %d results", taskA.ID, len(results)) + } + }) + + t.Run("json_hydrates_labels_and_counts", func(t *testing.T) { + results := bdProxiedSearchJSON(t, bd, p.dir, "Gamma") + var row map[string]interface{} + for _, r := range results { + if r["id"] == taskC.ID { + row = r + } + } + if row == nil { + t.Fatalf("taskC not found in search results") + } + labels := map[string]bool{} + if raw, ok := row["labels"].([]interface{}); ok { + for _, l := range raw { + labels[l.(string)] = true + } + } + if !labels["urgent"] || !labels["frontend"] { + t.Errorf("expected labels urgent+frontend hydrated in JSON, got %v", row["labels"]) + } + for _, key := range []string{"dependency_count", "dependent_count", "comment_count"} { + if _, ok := row[key]; !ok { + t.Errorf("expected %s field in counts JSON", key) + } + } + }) + + t.Run("json_comment_count", func(t *testing.T) { + issue := bdProxiedCreate(t, bd, p.dir, "Countable comment target", "--type", "task") + bdProxiedComment(t, bd, p.dir, issue.ID, "a note") + + results := bdProxiedSearchJSON(t, bd, p.dir, "Countable") + var row map[string]interface{} + for _, r := range results { + if r["id"] == issue.ID { + row = r + } + } + if row == nil { + t.Fatalf("comment target not found in search results") + } + if int(row["comment_count"].(float64)) != 1 { + t.Errorf("comment_count = %v, want 1", row["comment_count"]) + } + }) + + t.Run("wisp_appears_in_search", func(t *testing.T) { + wp := bdProxiedInit(t, bd, "sw") + wisp := bdProxiedCreate(t, bd, wp.dir, "Wispy alpha search target", "--ephemeral") + if !searchResultIDs(bdProxiedSearchJSON(t, bd, wp.dir, "Wispy"))[wisp.ID] { + t.Errorf("expected ephemeral wisp %s to appear in search results", wisp.ID) + } + }) + + t.Run("wisp_labels_hydrated_from_wisp_labels", func(t *testing.T) { + wp := bdProxiedInit(t, bd, "swl") + wisp := bdProxiedCreate(t, bd, wp.dir, "Wisp label search", "--ephemeral") + bdProxiedLabel(t, bd, wp.dir, "add", wisp.ID, "wlabel") + + db := openProxiedDB(t, wp) + var wispCount, permCount int + if err := db.QueryRowContext(context.Background(), + "SELECT COUNT(*) FROM wisp_labels WHERE issue_id = ?", wisp.ID).Scan(&wispCount); err != nil { + t.Fatalf("count wisp_labels: %v", err) + } + if err := db.QueryRowContext(context.Background(), + "SELECT COUNT(*) FROM labels WHERE issue_id = ?", wisp.ID).Scan(&permCount); err != nil { + t.Fatalf("count labels: %v", err) + } + if wispCount != 1 || permCount != 0 { + t.Fatalf("wisp label routing: wisp_labels=%d labels=%d, want 1/0", wispCount, permCount) + } + + results := bdProxiedSearchJSON(t, bd, wp.dir, "Wisp") + var row map[string]interface{} + for _, r := range results { + if r["id"] == wisp.ID { + row = r + } + } + if row == nil { + t.Fatalf("wisp not found in search results") + } + labels := map[string]bool{} + if raw, ok := row["labels"].([]interface{}); ok { + for _, l := range raw { + labels[l.(string)] = true + } + } + if !labels["wlabel"] { + t.Errorf("expected wisp label 'wlabel' hydrated from wisp_labels in search JSON, got %v", row["labels"]) + } + }) +} diff --git a/cmd/bd/search_proxied_server.go b/cmd/bd/search_proxied_server.go new file mode 100644 index 000000000..38fb2a02f --- /dev/null +++ b/cmd/bd/search_proxied_server.go @@ -0,0 +1,218 @@ +package main + +import ( + "context" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + "github.com/steveyegge/beads/internal/storage" + "github.com/steveyegge/beads/internal/types" + "github.com/steveyegge/beads/internal/utils" + "github.com/steveyegge/beads/internal/validation" +) + +func runSearchProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + queryFlag, _ := cmd.Flags().GetString("query") + var query string + if len(args) > 0 { + query = strings.Join(args, " ") + } else if queryFlag != "" { + query = queryFlag + } + + if query == "" { + if err := cmd.Help(); err != nil { + fmt.Fprintf(os.Stderr, "Error displaying help: %v\n", err) + } + return HandleErrorRespectJSON("search query is required") + } + + status, _ := cmd.Flags().GetString("status") + assignee, _ := cmd.Flags().GetString("assignee") + issueType, _ := cmd.Flags().GetString("type") + limit, _ := cmd.Flags().GetInt("limit") + labels, _ := cmd.Flags().GetStringSlice("label") + labelsAny, _ := cmd.Flags().GetStringSlice("label-any") + longFormat, _ := cmd.Flags().GetBool("long") + sortBy, _ := cmd.Flags().GetString("sort") + reverse, _ := cmd.Flags().GetBool("reverse") + + createdAfter, _ := cmd.Flags().GetString("created-after") + createdBefore, _ := cmd.Flags().GetString("created-before") + updatedAfter, _ := cmd.Flags().GetString("updated-after") + updatedBefore, _ := cmd.Flags().GetString("updated-before") + closedAfter, _ := cmd.Flags().GetString("closed-after") + closedBefore, _ := cmd.Flags().GetString("closed-before") + + priorityMinStr, _ := cmd.Flags().GetString("priority-min") + priorityMaxStr, _ := cmd.Flags().GetString("priority-max") + + descContains, _ := cmd.Flags().GetString("desc-contains") + notesContains, _ := cmd.Flags().GetString("notes-contains") + externalContains, _ := cmd.Flags().GetString("external-contains") + + emptyDesc, _ := cmd.Flags().GetBool("empty-description") + noAssignee, _ := cmd.Flags().GetBool("no-assignee") + noLabels, _ := cmd.Flags().GetBool("no-labels") + + labels = utils.NormalizeLabels(labels) + labelsAny = utils.NormalizeLabels(labelsAny) + + filter := types.IssueFilter{ + Limit: limit, + } + + if status != "" && status != "all" { + s := types.Status(status) + filter.Status = &s + } else if status != "all" { + filter.ExcludeStatus = []types.Status{types.StatusClosed} + } + + if assignee != "" { + filter.Assignee = &assignee + } + + if issueType != "" { + t := types.IssueType(issueType) + filter.IssueType = &t + } + + if len(labels) > 0 { + filter.Labels = labels + } + + if len(labelsAny) > 0 { + filter.LabelsAny = labelsAny + } + + if descContains != "" { + filter.DescriptionContains = descContains + } + if notesContains != "" { + filter.NotesContains = notesContains + } + if externalContains != "" { + filter.ExternalRefContains = externalContains + } + + if emptyDesc { + filter.EmptyDescription = true + } + if noAssignee { + filter.NoAssignee = true + } + if noLabels { + filter.NoLabels = true + } + + if createdAfter != "" { + t, err := parseTimeFlag(createdAfter) + if err != nil { + return HandleErrorRespectJSON("parsing --created-after: %v", err) + } + filter.CreatedAfter = &t + } + if createdBefore != "" { + t, err := parseTimeFlag(createdBefore) + if err != nil { + return HandleErrorRespectJSON("parsing --created-before: %v", err) + } + filter.CreatedBefore = &t + } + if updatedAfter != "" { + t, err := parseTimeFlag(updatedAfter) + if err != nil { + return HandleErrorRespectJSON("parsing --updated-after: %v", err) + } + filter.UpdatedAfter = &t + } + if updatedBefore != "" { + t, err := parseTimeFlag(updatedBefore) + if err != nil { + return HandleErrorRespectJSON("parsing --updated-before: %v", err) + } + filter.UpdatedBefore = &t + } + if closedAfter != "" { + t, err := parseTimeFlag(closedAfter) + if err != nil { + return HandleErrorRespectJSON("parsing --closed-after: %v", err) + } + filter.ClosedAfter = &t + } + if closedBefore != "" { + t, err := parseTimeFlag(closedBefore) + if err != nil { + return HandleErrorRespectJSON("parsing --closed-before: %v", err) + } + filter.ClosedBefore = &t + } + + if cmd.Flags().Changed("priority-min") { + priorityMin, err := validation.ValidatePriority(priorityMinStr) + if err != nil { + return HandleErrorRespectJSON("parsing --priority-min: %v", err) + } + filter.PriorityMin = &priorityMin + } + if cmd.Flags().Changed("priority-max") { + priorityMax, err := validation.ValidatePriority(priorityMaxStr) + if err != nil { + return HandleErrorRespectJSON("parsing --priority-max: %v", err) + } + filter.PriorityMax = &priorityMax + } + + metadataFieldFlags, _ := cmd.Flags().GetStringArray("metadata-field") + if len(metadataFieldFlags) > 0 { + filter.MetadataFields = make(map[string]string, len(metadataFieldFlags)) + for _, mf := range metadataFieldFlags { + k, v, ok := strings.Cut(mf, "=") + if !ok || k == "" { + return HandleErrorRespectJSON("invalid --metadata-field: expected key=value, got %q", mf) + } + if err := storage.ValidateMetadataKey(k); err != nil { + return HandleErrorRespectJSON("invalid --metadata-field key: %v", err) + } + filter.MetadataFields[k] = v + } + } + hasMetadataKey, _ := cmd.Flags().GetString("has-metadata-key") + if hasMetadataKey != "" { + if err := storage.ValidateMetadataKey(hasMetadataKey); err != nil { + return HandleErrorRespectJSON("invalid --has-metadata-key: %v", err) + } + filter.HasMetadataKey = hasMetadataKey + } + + uw, err := openProxiedListUOW(ctx) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + defer uw.Close(ctx) + + if jsonOutput { + page, err := uw.IssueUseCase().SearchIssuesWithCounts(ctx, query, filter) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + items := page.Items + sortIssuesWithCounts(items, sortBy, reverse) + if items == nil { + items = []*types.IssueWithCounts{} + } + return outputJSON(items) + } + + page, err := uw.IssueUseCase().SearchIssues(ctx, query, filter) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + issues := page.Items + sortIssues(issues, sortBy, reverse) + outputSearchResults(issues, query, longFormat) + return nil +} diff --git a/cmd/bd/state.go b/cmd/bd/state.go index 4774fb8e0..cddf97092 100644 --- a/cmd/bd/state.go +++ b/cmd/bd/state.go @@ -36,9 +36,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("state is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("state") defer func() { if c := metrics.Global(); c != nil { @@ -46,6 +43,10 @@ Examples: } }() + if usesProxiedServer() { + return runStateProxiedServer(rootCtx, args[0], args[1]) + } + ctx := rootCtx issueID := args[0] dimension := args[1] @@ -278,9 +279,6 @@ Example: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("state list is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("state-list") defer func() { if c := metrics.Global(); c != nil { @@ -288,6 +286,10 @@ Example: } }() + if usesProxiedServer() { + return runStateListProxiedServer(rootCtx, args[0]) + } + ctx := rootCtx issueID := args[0] diff --git a/cmd/bd/state_proxied_integration_test.go b/cmd/bd/state_proxied_integration_test.go new file mode 100644 index 000000000..160c09442 --- /dev/null +++ b/cmd/bd/state_proxied_integration_test.go @@ -0,0 +1,102 @@ +//go:build cgo + +package main + +import ( + "encoding/json" + "strings" + "testing" +) + +func TestProxiedServerState(t *testing.T) { + requireProxiedServerEnv(t) + bd := buildEmbeddedBD(t) + + t.Run("state_query", func(t *testing.T) { + p := bdProxiedInit(t, bd, "st") + issue := bdProxiedCreate(t, bd, p.dir, "State target") + bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "patrol:active") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "state", issue.ID, "patrol") + if err != nil { + t.Fatalf("state failed: %v\nstderr:\n%s", err, stderr) + } + if strings.TrimSpace(out) != "active" { + t.Errorf("state value = %q, want active", strings.TrimSpace(out)) + } + }) + + t.Run("state_query_unset", func(t *testing.T) { + p := bdProxiedInit(t, bd, "su") + issue := bdProxiedCreate(t, bd, p.dir, "No state") + out, _, err := bdProxiedRunBuffers(t, bd, p.dir, "state", issue.ID, "mode") + if err != nil { + t.Fatalf("state failed: %v", err) + } + if !strings.Contains(out, "no mode state set") { + t.Errorf("expected unset message, got:\n%s", out) + } + }) + + t.Run("state_query_json", func(t *testing.T) { + p := bdProxiedInit(t, bd, "sj") + issue := bdProxiedCreate(t, bd, p.dir, "State json") + bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "mode:degraded") + + stdout, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "state", issue.ID, "mode", "--json") + if err != nil { + t.Fatalf("state --json failed: %v\nstderr:\n%s", err, stderr) + } + start := strings.Index(stdout, "{") + if start < 0 { + t.Fatalf("no JSON object in state output:\n%s", stdout) + } + var res map[string]interface{} + if err := json.Unmarshal([]byte(stdout[start:]), &res); err != nil { + t.Fatalf("parse state JSON: %v\nraw: %s", err, stdout[start:]) + } + if res["value"] != "degraded" { + t.Errorf("json value = %v, want degraded", res["value"]) + } + }) + + t.Run("state_list", func(t *testing.T) { + p := bdProxiedInit(t, bd, "sl") + issue := bdProxiedCreate(t, bd, p.dir, "State list target") + bdProxiedLabel(t, bd, p.dir, "add", issue.ID, "patrol:active,mode:normal") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "state", "list", issue.ID) + if err != nil { + t.Fatalf("state list failed: %v\nstderr:\n%s", err, stderr) + } + if !strings.Contains(out, "patrol: active") || !strings.Contains(out, "mode: normal") { + t.Errorf("expected both dimensions in output, got:\n%s", out) + } + }) + + t.Run("state_list_empty", func(t *testing.T) { + p := bdProxiedInit(t, bd, "se") + issue := bdProxiedCreate(t, bd, p.dir, "No labels") + out, _, err := bdProxiedRunBuffers(t, bd, p.dir, "state", "list", issue.ID) + if err != nil { + t.Fatalf("state list failed: %v", err) + } + if !strings.Contains(out, "no state labels") { + t.Errorf("expected empty-state message, got:\n%s", out) + } + }) + + t.Run("state_reads_wisp_labels", func(t *testing.T) { + p := bdProxiedInit(t, bd, "sw") + wisp := bdProxiedCreate(t, bd, p.dir, "Wisp state", "--ephemeral") + bdProxiedLabel(t, bd, p.dir, "add", wisp.ID, "patrol:muted") + + out, stderr, err := bdProxiedRunBuffers(t, bd, p.dir, "state", wisp.ID, "patrol") + if err != nil { + t.Fatalf("state on wisp failed: %v\nstderr:\n%s", err, stderr) + } + if strings.TrimSpace(out) != "muted" { + t.Errorf("wisp state value = %q, want muted (must read from wisp_labels)", strings.TrimSpace(out)) + } + }) +} diff --git a/cmd/bd/state_proxied_server.go b/cmd/bd/state_proxied_server.go new file mode 100644 index 000000000..0bb126417 --- /dev/null +++ b/cmd/bd/state_proxied_server.go @@ -0,0 +1,110 @@ +package main + +import ( + "context" + "fmt" + "strings" + + "github.com/steveyegge/beads/internal/storage/uow" + "github.com/steveyegge/beads/internal/ui" +) + +func proxiedStateLabels(ctx context.Context, uw uow.UnitOfWork, issueID string) (string, []string, error) { + issue, isWisp, err := proxiedGetIssueOrWisp(ctx, uw, issueID) + if err != nil { + return "", nil, HandleErrorRespectJSON("resolving %s: %v", issueID, err) + } + if issue == nil { + return "", nil, HandleErrorRespectJSON("resolving %s: not found", issueID) + } + var labels []string + if isWisp { + labels, err = uw.LabelUseCase().GetWispLabels(ctx, issue.ID) + } else { + labels, err = uw.LabelUseCase().GetLabels(ctx, issue.ID) + } + if err != nil { + return "", nil, HandleErrorRespectJSON("%v", err) + } + return issue.ID, labels, nil +} + +func runStateProxiedServer(ctx context.Context, issueID, dimension string) error { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return err + } + defer uw.Close(ctx) + + fullID, labels, err := proxiedStateLabels(ctx, uw, issueID) + if err != nil { + return err + } + + prefix := dimension + ":" + var value string + for _, label := range labels { + if strings.HasPrefix(label, prefix) { + value = strings.TrimPrefix(label, prefix) + break + } + } + + if jsonOutput { + result := map[string]interface{}{ + "issue_id": fullID, + "dimension": dimension, + "value": value, + } + if value == "" { + result["value"] = nil + } + return outputJSON(result) + } + + if value == "" { + fmt.Printf("(no %s state set)\n", dimension) + } else { + fmt.Println(value) + } + return nil +} + +func runStateListProxiedServer(ctx context.Context, issueID string) error { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return err + } + defer uw.Close(ctx) + + fullID, labels, err := proxiedStateLabels(ctx, uw, issueID) + if err != nil { + return err + } + + states := make(map[string]string) + for _, label := range labels { + if idx := strings.Index(label, ":"); idx > 0 { + states[label[:idx]] = label[idx+1:] + } + } + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "issue_id": fullID, + "states": states, + }) + } + + if len(states) == 0 { + fmt.Printf("\n%s has no state labels\n", fullID) + return nil + } + + fmt.Printf("\n%s State for %s:\n", ui.RenderAccent("📊"), fullID) + for dimension, value := range states { + fmt.Printf(" %s: %s\n", dimension, value) + } + fmt.Println() + return nil +} diff --git a/cmd/bd/tag.go b/cmd/bd/tag.go index defe40cff..33e06bec7 100644 --- a/cmd/bd/tag.go +++ b/cmd/bd/tag.go @@ -23,9 +23,6 @@ Examples: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("tag is not supported in proxied-server mode") - } CheckReadonly("tag") evt := metrics.NewCommandEvent("tag") @@ -35,6 +32,10 @@ Examples: } }() + if usesProxiedServer() { + return runTagProxiedServer(rootCtx, args) + } + id := args[0] label := args[1] diff --git a/cmd/bd/todo.go b/cmd/bd/todo.go index 907641aec..98163f257 100644 --- a/cmd/bd/todo.go +++ b/cmd/bd/todo.go @@ -30,9 +30,6 @@ TODOs can be promoted to full issues by changing type or priority: SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("todo is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("todo") defer func() { if c := metrics.Global(); c != nil { @@ -53,9 +50,6 @@ var addTodoCmd = &cobra.Command{ SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("todo add is not supported in proxied-server mode") - } CheckReadonly("todo add") evt := metrics.NewCommandEvent("todo-add") @@ -65,6 +59,10 @@ var addTodoCmd = &cobra.Command{ } }() + if usesProxiedServer() { + return runTodoAddProxiedServer(cmd, rootCtx, args) + } + title := strings.Join(args, " ") priority, _ := cmd.Flags().GetInt("priority") @@ -109,9 +107,6 @@ var listTodosCmd = &cobra.Command{ SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("todo list is not supported in proxied-server mode") - } evt := metrics.NewCommandEvent("todo-list") defer func() { if c := metrics.Global(); c != nil { @@ -140,9 +135,19 @@ func runTodoListCore(cmd *cobra.Command, _ []string) error { filter.Status = &openStatus } - issues, err := getStore().SearchIssues(ctx, "", filter) - if err != nil { - return HandleError("failed to list TODOs: %v", err) + var issues []*types.Issue + if usesProxiedServer() { + var err error + issues, err = todoListProxied(ctx, filter) + if err != nil { + return err + } + } else { + var err error + issues, err = getStore().SearchIssues(ctx, "", filter) + if err != nil { + return HandleError("failed to list TODOs: %v", err) + } } if jsonOutput { @@ -181,9 +186,6 @@ var doneTodoCmd = &cobra.Command{ SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { - if usesProxiedServer() { - return HandleErrorRespectJSON("todo done is not supported in proxied-server mode") - } CheckReadonly("todo done") evt := metrics.NewCommandEvent("todo-done") @@ -193,6 +195,10 @@ var doneTodoCmd = &cobra.Command{ } }() + if usesProxiedServer() { + return runTodoDoneProxiedServer(cmd, rootCtx, args) + } + ctx := rootCtx reason, _ := cmd.Flags().GetString("reason") diff --git a/cmd/bd/todo_proxied_server.go b/cmd/bd/todo_proxied_server.go new file mode 100644 index 000000000..ea7a4f492 --- /dev/null +++ b/cmd/bd/todo_proxied_server.go @@ -0,0 +1,132 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + "strings" + + "github.com/spf13/cobra" + + "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 todoListProxied(ctx context.Context, filter types.IssueFilter) ([]*types.Issue, error) { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return nil, err + } + defer uw.Close(ctx) + + page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter) + if err != nil { + return nil, HandleError("failed to list TODOs: %v", err) + } + return page.Items, nil +} + +func runTodoAddProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + title := strings.Join(args, " ") + + priority, _ := cmd.Flags().GetInt("priority") + description, _ := cmd.Flags().GetString("description") + + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + issue := &types.Issue{ + Title: title, + Description: description, + Priority: priority, + IssueType: types.TypeTask, + Status: types.StatusOpen, + Assignee: getActorWithGit(), + Owner: getOwner(), + CreatedBy: getActorWithGit(), + } + + res, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (*types.Issue, string, error) { + result, err := uw.IssueUseCase().CreateIssue(ctx, domain.CreateIssueParams{Issue: issue}, getActorWithGit()) + if err != nil { + return nil, "", err + } + return result.Issue, fmt.Sprintf("bd: create %s", result.Issue.ID), nil + }) + if err != nil { + return HandleError("failed to create TODO: %v", err) + } + commandDidWrite.Store(true) + + if jsonOutput { + data, err := json.MarshalIndent(res, "", " ") + if err != nil { + return HandleError("failed to marshal JSON: %v", err) + } + fmt.Println(string(data)) + return nil + } + fmt.Printf("Created %s: %s\n", ui.RenderID(res.ID), res.Title) + return nil +} + +func runTodoDoneProxiedServer(cmd *cobra.Command, ctx context.Context, args []string) error { + reason, _ := cmd.Flags().GetString("reason") + if reason == "" { + reason = "Completed" + } + + if uowProvider == nil { + return HandleError("proxied-server UOW provider not initialized") + } + + var closedIDs []string + for _, issueID := range args { + _, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (struct{}, string, error) { + issue, isWisp := proxiedResolveIssueOrWisp(ctx, uw, issueID) + if issue == nil { + return struct{}{}, "", fmt.Errorf("issue %s not found", issueID) + } + params := domain.CloseIssueParams{Reason: reason} + var e error + if isWisp { + _, e = uw.IssueUseCase().CloseWisp(ctx, issue.ID, params, getActorWithGit()) + } else { + _, e = uw.IssueUseCase().CloseIssue(ctx, issue.ID, params, getActorWithGit()) + } + if e != nil { + return struct{}{}, "", e + } + return struct{}{}, fmt.Sprintf("bd: close %s", issue.ID), nil + }) + if err != nil { + fmt.Fprintf(os.Stderr, "Error: failed to close %s: %v\n", issueID, err) + continue + } + closedIDs = append(closedIDs, issueID) + } + + if len(closedIDs) > 0 { + commandDidWrite.Store(true) + } + + if jsonOutput { + data, err := json.MarshalIndent(map[string]interface{}{ + "closed": closedIDs, + "reason": reason, + }, "", " ") + if err != nil { + return HandleError("failed to marshal JSON: %v", err) + } + fmt.Println(string(data)) + return nil + } + for _, id := range closedIDs { + fmt.Printf("Closed %s\n", ui.RenderID(id)) + } + return nil +}