diff --git a/.github/scripts/proxied-cmd-test-shards.txt b/.github/scripts/proxied-cmd-test-shards.txt index 1c78ab8f1..64225f9c9 100644 --- a/.github/scripts/proxied-cmd-test-shards.txt +++ b/.github/scripts/proxied-cmd-test-shards.txt @@ -71,6 +71,7 @@ 15 7 TestProxiedServerMolStale 15 7 TestProxiedServerReadyWisp 15 7 TestProxiedServerReclaim +15 7 TestProxiedServerRelate 15 8 TestProxiedServerCreate 15 8 TestProxiedServerGC @@ -101,6 +102,7 @@ 15 11 TestProxiedServerCompactHistory 15 11 TestProxiedServerDeleteWisp 15 11 TestProxiedServerEpic +15 11 TestProxiedServerHuman 15 11 TestProxiedServerInfo 15 11 TestProxiedServerMolDistill 15 11 TestProxiedServerReady diff --git a/.golangci.yml b/.golangci.yml index 43ead06a8..bb247e8f0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -276,7 +276,7 @@ linters: # # Commands with a direct route and a proxied twin that build the same # filter on both: - - path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|info|label|orphans|purge|search|status|todo|wisp)(_proxied_server)?\.go$' + - path: '^cmd/bd/(close|duplicates|find_duplicates|gate|gc|graph|human|info|label|orphans|purge|search|status|todo|wisp)(_proxied_server)?\.go$' linters: - forbidigo # Molecule reporting: each selects the members of one molecule. @@ -299,7 +299,7 @@ linters: linters: - forbidigo # One command each, no family to join. - - path: '^cmd/bd/(cleanup|completions|count|gate_discover|human|lint|ping|repo|swarm|template)\.go$' + - path: '^cmd/bd/(cleanup|completions|count|gate_discover|lint|ping|repo|swarm|template)\.go$' linters: - forbidigo # Tests are exempt for the same reason the depguard twin exempts them: diff --git a/cmd/bd/human.go b/cmd/bd/human.go index 7f987bfd3..482ebcd6c 100644 --- a/cmd/bd/human.go +++ b/cmd/bd/human.go @@ -120,6 +120,10 @@ Examples: ctx := rootCtx + if usesProxiedServer() { + return runHumanListProxiedServer(ctx, status) + } + filter := types.IssueFilter{ Labels: []string{"human"}, } @@ -214,6 +218,10 @@ Examples: ctx := rootCtx issueID := args[0] + if usesProxiedServer() { + return runHumanRespondProxiedServer(ctx, issueID, response) + } + // Direct mode if err := ensureStoreActive(); err != nil { return HandleErrorRespectJSON("responding to human bead: %v", err) @@ -297,6 +305,10 @@ Examples: ctx := rootCtx issueID := args[0] + if usesProxiedServer() { + return runHumanDismissProxiedServer(ctx, issueID, reason) + } + // Direct mode if err := ensureStoreActive(); err != nil { return HandleErrorRespectJSON("dismissing human bead: %v", err) @@ -373,6 +385,10 @@ Example: ctx := rootCtx + if usesProxiedServer() { + return runHumanStatsProxiedServer(ctx) + } + filter := types.IssueFilter{ Labels: []string{"human"}, } diff --git a/cmd/bd/human_proxied_integration_test.go b/cmd/bd/human_proxied_integration_test.go new file mode 100644 index 000000000..47043a7d4 --- /dev/null +++ b/cmd/bd/human_proxied_integration_test.go @@ -0,0 +1,205 @@ +//go:build cgo + +package main + +import ( + "os/exec" + "strings" + "testing" +) + +func bdProxiedHuman(t *testing.T, bd, dir string, args ...string) (string, string) { + t.Helper() + fullArgs := append([]string{"human"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...) + if err != nil { + t.Fatalf("bd human %s failed: %v\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), err, stdout, stderr) + } + return stdout, stderr +} + +func bdProxiedHumanFail(t *testing.T, bd, dir string, args ...string) string { + t.Helper() + fullArgs := append([]string{"human"}, args...) + stdout, stderr, err := bdProxiedRunBuffers(t, bd, dir, fullArgs...) + if err == nil { + t.Fatalf("expected bd human %s to fail, but succeeded:\nstdout:\n%s\nstderr:\n%s", + strings.Join(args, " "), stdout, stderr) + } + return stdout + stderr +} + +func bdProxiedLabelAdd(t *testing.T, bd, dir, id, label string) { + t.Helper() + cmd := exec.Command(bd, "label", "add", id, label) + cmd.Dir = dir + cmd.Env = bdProxiedEnv(dir) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("bd label add %s %s failed: %v\n%s", id, label, err, out) + } +} + +// TestProxiedServerHuman covers the bd-m7zzd port of the four `bd human` +// subcommands to proxied-server mode. Before it, each of them called +// ensureStoreActive(), which in proxied mode lazily opened a DIRECT store — +// silently bypassing the proxy, so writes landed outside the proxied commit +// scoping. The dolt_log assertions below are the behavioral check that the +// writes now ride the managed server's own commit plane, one commit with a +// real message per write invocation. +func TestProxiedServerHuman(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + + t.Run("list_and_stats_empty", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm1") + out, _ := bdProxiedHuman(t, bd, p.dir, "list") + if !strings.Contains(out, "No human-needed beads found") { + t.Errorf("expected empty human list message: %s", out) + } + statsOut, _ := bdProxiedHuman(t, bd, p.dir, "stats") + if !strings.Contains(statsOut, "Total:") || !strings.Contains(statsOut, "0") { + t.Errorf("expected zeroed stats output: %s", statsOut) + } + }) + + t.Run("respond_journey", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm2") + issue := bdProxiedCreate(t, bd, p.dir, "Needs a human", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, issue.ID, "human") + + listOut, _ := bdProxiedHuman(t, bd, p.dir, "list") + if !strings.Contains(listOut, issue.ID) { + t.Errorf("expected %s in human list:\n%s", issue.ID, listOut) + } + + db := openProxiedDB(t, p) + head := readDoltHead(t, db) + + out, _ := bdProxiedHuman(t, bd, p.dir, "respond", issue.ID, "--response", "Use OAuth2") + if !strings.Contains(out, "closed with response") { + t.Errorf("expected respond confirmation: %s", out) + } + + // The close and the comment are visible through the PROXIED read + // path — the write went through the proxy, not a direct store. + after := bdProxiedShow(t, bd, p.dir, issue.ID) + if string(after.Status) != "closed" { + t.Errorf("expected closed status after respond, got %s", after.Status) + } + if after.CloseReason != "Responded" { + t.Errorf("expected close reason 'Responded', got %q", after.CloseReason) + } + commentsOut, err := bdProxiedRun(t, bd, p.dir, "comments", issue.ID) + if err != nil { + t.Fatalf("bd comments failed: %v\n%s", err, commentsOut) + } + if !strings.Contains(string(commentsOut), "Response: Use OAuth2") { + t.Errorf("expected response comment:\n%s", commentsOut) + } + + // Comment + close landed as ONE commit on the managed server, with + // the invocation's own message. + if n := readDoltLogCountSince(t, db, head); n != 1 { + t.Errorf("expected exactly 1 commit for respond, got %d", n) + } + if msg := readDoltLogTopMessage(t, db); !strings.Contains(msg, "bd: human respond") { + t.Errorf("expected 'bd: human respond' commit message, got %q", msg) + } + }) + + t.Run("dismiss_journey", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm3") + issue := bdProxiedCreate(t, bd, p.dir, "Dismiss me", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, issue.ID, "human") + + db := openProxiedDB(t, p) + head := readDoltHead(t, db) + + out, _ := bdProxiedHuman(t, bd, p.dir, "dismiss", issue.ID, "--reason", "Not needed") + if !strings.Contains(out, "dismissed") { + t.Errorf("expected dismiss confirmation: %s", out) + } + + after := bdProxiedShow(t, bd, p.dir, issue.ID) + if string(after.Status) != "closed" { + t.Errorf("expected closed status after dismiss, got %s", after.Status) + } + if after.CloseReason != "Dismissed: Not needed" { + t.Errorf("expected close reason 'Dismissed: Not needed', got %q", after.CloseReason) + } + + if n := readDoltLogCountSince(t, db, head); n != 1 { + t.Errorf("expected exactly 1 commit for dismiss, got %d", n) + } + if msg := readDoltLogTopMessage(t, db); !strings.Contains(msg, "bd: human dismiss") { + t.Errorf("expected 'bd: human dismiss' commit message, got %q", msg) + } + }) + + t.Run("respond_without_label_warns", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm4") + issue := bdProxiedCreate(t, bd, p.dir, "Unlabeled", "--type", "task") + _, stderr := bdProxiedHuman(t, bd, p.dir, "respond", issue.ID, "--response", "ok") + if !strings.Contains(stderr, "does not have 'human' label") { + t.Errorf("expected missing-label warning on stderr: %s", stderr) + } + }) + + t.Run("respond_refusals", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm5") + + out := bdProxiedHumanFail(t, bd, p.dir, "respond", "hm5-nonexistent", "--response", "ok") + if !strings.Contains(out, "issue not found") { + t.Errorf("expected 'issue not found' refusal: %s", out) + } + if strings.Contains(out, "storage is nil") { + t.Errorf("opaque 'storage is nil' error leaked through: %s", out) + } + + issue := bdProxiedCreate(t, bd, p.dir, "Already closed", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, issue.ID, "human") + bdProxiedHuman(t, bd, p.dir, "dismiss", issue.ID) + out = bdProxiedHumanFail(t, bd, p.dir, "respond", issue.ID, "--response", "late") + if !strings.Contains(out, "already closed") { + t.Errorf("expected already-closed refusal: %s", out) + } + }) + + t.Run("stats_counts", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "hm6") + + pending := bdProxiedCreate(t, bd, p.dir, "Pending", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, pending.ID, "human") + responded := bdProxiedCreate(t, bd, p.dir, "Responded", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, responded.ID, "human") + dismissed := bdProxiedCreate(t, bd, p.dir, "Dismissed", "--type", "task") + bdProxiedLabelAdd(t, bd, p.dir, dismissed.ID, "human") + + bdProxiedHuman(t, bd, p.dir, "respond", responded.ID, "--response", "done") + bdProxiedHuman(t, bd, p.dir, "dismiss", dismissed.ID) + + out, _ := bdProxiedHuman(t, bd, p.dir, "stats") + for _, want := range []string{"Total: 3", "Pending: 1", "Responded: 1", "Dismissed: 1"} { + if !strings.Contains(out, want) { + t.Errorf("expected %q in stats output:\n%s", want, out) + } + } + + // And the closed pair drops out of the open list. + listOut, _ := bdProxiedHuman(t, bd, p.dir, "list", "--status", "open") + if !strings.Contains(listOut, pending.ID) { + t.Errorf("expected %s in open human list:\n%s", pending.ID, listOut) + } + if strings.Contains(listOut, responded.ID) || strings.Contains(listOut, dismissed.ID) { + t.Errorf("closed beads leaked into open human list:\n%s", listOut) + } + }) +} diff --git a/cmd/bd/human_proxied_server.go b/cmd/bd/human_proxied_server.go new file mode 100644 index 000000000..b007af022 --- /dev/null +++ b/cmd/bd/human_proxied_server.go @@ -0,0 +1,176 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "os" + + "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" +) + +// The proxied-server twins of the four `bd human` subcommands. The direct +// route reaches storage through ensureStoreActive(), which in proxied mode +// would lazily open a DIRECT store and silently bypass the proxy (bd-m7zzd) — +// so each RunE branches here BEFORE that call. Reads ride one read-only unit +// of work; each write invocation is exactly ONE RunTx with a real commit +// message, per the proxied write convention. + +// proxiedHumanSearch runs the shared human-label query and hands back the +// issues, inside the caller's unit of work. +func proxiedHumanSearch(ctx context.Context, uw uow.UnitOfWork, status string) ([]*types.Issue, error) { + filter := types.IssueFilter{ + Labels: []string{"human"}, + } + if status != "" { + s := types.Status(status) + filter.Status = &s + } + page, err := uw.IssueUseCase().SearchIssues(ctx, "", filter) + if err != nil { + return nil, err + } + return page.Items, nil +} + +func runHumanListProxiedServer(ctx context.Context, status string) error { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return HandleErrorRespectJSON("listing human beads: %v", err) + } + defer uw.Close(ctx) + + issues, err := proxiedHumanSearch(ctx, uw, status) + if err != nil { + return HandleErrorRespectJSON("listing human beads: %v", err) + } + + if jsonOutput { + issueIDs := make([]string, len(issues)) + for i, issue := range issues { + issueIDs[i] = issue.ID + } + labelsMap, _ := uw.LabelUseCase().GetLabelsForIssues(ctx, issueIDs) + for _, issue := range issues { + issue.Labels = labelsMap[issue.ID] + } + + data, err := json.MarshalIndent(issues, "", " ") + if err != nil { + return HandleErrorRespectJSON("encoding JSON: %v", err) + } + fmt.Println(string(data)) + return nil + } + + printHumanList(issues) + return nil +} + +func runHumanStatsProxiedServer(ctx context.Context) error { + uw, err := proxiedOpenReadUOW(ctx) + if err != nil { + return HandleErrorRespectJSON("getting human bead stats: %v", err) + } + defer uw.Close(ctx) + + issues, err := proxiedHumanSearch(ctx, uw, "") + if err != nil { + return HandleErrorRespectJSON("getting human bead stats: %v", err) + } + + printHumanStats(issues) + return nil +} + +// proxiedHumanCloseTarget is the shared pre-flight for respond and dismiss, +// run INSIDE the write transaction so the already-closed verdict and the close +// ride the same snapshot: the classic existence / already-closed refusals with +// their exact wording, plus the missing-'human'-label observation the caller +// warns about after the transaction lands. +func proxiedHumanCloseTarget(ctx context.Context, uw uow.UnitOfWork, issueID string) (hasHumanLabel bool, err error) { + issue, err := proxiedRequireIssue(ctx, uw, issueID) + if err != nil { + return false, err + } + if issue == nil { + return false, fmt.Errorf("issue not found: %s", issueID) + } + if issue.Status == types.StatusClosed { + return false, fmt.Errorf("issue %s is already closed", issueID) + } + + labelsMap, _ := uw.LabelUseCase().GetLabelsForIssues(ctx, []string{issueID}) + for _, label := range labelsMap[issueID] { + if label == "human" { + return true, nil + } + } + return false, nil +} + +func runHumanRespondProxiedServer(ctx context.Context, issueID, response string) error { + if uowProvider == nil { + return HandleErrorRespectJSON("proxied-server UOW provider not initialized") + } + + hasHumanLabel, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (bool, string, error) { + hasLabel, err := proxiedHumanCloseTarget(ctx, uw, issueID) + if err != nil { + return false, "", err + } + commentText := fmt.Sprintf("Response: %s", response) + if _, err := uw.CommentUseCase().AddCommentToIssue(ctx, issueID, actor, commentText); err != nil { + return false, "", fmt.Errorf("adding comment: %w", err) + } + if _, err := uw.IssueUseCase().CloseIssue(ctx, issueID, domain.CloseIssueParams{Reason: "Responded"}, actor); err != nil { + return false, "", fmt.Errorf("closing bead: %w", err) + } + return hasLabel, fmt.Sprintf("bd: human respond %s", issueID), nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + if !hasHumanLabel { + fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", issueID) + } + + fmt.Printf("%s Bead %s closed with response.\n", ui.RenderPass("✔"), issueID) + return nil +} + +func runHumanDismissProxiedServer(ctx context.Context, issueID, reason string) error { + if uowProvider == nil { + return HandleErrorRespectJSON("proxied-server UOW provider not initialized") + } + + closeReason := "Dismissed" + if reason != "" { + closeReason = fmt.Sprintf("Dismissed: %s", reason) + } + + hasHumanLabel, err := uow.RunTxResult(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (bool, string, error) { + hasLabel, err := proxiedHumanCloseTarget(ctx, uw, issueID) + if err != nil { + return false, "", err + } + if _, err := uw.IssueUseCase().CloseIssue(ctx, issueID, domain.CloseIssueParams{Reason: closeReason}, actor); err != nil { + return false, "", fmt.Errorf("closing bead: %w", err) + } + return hasLabel, fmt.Sprintf("bd: human dismiss %s", issueID), nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + if !hasHumanLabel { + fmt.Fprintf(os.Stderr, "Warning: Issue %s does not have 'human' label\n", issueID) + } + + fmt.Printf("%s Bead %s dismissed.\n", ui.RenderPass("✔"), issueID) + return nil +} diff --git a/cmd/bd/main.go b/cmd/bd/main.go index e8275faf6..2068d1169 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -1064,6 +1064,13 @@ var rootCmd = &cobra.Command{ // silently skipped if "remote" were ever added to noDbCommands. needsStoreDoltGrandchildren := []string{"remote"} + // bd-m7zzd: "human" is listed in noDbCommands for its bare help + // screen, but list/respond/dismiss/stats are DB-backed. Without this + // they skip store init entirely, which direct mode papered over by + // lazily opening a store via ensureStoreActive() — and which in + // proxied mode left no UOW provider for the proxied duals. + needsStoreHumanSubcommands := []string{"list", "respond", "dismiss", "stats"} + skipStoreMigrateSubcommands := []string{"from-server-to-proxied-server", "from-proxied-server-to-server", "from-shared-server-to-proxied-server", "from-proxied-server-to-shared-server"} // Check both the command name and parent command name for subcommands @@ -1076,6 +1083,8 @@ var rootCmd = &cobra.Command{ // GH#2042: dolt push/pull/commit need the store — fall through to init } else if slices.Contains(needsStoreDoltGrandchildren, parentName) { // GH#2224: dolt remote add/list/remove need the store — fall through to init + } else if parentName == "human" && slices.Contains(needsStoreHumanSubcommands, cmdName) { + // bd-m7zzd: human list/respond/dismiss/stats need the store — fall through to init } else if parentName == "migrate" && slices.Contains(skipStoreMigrateSubcommands, cmdName) { skipsStoreInit = true } else if slices.Contains(noDbCommands, parentName) { diff --git a/cmd/bd/relate.go b/cmd/bd/relate.go index ca8fe8073..987ccdff9 100644 --- a/cmd/bd/relate.go +++ b/cmd/bd/relate.go @@ -63,6 +63,10 @@ func runRelate(cmd *cobra.Command, args []string) error { ctx := rootCtx + if usesProxiedServer() { + return runRelateProxiedServer(ctx, args) + } + // Resolve partial IDs var id1, id2 string var err error @@ -147,6 +151,10 @@ func runUnrelate(cmd *cobra.Command, args []string) error { ctx := rootCtx + if usesProxiedServer() { + return runUnrelateProxiedServer(ctx, args) + } + // Resolve partial IDs var id1, id2 string var err error diff --git a/cmd/bd/relate_proxied_integration_test.go b/cmd/bd/relate_proxied_integration_test.go new file mode 100644 index 000000000..d272617b2 --- /dev/null +++ b/cmd/bd/relate_proxied_integration_test.go @@ -0,0 +1,149 @@ +//go:build cgo + +package main + +import ( + "context" + "database/sql" + "strings" + "testing" +) + +// TestProxiedServerRelate covers the bd-m7zzd port of `bd dep relate` / +// `bd dep unrelate` to proxied-server mode: before it, both verbs died with +// the opaque "cannot resolve issue ID: storage is nil" (id_parser.go) because +// runRelate/runUnrelate had no usesProxiedServer() branch. +func TestProxiedServerRelate(t *testing.T) { + requireSharedProxiedServer(t) + t.Parallel() + bd := buildEmbeddedBD(t) + + countRelatesTo := func(t *testing.T, db *sql.DB, issueID, dependsOnID string) int { + t.Helper() + var count int + err := db.QueryRowContext(context.Background(), + "SELECT COUNT(*) FROM dependencies WHERE issue_id = ? AND COALESCE(depends_on_issue_id, depends_on_wisp_id, depends_on_external) = ? AND type = ?", + issueID, dependsOnID, "relates-to").Scan(&count) + if err != nil { + t.Fatalf("query relates-to %s -> %s: %v", issueID, dependsOnID, err) + } + return count + } + + t.Run("relate_happy_path", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rl1") + a := bdProxiedCreate(t, bd, p.dir, "Relate A", "--type", "task") + b := bdProxiedCreate(t, bd, p.dir, "Relate B", "--type", "task") + + db := openProxiedDB(t, p) + head := readDoltHead(t, db) + + out := bdProxiedDep(t, bd, p.dir, "relate", a.ID, b.ID) + if !strings.Contains(out, "Linked") { + t.Errorf("expected 'Linked' output: %s", out) + } + + // Bidirectional: both directed relates-to edges landed. + assertProxiedDepExistsWithType(t, db, a.ID, b.ID, "relates-to") + assertProxiedDepExistsWithType(t, db, b.ID, a.ID, "relates-to") + + // ONE transaction with a real commit message: both edges rode a + // single Dolt commit. + if n := readDoltLogCountSince(t, db, head); n != 1 { + t.Errorf("expected exactly 1 commit for relate, got %d", n) + } + if msg := readDoltLogTopMessage(t, db); !strings.Contains(msg, "bd: relate") { + t.Errorf("expected 'bd: relate' commit message, got %q", msg) + } + }) + + t.Run("relate_json", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rl2") + a := bdProxiedCreate(t, bd, p.dir, "JSON A", "--type", "task") + b := bdProxiedCreate(t, bd, p.dir, "JSON B", "--type", "task") + m := bdProxiedDepJSON(t, bd, p.dir, "relate", a.ID, b.ID) + if related, _ := m["related"].(bool); !related { + t.Errorf("expected related=true in JSON output: %v", m) + } + if m["id1"] != a.ID || m["id2"] != b.ID { + t.Errorf("expected ids %s/%s in JSON output: %v", a.ID, b.ID, m) + } + }) + + t.Run("unrelate_removes_both_directions", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rl3") + a := bdProxiedCreate(t, bd, p.dir, "Unrelate A", "--type", "task") + b := bdProxiedCreate(t, bd, p.dir, "Unrelate B", "--type", "task") + bdProxiedDep(t, bd, p.dir, "relate", a.ID, b.ID) + + db := openProxiedDB(t, p) + head := readDoltHead(t, db) + + out := bdProxiedDep(t, bd, p.dir, "unrelate", a.ID, b.ID) + if !strings.Contains(out, "Unlinked") { + t.Errorf("expected 'Unlinked' output: %s", out) + } + if n := countRelatesTo(t, db, a.ID, b.ID); n != 0 { + t.Errorf("expected relates-to %s -> %s gone, found %d", a.ID, b.ID, n) + } + if n := countRelatesTo(t, db, b.ID, a.ID); n != 0 { + t.Errorf("expected relates-to %s -> %s gone, found %d", b.ID, a.ID, n) + } + if n := readDoltLogCountSince(t, db, head); n != 1 { + t.Errorf("expected exactly 1 commit for unrelate, got %d", n) + } + if msg := readDoltLogTopMessage(t, db); !strings.Contains(msg, "bd: unrelate") { + t.Errorf("expected 'bd: unrelate' commit message, got %q", msg) + } + }) + + t.Run("unrelate_idempotent_no_commit", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rl4") + a := bdProxiedCreate(t, bd, p.dir, "Idem A", "--type", "task") + b := bdProxiedCreate(t, bd, p.dir, "Idem B", "--type", "task") + + db := openProxiedDB(t, p) + head := readDoltHead(t, db) + + // No edge exists: still a success (matches the direct route), and a + // deliberate no-commit no-op. + out := bdProxiedDep(t, bd, p.dir, "unrelate", a.ID, b.ID) + if !strings.Contains(out, "Unlinked") { + t.Errorf("expected 'Unlinked' output: %s", out) + } + if n := readDoltLogCountSince(t, db, head); n != 0 { + t.Errorf("expected no commit for no-op unrelate, got %d", n) + } + }) + + t.Run("self_relate_refused", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rl5") + a := bdProxiedCreate(t, bd, p.dir, "Self A", "--type", "task") + out := bdProxiedDepFail(t, bd, p.dir, "relate", a.ID, a.ID) + if !strings.Contains(out, "cannot relate an issue to itself") { + t.Errorf("expected self-relate refusal: %s", out) + } + }) + + t.Run("missing_issue_clean_error_not_storage_nil", func(t *testing.T) { + t.Parallel() + p := newSharedProxiedProject(t, bd, "rl6") + a := bdProxiedCreate(t, bd, p.dir, "Lonely A", "--type", "task") + + for _, verb := range []string{"relate", "unrelate"} { + out := bdProxiedDepFail(t, bd, p.dir, verb, a.ID, "rl6-nonexistent") + if !strings.Contains(out, "issue not found") { + t.Errorf("%s: expected 'issue not found' refusal: %s", verb, out) + } + // The bd-m7zzd seam itself: the opaque nil-storage death is gone. + if strings.Contains(out, "storage is nil") { + t.Errorf("%s: opaque 'storage is nil' error leaked through: %s", verb, out) + } + } + }) +} diff --git a/cmd/bd/relate_proxied_server.go b/cmd/bd/relate_proxied_server.go new file mode 100644 index 000000000..601b1a30d --- /dev/null +++ b/cmd/bd/relate_proxied_server.go @@ -0,0 +1,141 @@ +package main + +import ( + "context" + "database/sql" + "errors" + "fmt" + + "github.com/steveyegge/beads/internal/storage" + "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" +) + +// proxiedRequireIssue mirrors the direct route's pre-flight for the verbs that +// refuse a ghost endpoint with the classic "issue not found" wording: it reads +// the durable issue row through the unit of work and normalizes both not-found +// shapes (a sentinel error or a nil row) into one nil-issue answer the caller +// turns into the classic message. Exact canonical ids only — proxied mode does +// no partial-id resolution, matching every other proxied verb. +func proxiedRequireIssue(ctx context.Context, uw uow.UnitOfWork, id string) (*types.Issue, error) { + issue, err := uw.IssueUseCase().GetIssue(ctx, id) + if err != nil { + if errors.Is(err, storage.ErrNotFound) || errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, fmt.Errorf("failed to get issue %s: %w", id, err) + } + return issue, nil +} + +// runRelateProxiedServer is the proxied-server twin of runRelate: both +// directed relates-to edges land in ONE unit of work under one commit message, +// where the direct route's two AddDependencyWithOptions calls ride the shared +// store transaction. The bidirectional pair cannot trip the cycle gates — +// relates-to is not a scheduling type, so both the per-edge probe and the +// whole-graph gate skip it by design. +func runRelateProxiedServer(ctx context.Context, args []string) error { + id1 := args[0] + id2 := args[1] + + if id1 == id2 { + return HandleErrorRespectJSON("cannot relate an issue to itself") + } + if uowProvider == nil { + return HandleErrorRespectJSON("proxied-server UOW provider not initialized") + } + + err := uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) { + // The direct route refuses a missing endpoint before writing anything; + // keep its exact wording rather than the bulk path's anonymous + // ghost-source refusal (bd-yby99.9). + for _, id := range []string{id1, id2} { + issue, err := proxiedRequireIssue(ctx, uw, id) + if err != nil { + return "", err + } + if issue == nil { + return "", fmt.Errorf("issue not found: %s", id) + } + } + deps := []*types.Dependency{ + {IssueID: id1, DependsOnID: id2, Type: types.DepRelatesTo}, + {IssueID: id2, DependsOnID: id1, Type: types.DepRelatesTo}, + } + // bd relate is an explicit dependency verb, so the bulk path's + // EmitEvent trail matches the direct route's history behavior. + if _, err := uw.DependencyUseCase().AddDependencies(ctx, deps, actor, domain.BulkAddDepsOpts{}); err != nil { + return "", err + } + return fmt.Sprintf("bd: relate %s %s", id1, id2), nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "id1": id1, + "id2": id2, + "related": true, + }) + } + + fmt.Printf("%s Linked %s ↔ %s\n", ui.RenderPass("✓"), id1, id2) + return nil +} + +// runUnrelateProxiedServer is the proxied-server twin of runUnrelate: both +// directed removals ride ONE unit of work. Removal is idempotent on each +// direction (a missing edge is a success, like the direct route), and a pair +// that removed nothing returns an empty commit message — the deliberate +// no-commit no-op, the same answer the DependencyEditor role gives a removal +// that found no edge. +func runUnrelateProxiedServer(ctx context.Context, args []string) error { + id1 := args[0] + id2 := args[1] + + if uowProvider == nil { + return HandleErrorRespectJSON("proxied-server UOW provider not initialized") + } + + err := uow.RunTx(ctx, uowProvider, func(ctx context.Context, uw uow.UnitOfWork) (string, error) { + for _, id := range []string{id1, id2} { + issue, err := proxiedRequireIssue(ctx, uw, id) + if err != nil { + return "", err + } + if issue == nil { + return "", fmt.Errorf("issue not found: %s", id) + } + } + removed1, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, id1, id2, actor) + if err != nil { + return "", fmt.Errorf("failed to remove relates-to %s -> %s: %w", id1, id2, err) + } + removed2, err := uw.DependencyUseCase().RemoveDependencyBySource(ctx, id2, id1, actor) + if err != nil { + return "", fmt.Errorf("failed to remove relates-to %s -> %s: %w", id2, id1, err) + } + if !removed1 && !removed2 { + return "", nil + } + return fmt.Sprintf("bd: unrelate %s %s", id1, id2), nil + }) + if err != nil { + return HandleErrorRespectJSON("%v", err) + } + + if jsonOutput { + return outputJSON(map[string]interface{}{ + "id1": id1, + "id2": id2, + "unrelated": true, + }) + } + + fmt.Printf("%s Unlinked %s ↔ %s\n", ui.RenderPass("✓"), id1, id2) + return nil +}