beads/cmd/bd/dep_test.go
Julian Knutsen d15958a5eb
fix(issueops): enforce the dotted-child dependency rule on every leg (#7424)
* fix(issueops): enforce the dotted-child dependency rule on every leg

The refusal of an explicit edge from a dotted-id child to its own ancestor
(bd-abc.1 -> bd-abc; only the parent-child edge to the immediate dotted
parent is allowed) lived only in cmd/bd (isDisallowedHierarchicalDependency).
HTTP dependencies:add, batch:apply dep_add items and `bd create --graph`'s own
edges skipped it.

It is now one library rule, issueops.CheckDottedChildDependency, returning
*issueops.DottedChildDependencyError (unwraps to ErrValidation, same message
the CLI printed):
- ValidateAddDependenciesRequest applies it, so DependencyEditor refuses on
  dolt, embedded, uow and the server behind httpapi (400 invalid_argument);
- both BatchApplier bodies (issueops and uow) apply it to each dep_add item on
  the resolved ids, so a key bound to a minted dotted child is refused too;
- the HTTP client checks it before the dial, as it does self-dependency, so
  the typed error survives the wire.

cmd/bd keeps no copy: single-edge dep add / dep --blocks rely on the role;
bd link (still on the store verb) and the --file bulk reporter call the
library rule. CLI output is byte-identical (checked against origin/main).

Conformance: RunDependencyEditorRefusesADottedChildGatedOnItsOwnParent and
RunBatchApplyRefusesADottedChildGatedOnItsOwnParent wired on dolt, embedded,
uow and http, plus a raw-wire served test past the client check and handler
mapping cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(batch): refuse a dotted child gated on its own ancestor in bd batch

Review fixup for PR #7424 (iterations 1 and 2).

Major: a bd batch script line `dep add bd-abc.1 bd-abc` still wrote the
edge this PR refuses everywhere else, on both backends. Neither batch
dispatch writes through the DependencyEditor role that enforces the
dotted-child rule: the classic arm calls storage.Transaction.AddDependency
and the proxied arm the unit of work's AddDependencies verb. Both arms now
build the edge with one helper, batchDepAddEdge, which keeps the default
type and the arity and type errors, and asks
publicops.CheckDottedChildDependency the way bd link does. A refused line
rolls the whole batch back.

Tests: TestBatchDepAddEdge (default and explicit types, arity and type
errors, three refusals typed *DottedChildDependencyError matching
ErrValidation, and the immediate parent-child edge allowed), and
TestProxiedServerBatchDepAddRefusesADottedChildGatedOnItsParent (classic
and proxied: the refusal names line 2, rolls back an earlier update line
and writes no edge, and `dep add C P parent-child` still lands exactly
one), registered in the proxied shard manifest. A mutant that drops the
rule from the shared helper fails both; one that bypasses the helper in
the proxied arm alone fails the proxied leg.

Minors:
- For a child whose parent-child edge is already stored (a
  `bd create --parent` child) the rule answers ahead of the hierarchy and
  type conflicts, so an HTTP caller now gets 400 invalid_argument where it
  got 409 dependency_cycle (blocking types) or dependency_exists (any
  other type). Documented in the DependencyEditor role doc, the CHANGELOG
  entry and the httpapi batch-apply test comment, and pinned by a
  stored-hierarchy phase in the DependencyEditor and BatchApplier
  dotted-child conformance contracts on every leg; a mutant that drops the
  rule gets the hierarchy conflict instead (409 dependency_cycle on the
  wire).
- The bd create --graph dry-run note now says the live create may also
  refuse an edge that gates a dotted-id child on its own ancestor.
- The DottedChildDependencyError comment says the message is kept verbatim
  and says "deadlock" whatever the type.

Not changed: bd relate (relates-to does not schedule) and the edges a
create writes with its issue (bd create --deps/--waits-for, and over
HTTP an explicit dotted id with a non-immediate ParentID) still write
through paths that skip the rule. The scheduling shapes need an explicit
dotted id or a grandparent target. Follow-up bd-25s1wh tracks moving the
rule down to the domain/store add verbs, with a structural bypass for
reparent and template edges.

Iteration 2 (minor): the CheckDottedChildDependency doc no longer implies
bd link and bd batch are the only writers outside the roles. It names
bd relate and the create edges as not applying the rule yet and cites
bd-25s1wh.

Complexity (cyclomatic/cognitive): runBatchOp 23/35 -> 21/31,
runBatchOpUOW 28/48 -> 26/44, batchDepAddEdge 5/4. Touching them brings
both pre-existing dispatch switches into the measured set; splitting them
is out of scope here.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(issueops,httpapi): document the dotted-child 400 and widen its gap list

Review fixup for PR #7424 (relaunch, iteration 1, minors).

- The OpenAPI spec now describes the wire change this PR makes. The
  dependencies:add and issues:batchApply 400 vocabularies name an edge
  from a dotted-id child to its own ancestor (anything but the
  parent-child edge to its immediate parent; param `edges` and `items`).
  dependencies:add says why that is request-intrinsic, and both 409s say
  it is never dependency_cycle or dependency_exists, even for a child
  whose parent-child edge is stored. Response descriptions only: the
  generated types and the wireshape digest are unchanged (make api-check).
- The CheckDottedChildDependency doc no longer reads as a complete list of
  the writers that skip the rule. Besides bd relate and the create edges
  it names bd duplicate, bd supersede, bd duplicates --auto-merge (its
  related link and its reparenting) and the tracker engine's
  createDependencies, and says the molecule, template and swarm writers
  are unaudited. bd-25s1wh's notes carry the widened scope, including
  `bd duplicate bd-a.1 --of bd-a`.

Declined (nit): unifying the root issueops import alias across the PR's
cmd/bd files. batch.go is the one file that imports both issueops
packages, so one of them needs an alias there; it uses publicops, the
repo's usual alias for the root package, and aliasing the other side
instead would rewrite base-owned lines.

Agent-Signature: claude-code-claude-opus-5-5-max on behalf of Gas City Adopt-PR
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 22:56:46 +00:00

1315 lines
37 KiB
Go

//go:build cgo
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/dolt"
storageissueops "github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func TestDependencySuite(t *testing.T) {
t.Parallel()
tmpDir := t.TempDir()
testDB := filepath.Join(tmpDir, ".beads", "beads.db")
s := newTestStore(t, testDB)
ctx := context.Background()
t.Run("DepAdd", func(t *testing.T) {
// Create test issues
issues := []*types.Issue{
{
ID: "test-1",
Title: "Task 1",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
},
{
ID: "test-2",
Title: "Task 2",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
},
}
for _, issue := range issues {
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Add dependency
dep := &types.Dependency{
IssueID: "test-1",
DependsOnID: "test-2",
Type: types.DepBlocks,
CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("AddDependency failed: %v", err)
}
// Verify dependency was added
deps, err := s.GetDependencies(ctx, "test-1")
if err != nil {
t.Fatalf("GetDependencies failed: %v", err)
}
if len(deps) != 1 {
t.Fatalf("Expected 1 dependency, got %d", len(deps))
}
if deps[0].ID != "test-2" {
t.Errorf("Expected dependency on test-2, got %s", deps[0].ID)
}
})
t.Run("DepTypes", func(t *testing.T) {
// Create test issues
for i := 1; i <= 4; i++ {
issue := &types.Issue{
ID: fmt.Sprintf("test-types-%d", i),
Title: fmt.Sprintf("Task %d", i),
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
}
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Test different dependency types (without creating cycles)
depTypes := []struct {
depType types.DependencyType
from string
to string
}{
{types.DepBlocks, "test-types-2", "test-types-1"},
{types.DepRelated, "test-types-3", "test-types-1"},
{types.DepParentChild, "test-types-4", "test-types-1"},
{types.DepDiscoveredFrom, "test-types-3", "test-types-2"},
}
for _, dt := range depTypes {
dep := &types.Dependency{
IssueID: dt.from,
DependsOnID: dt.to,
Type: dt.depType,
CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("AddDependency failed for type %s: %v", dt.depType, err)
}
}
})
t.Run("DepCycleDetection", func(t *testing.T) {
// Create test issues
for i := 1; i <= 3; i++ {
issue := &types.Issue{
ID: fmt.Sprintf("test-cycle-%d", i),
Title: fmt.Sprintf("Task %d", i),
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
}
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Create a cycle: test-cycle-1 -> test-cycle-2 -> test-cycle-3 -> test-cycle-1
// Add first two deps successfully
deps := []struct {
from string
to string
}{
{"test-cycle-1", "test-cycle-2"},
{"test-cycle-2", "test-cycle-3"},
}
for _, d := range deps {
dep := &types.Dependency{
IssueID: d.from,
DependsOnID: d.to,
Type: types.DepBlocks,
CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("AddDependency failed: %v", err)
}
}
// Try to add the third dep which would create a cycle - should fail
cycleDep := &types.Dependency{
IssueID: "test-cycle-3",
DependsOnID: "test-cycle-1",
Type: types.DepBlocks,
CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, cycleDep, "test"); err == nil {
t.Fatal("Expected AddDependency to fail when creating cycle, but it succeeded")
}
// Since cycle detection prevented the cycle, DetectCycles should find no cycles
cycles, err := s.DetectCycles(ctx)
if err != nil {
t.Fatalf("DetectCycles failed: %v", err)
}
if len(cycles) != 0 {
t.Error("Expected no cycles since cycle was prevented")
}
})
t.Run("DepRemove", func(t *testing.T) {
// Create test issues
issues := []*types.Issue{
{
ID: "test-remove-1",
Title: "Task 1",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
},
{
ID: "test-remove-2",
Title: "Task 2",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeTask,
CreatedAt: time.Now(),
},
}
for _, issue := range issues {
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// Add dependency
dep := &types.Dependency{
IssueID: "test-remove-1",
DependsOnID: "test-remove-2",
Type: types.DepBlocks,
CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatal(err)
}
// Remove dependency
if err := s.RemoveDependency(ctx, "test-remove-1", "test-remove-2", "test"); err != nil {
t.Fatalf("RemoveDependency failed: %v", err)
}
// Verify dependency was removed
deps, err := s.GetDependencies(ctx, "test-remove-1")
if err != nil {
t.Fatalf("GetDependencies failed: %v", err)
}
if len(deps) != 0 {
t.Errorf("Expected 0 dependencies after removal, got %d", len(deps))
}
})
// Merged from TestDepBlocksFlagFunctionality — tests --blocks flag semantics
t.Run("BlocksFlagFunctionality", func(t *testing.T) {
issues := []*types.Issue{
{ID: "test-blocks-1", Title: "Blocker Issue", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now()},
{ID: "test-blocks-2", Title: "Blocked Issue", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now()},
}
for _, issue := range issues {
if err := s.CreateIssue(ctx, issue, "test"); err != nil {
t.Fatal(err)
}
}
// "blocker --blocks blocked" means blocked depends on blocker
dep := &types.Dependency{
IssueID: "test-blocks-2",
DependsOnID: "test-blocks-1",
Type: types.DepBlocks,
CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("AddDependency failed: %v", err)
}
deps, err := s.GetDependencies(ctx, "test-blocks-2")
if err != nil {
t.Fatalf("GetDependencies failed: %v", err)
}
if len(deps) != 1 {
t.Fatalf("Expected 1 dependency, got %d", len(deps))
}
if deps[0].ID != "test-blocks-1" {
t.Errorf("Expected blocked issue to depend on test-blocks-1, got %s", deps[0].ID)
}
dependents, err := s.GetDependents(ctx, "test-blocks-1")
if err != nil {
t.Fatalf("GetDependents failed: %v", err)
}
if len(dependents) != 1 {
t.Fatalf("Expected 1 dependent, got %d", len(dependents))
}
if dependents[0].ID != "test-blocks-2" {
t.Errorf("Expected test-blocks-1 to have dependent test-blocks-2, got %s", dependents[0].ID)
}
})
// Merged from TestDepAdd_FKError* and TestDepRemove_FKError — tests
// that FK constraint violations produce user-friendly error messages.
t.Run("FKError_InvalidFromID", func(t *testing.T) {
validIssue := &types.Issue{
ID: "test-fk-valid", Title: "Valid Issue", Status: types.StatusOpen,
Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now(),
}
if err := s.CreateIssue(ctx, validIssue, "test"); err != nil {
t.Fatal(err)
}
dep := &types.Dependency{
IssueID: "test-nonexistent-from", DependsOnID: "test-fk-valid",
Type: types.DepBlocks, CreatedAt: time.Now(),
}
err := s.AddDependency(ctx, dep, "test")
if err == nil {
t.Fatal("Expected error when adding dependency with invalid from ID")
}
errMsg := err.Error()
if strings.Contains(errMsg, "FOREIGN KEY constraint failed") || strings.Contains(errMsg, "foreign key constraint failed") {
t.Errorf("Error exposes raw FK constraint: %q", errMsg)
}
if !strings.Contains(errMsg, "not found") && !strings.Contains(errMsg, "Not Found") {
t.Errorf("Error message should indicate issue not found: %q", errMsg)
}
})
t.Run("FKError_InvalidToID", func(t *testing.T) {
dep := &types.Dependency{
IssueID: "test-fk-valid", DependsOnID: "test-nonexistent-to",
Type: types.DepBlocks, CreatedAt: time.Now(),
}
err := s.AddDependency(ctx, dep, "test")
if err == nil {
t.Fatal("Expected error when adding dependency with invalid to ID")
}
errMsg := err.Error()
if strings.Contains(errMsg, "FOREIGN KEY constraint failed") || strings.Contains(errMsg, "foreign key constraint failed") {
t.Errorf("Error exposes raw FK constraint: %q", errMsg)
}
if !strings.Contains(errMsg, "not found") && !strings.Contains(errMsg, "Not Found") {
t.Errorf("Error message should indicate dependency target not found: %q", errMsg)
}
})
t.Run("FKError_BothInvalid", func(t *testing.T) {
dep := &types.Dependency{
IssueID: "test-nonexistent-1", DependsOnID: "test-nonexistent-2",
Type: types.DepBlocks, CreatedAt: time.Now(),
}
err := s.AddDependency(ctx, dep, "test")
if err == nil {
t.Fatal("Expected error when adding dependency with both invalid IDs")
}
errMsg := err.Error()
if strings.Contains(errMsg, "FOREIGN KEY constraint failed") || strings.Contains(errMsg, "foreign key constraint failed") {
t.Errorf("Error exposes raw FK constraint: %q", errMsg)
}
if !strings.Contains(errMsg, "not found") && !strings.Contains(errMsg, "Not Found") {
t.Errorf("Error message should indicate issue not found: %q", errMsg)
}
})
t.Run("FKError_JSONMode", func(t *testing.T) {
dep := &types.Dependency{
IssueID: "test-fk-valid", DependsOnID: "test-json-nonexistent",
Type: types.DepBlocks, CreatedAt: time.Now(),
}
err := s.AddDependency(ctx, dep, "test")
if err == nil {
t.Fatal("Expected error when adding dependency with invalid ID")
}
if strings.Contains(err.Error(), "FOREIGN KEY") {
t.Errorf("Error exposes raw FK constraint (JSON mode): %q", err.Error())
}
})
t.Run("FKError_DaemonMode", func(t *testing.T) {
dep := &types.Dependency{
IssueID: "test-fk-valid", DependsOnID: "test-daemon-nonexistent",
Type: types.DepBlocks, CreatedAt: time.Now(),
}
err := s.AddDependency(ctx, dep, "test")
if err == nil {
t.Fatal("Expected error when adding dependency with invalid ID via daemon path")
}
errMsg := err.Error()
daemonError := fmt.Sprintf("failed to add dependency: %v", err)
if strings.Contains(daemonError, "FOREIGN KEY constraint failed") || strings.Contains(daemonError, "foreign key constraint failed") {
t.Errorf("Daemon error exposes raw FK constraint: %q", daemonError)
}
if !strings.Contains(errMsg, "not found") {
t.Errorf("Storage error should indicate not found: %q", errMsg)
}
})
t.Run("FKError_RemoveNonexistent", func(t *testing.T) {
// Create issues and dep for removal test
issue1 := &types.Issue{ID: "test-fk-remove-1", Title: "Issue 1", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now()}
issue2 := &types.Issue{ID: "test-fk-remove-2", Title: "Issue 2", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask, CreatedAt: time.Now()}
if err := s.CreateIssue(ctx, issue1, "test"); err != nil {
t.Fatal(err)
}
if err := s.CreateIssue(ctx, issue2, "test"); err != nil {
t.Fatal(err)
}
dep := &types.Dependency{
IssueID: "test-fk-remove-1", DependsOnID: "test-fk-remove-2",
Type: types.DepBlocks, CreatedAt: time.Now(),
}
if err := s.AddDependency(ctx, dep, "test"); err != nil {
t.Fatal(err)
}
// Try removing with non-existent IDs
err := s.RemoveDependency(ctx, "test-nonexistent-1", "test-nonexistent-2", "test")
if err != nil {
errMsg := err.Error()
if strings.Contains(errMsg, "FOREIGN KEY constraint failed") || strings.Contains(errMsg, "foreign key constraint failed") {
t.Errorf("Error exposes raw FK constraint: %q", errMsg)
}
}
// Remove the real dep, then try removing again
if err := s.RemoveDependency(ctx, "test-fk-remove-1", "test-fk-remove-2", "test"); err != nil {
t.Fatalf("Failed to remove existing dependency: %v", err)
}
err = s.RemoveDependency(ctx, "test-fk-remove-1", "test-fk-remove-2", "test")
if err != nil {
errMsg := err.Error()
if strings.Contains(errMsg, "FOREIGN KEY") {
t.Errorf("Error exposes raw FK constraint: %q", errMsg)
}
}
})
}
func TestDepCommandsInit(t *testing.T) {
if depCmd == nil {
t.Fatal("depCmd should be initialized")
}
if depCmd.Use != "dep [issue-id]" {
t.Errorf("Expected Use='dep [issue-id]', got %q", depCmd.Use)
}
if depAddCmd == nil {
t.Fatal("depAddCmd should be initialized")
}
if depRemoveCmd == nil {
t.Fatal("depRemoveCmd should be initialized")
}
}
func TestDepAddFlagAliases(t *testing.T) {
// Test that --blocked-by flag exists on depAddCmd
blockedByFlag := depAddCmd.Flags().Lookup("blocked-by")
if blockedByFlag == nil {
t.Fatal("depAddCmd should have --blocked-by flag")
}
if blockedByFlag.DefValue != "" {
t.Errorf("Expected default blocked-by='', got %q", blockedByFlag.DefValue)
}
// Test that --depends-on flag exists on depAddCmd
dependsOnFlag := depAddCmd.Flags().Lookup("depends-on")
if dependsOnFlag == nil {
t.Fatal("depAddCmd should have --depends-on flag")
}
if dependsOnFlag.DefValue != "" {
t.Errorf("Expected default depends-on='', got %q", dependsOnFlag.DefValue)
}
// Verify the help text mentions the flags
longDesc := depAddCmd.Long
if !strings.Contains(longDesc, "--blocked-by") {
t.Error("Expected Long description to mention --blocked-by flag")
}
if !strings.Contains(longDesc, "--depends-on") {
t.Error("Expected Long description to mention --depends-on flag")
}
if fileFlag := depAddCmd.Flags().Lookup("file"); fileFlag == nil {
t.Fatal("depAddCmd should have --file flag")
} else if fileFlag.DefValue != "" {
t.Errorf("Expected default file='', got %q", fileFlag.DefValue)
}
if !strings.Contains(longDesc, "--file") {
t.Error("Expected Long description to mention --file flag")
}
}
func TestDepBlocksFlag(t *testing.T) {
// Test that the --blocks flag exists on depCmd
flag := depCmd.Flags().Lookup("blocks")
if flag == nil {
t.Fatal("depCmd should have --blocks flag")
}
// Test shorthand is -b
if flag.Shorthand != "b" {
t.Errorf("Expected shorthand='b', got %q", flag.Shorthand)
}
// Test default value is empty string
if flag.DefValue != "" {
t.Errorf("Expected default blocks='', got %q", flag.DefValue)
}
// Test usage text
if !strings.Contains(flag.Usage, "blocks") {
t.Errorf("Expected flag usage to mention 'blocks', got %q", flag.Usage)
}
}
func TestDepTreeFormatFlag(t *testing.T) {
// Test that the --format flag exists on depTreeCmd
flag := depTreeCmd.Flags().Lookup("format")
if flag == nil {
t.Fatal("depTreeCmd should have --format flag")
}
// Test default value is empty string
if flag.DefValue != "" {
t.Errorf("Expected default format='', got %q", flag.DefValue)
}
// Test usage text mentions mermaid
if !strings.Contains(flag.Usage, "mermaid") {
t.Errorf("Expected flag usage to mention 'mermaid', got %q", flag.Usage)
}
}
// TestDepTreeFormatMermaidCaseInsensitive pins that --format mermaid folds case
// the same way the json format check does.
func TestDepTreeFormatMermaidCaseInsensitive(t *testing.T) {
tests := []struct {
format string
want bool
}{
{"mermaid", true},
{"Mermaid", true},
{"MERMAID", true},
{"", false},
{"json", false},
{"dot", false},
}
for _, tt := range tests {
t.Run(tt.format, func(t *testing.T) {
if got := isMermaidTreeFormat(tt.format); got != tt.want {
t.Errorf("isMermaidTreeFormat(%q) = %v, want %v", tt.format, got, tt.want)
}
})
}
}
func TestGetStatusEmoji(t *testing.T) {
tests := []struct {
status types.Status
want string
}{
{types.StatusOpen, "☐"},
{types.StatusInProgress, "◧"},
{types.StatusBlocked, "⚠"},
{types.StatusClosed, "☑"},
{types.Status("unknown"), "?"},
}
for _, tt := range tests {
t.Run(string(tt.status), func(t *testing.T) {
got := getStatusEmoji(tt.status)
if got != tt.want {
t.Errorf("getStatusEmoji(%q) = %q, want %q", tt.status, got, tt.want)
}
})
}
}
func TestOutputMermaidTree(t *testing.T) {
tests := []struct {
name string
tree []*types.TreeNode
rootID string
want []string // Lines that must appear in output
}{
{
name: "empty tree",
tree: []*types.TreeNode{},
rootID: "test-1",
want: []string{
"flowchart TD",
`test-1["No dependencies"]`,
},
},
{
name: "single dependency",
tree: []*types.TreeNode{
{
Issue: types.Issue{ID: "test-1", Title: "Task 1", Status: types.StatusInProgress},
Depth: 0,
ParentID: "",
},
{
Issue: types.Issue{ID: "test-2", Title: "Task 2", Status: types.StatusClosed},
Depth: 1,
ParentID: "test-1",
},
},
rootID: "test-1",
want: []string{
"flowchart TD",
`test-1["◧ test-1: Task 1"]`,
`test-2["☑ test-2: Task 2"]`,
"test-1 --> test-2",
},
},
{
name: "multiple dependencies",
tree: []*types.TreeNode{
{
Issue: types.Issue{ID: "test-1", Title: "Main", Status: types.StatusOpen},
Depth: 0,
ParentID: "",
},
{
Issue: types.Issue{ID: "test-2", Title: "Sub 1", Status: types.StatusClosed},
Depth: 1,
ParentID: "test-1",
},
{
Issue: types.Issue{ID: "test-3", Title: "Sub 2", Status: types.StatusBlocked},
Depth: 1,
ParentID: "test-1",
},
},
rootID: "test-1",
want: []string{
"flowchart TD",
`test-1["☐ test-1: Main"]`,
`test-2["☑ test-2: Sub 1"]`,
`test-3["⚠ test-3: Sub 2"]`,
"test-1 --> test-2",
"test-1 --> test-3",
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Capture stdout
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
defer func() { os.Stdout = old }()
outputMermaidTree(tt.tree, tt.rootID)
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
output := buf.String()
// Verify all expected lines appear
for _, line := range tt.want {
if !strings.Contains(output, line) {
t.Errorf("expected output to contain %q, got:\n%s", line, output)
}
}
})
}
}
func TestOutputMermaidTree_Siblings(t *testing.T) {
// Test case: Siblings with children (reproduces issue with wrong parent inference)
// Structure:
// BD-1 (root)
// ├── BD-2 (sibling 1)
// │ └── BD-4 (child of BD-2)
// └── BD-3 (sibling 2)
// └── BD-5 (child of BD-3)
tree := []*types.TreeNode{
{
Issue: types.Issue{ID: "BD-1", Title: "Parent", Status: types.StatusOpen},
Depth: 0,
ParentID: "",
},
{
Issue: types.Issue{ID: "BD-2", Title: "Sibling 1", Status: types.StatusOpen},
Depth: 1,
ParentID: "BD-1",
},
{
Issue: types.Issue{ID: "BD-3", Title: "Sibling 2", Status: types.StatusOpen},
Depth: 1,
ParentID: "BD-1",
},
{
Issue: types.Issue{ID: "BD-4", Title: "Child of Sibling 1", Status: types.StatusOpen},
Depth: 2,
ParentID: "BD-2",
},
{
Issue: types.Issue{ID: "BD-5", Title: "Child of Sibling 2", Status: types.StatusOpen},
Depth: 2,
ParentID: "BD-3",
},
}
// Capture stdout
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
defer func() { os.Stdout = old }()
outputMermaidTree(tree, "BD-1")
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
output := buf.String()
// Verify correct edges exist
correctEdges := []string{
"BD-1 --> BD-2",
"BD-1 --> BD-3",
"BD-2 --> BD-4",
"BD-3 --> BD-5",
}
for _, edge := range correctEdges {
if !strings.Contains(output, edge) {
t.Errorf("expected edge %q to be present, got:\n%s", edge, output)
}
}
// Verify incorrect edges do NOT exist (siblings shouldn't be connected)
incorrectEdges := []string{
"BD-2 --> BD-3", // Siblings shouldn't be connected
"BD-3 --> BD-4", // BD-4's parent is BD-2, not BD-3
"BD-4 --> BD-3", // Wrong direction
"BD-4 --> BD-5", // These are cousins, not parent-child
}
for _, edge := range incorrectEdges {
if strings.Contains(output, edge) {
t.Errorf("incorrect edge %q should NOT be present, got:\n%s", edge, output)
}
}
}
func TestDepTreeDirectionFlag(t *testing.T) {
// Test that the --direction flag exists on depTreeCmd
flag := depTreeCmd.Flags().Lookup("direction")
if flag == nil {
t.Fatal("depTreeCmd should have --direction flag")
}
// Test default value is empty string (will default to "down")
if flag.DefValue != "" {
t.Errorf("Expected default direction='', got %q", flag.DefValue)
}
// Test usage text mentions valid options
usage := flag.Usage
if !strings.Contains(usage, "down") || !strings.Contains(usage, "up") || !strings.Contains(usage, "both") {
t.Errorf("Expected flag usage to mention 'down', 'up', 'both', got %q", usage)
}
}
func TestDepTreeStatusFlag(t *testing.T) {
// Test that the --status flag exists on depTreeCmd
flag := depTreeCmd.Flags().Lookup("status")
if flag == nil {
t.Fatal("depTreeCmd should have --status flag")
}
// Test default value is empty string
if flag.DefValue != "" {
t.Errorf("Expected default status='', got %q", flag.DefValue)
}
}
func TestFormatTreeNode(t *testing.T) {
tests := []struct {
name string
node *types.TreeNode
contains []string
}{
{
name: "open issue at depth 0 shows READY",
node: &types.TreeNode{
Issue: types.Issue{
ID: "BD-1",
Title: "Test Issue",
Status: types.StatusOpen,
Priority: 2,
},
Depth: 0,
},
contains: []string{"BD-1", "Test Issue", "P2", "open", "[READY]"},
},
{
name: "open issue at depth 1 does not show READY",
node: &types.TreeNode{
Issue: types.Issue{
ID: "BD-2",
Title: "Child Issue",
Status: types.StatusOpen,
Priority: 1,
},
Depth: 1,
},
contains: []string{"BD-2", "Child Issue", "P1", "open"},
},
{
name: "closed issue",
node: &types.TreeNode{
Issue: types.Issue{
ID: "BD-3",
Title: "Done Issue",
Status: types.StatusClosed,
Priority: 3,
},
Depth: 0,
},
contains: []string{"BD-3", "Done Issue", "P3", "closed"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := formatTreeNode(tt.node, false)
for _, want := range tt.contains {
if !strings.Contains(result, want) {
t.Errorf("formatTreeNode() = %q, want to contain %q", result, want)
}
}
// For non-root open issues, verify READY is NOT shown
if tt.node.Status == types.StatusOpen && tt.node.Depth > 0 {
if strings.Contains(result, "[READY]") {
t.Errorf("formatTreeNode() = %q, should NOT contain [READY] for depth > 0", result)
}
}
})
}
// Test that blocked root shows [BLOCKED] instead of [READY]
t.Run("blocked root shows BLOCKED not READY", func(t *testing.T) {
node := &types.TreeNode{
Issue: types.Issue{
ID: "BD-10",
Title: "Blocked Root",
Status: types.StatusOpen,
Priority: 1,
},
Depth: 0,
}
result := formatTreeNode(node, true)
if strings.Contains(result, "[READY]") {
t.Errorf("blocked root should not show [READY], got: %q", result)
}
if !strings.Contains(result, "[BLOCKED]") {
t.Errorf("blocked root should show [BLOCKED], got: %q", result)
}
})
}
func TestFormatTreeNodeShowsDependencyType(t *testing.T) {
tests := []struct {
name string
node *types.TreeNode
want string
}{
{
name: "blocks edge",
node: &types.TreeNode{
Issue: types.Issue{ID: "BD-2", Title: "Blocked task", Status: types.StatusOpen, Priority: 1},
Depth: 1,
ParentID: "BD-1",
EdgeFromParent: types.DepBlocks,
},
want: "[blocks]",
},
{
name: "parent-child edge",
node: &types.TreeNode{
Issue: types.Issue{ID: "BD-3", Title: "Child task", Status: types.StatusOpen, Priority: 2},
Depth: 1,
ParentID: "BD-1",
EdgeFromParent: types.DepParentChild,
},
want: "[parent-child]",
},
{
name: "root has no edge label",
node: &types.TreeNode{
Issue: types.Issue{ID: "BD-1", Title: "Root", Status: types.StatusOpen, Priority: 0},
Depth: 0,
EdgeFromParent: types.DepBlocks,
},
want: "[blocks]",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := formatTreeNode(tt.node, false)
if tt.node.Depth == 0 {
if strings.Contains(got, tt.want) {
t.Fatalf("root node should not show dependency label %q: %s", tt.want, got)
}
return
}
if !strings.Contains(got, tt.want) {
t.Fatalf("formatTreeNode() = %q, want dependency label %q", got, tt.want)
}
})
}
}
func TestRenderTreeOutput(t *testing.T) {
// Test tree with proper connectors
tree := []*types.TreeNode{
{
Issue: types.Issue{ID: "BD-1", Title: "Root", Status: types.StatusOpen, Priority: 1},
Depth: 0,
ParentID: "",
},
{
Issue: types.Issue{ID: "BD-2", Title: "Child 1", Status: types.StatusOpen, Priority: 2},
Depth: 1,
ParentID: "BD-1",
},
{
Issue: types.Issue{ID: "BD-3", Title: "Child 2", Status: types.StatusClosed, Priority: 2},
Depth: 1,
ParentID: "BD-1",
},
{
Issue: types.Issue{ID: "BD-4", Title: "Grandchild", Status: types.StatusOpen, Priority: 3},
Depth: 2,
ParentID: "BD-2",
},
}
// Capture stdout
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
defer func() { os.Stdout = old }()
renderTree(tree, 50, "down")
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
output := buf.String()
// Check for tree connectors
if !strings.Contains(output, "├──") && !strings.Contains(output, "└──") {
t.Errorf("Expected tree connectors (├── or └──) in output, got:\n%s", output)
}
// Check that all nodes are present
for _, node := range tree {
if !strings.Contains(output, node.ID) {
t.Errorf("Expected node %s in output, got:\n%s", node.ID, output)
}
}
}
func TestRenderTreeExternalBlockerMarksRootBlocked(t *testing.T) {
tree := []*types.TreeNode{
{
Issue: types.Issue{ID: "BD-root", Title: "Root", Status: types.StatusOpen, Priority: 1},
},
{
Issue: types.Issue{ID: "external:remote:payments", Title: "○ payments", Status: types.StatusOpen},
Depth: 1,
ParentID: "BD-root",
EdgeFromParent: types.DepBlocks,
},
}
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
renderTree(tree, 50, "down")
w.Close()
os.Stdout = old
var buf bytes.Buffer
_, _ = io.Copy(&buf, r)
output := buf.String()
if !strings.Contains(output, "[BLOCKED]") || strings.Contains(output, "[READY]") {
t.Fatalf("external blocker should mark root blocked, got:\n%s", output)
}
}
func TestRenderTreeOutputShowsDependencyTypeLabelsInMixedGraph(t *testing.T) {
downTree := []*types.TreeNode{
{
Issue: types.Issue{ID: "BD-root", Title: "Root", Status: types.StatusOpen, Priority: 1},
Depth: 0,
ParentID: "",
},
{
Issue: types.Issue{ID: "BD-child", Title: "Child", Status: types.StatusOpen, Priority: 2},
Depth: 1,
ParentID: "BD-root",
EdgeFromParent: types.DepParentChild,
},
}
upTree := []*types.TreeNode{
{
Issue: types.Issue{ID: "BD-root", Title: "Root", Status: types.StatusOpen, Priority: 1},
Depth: 0,
ParentID: "",
},
{
Issue: types.Issue{ID: "BD-dependent", Title: "Dependent", Status: types.StatusOpen, Priority: 3},
Depth: 1,
ParentID: "BD-root",
EdgeFromParent: types.DepBlocks,
},
}
tree := storageissueops.MergeBidirectionalTree(downTree, upTree, "BD-root")
old := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
defer func() { os.Stdout = old }()
renderTree(tree, 3, "both")
w.Close()
var buf bytes.Buffer
io.Copy(&buf, r)
output := buf.String()
for _, want := range []string{"BD-dependent", "[blocks]", "BD-child", "[parent-child]"} {
if !strings.Contains(output, want) {
t.Fatalf("expected mixed graph output to contain %q, got:\n%s", want, output)
}
}
}
func TestTreeNodeJSONIncludesEdgeFromParent(t *testing.T) {
node := types.TreeNode{
Issue: types.Issue{ID: "BD-child", Title: "Child", Status: types.StatusOpen, Priority: 2},
Depth: 1,
ParentID: "BD-root",
EdgeFromParent: types.DepParentChild,
}
got, err := json.Marshal(node)
if err != nil {
t.Fatalf("json.Marshal(TreeNode): %v", err)
}
if !strings.Contains(string(got), `"edge_from_parent":"parent-child"`) {
t.Fatalf("TreeNode JSON missing edge_from_parent: %s", got)
}
}
// Tests for child→parent dependency detection (bd-nim5)
// ============================================================================
// Foreign Key Error Tests (GH#952 Issue 4)
// ============================================================================
//
// These tests verify that foreign key constraint violations produce
// user-friendly error messages instead of raw database errors.
//
// Expected behavior:
// - Error should say "issue X or Y not found" (user-friendly)
// - Error should NOT say "FOREIGN KEY constraint failed" (raw database error)
//
// TRACER BULLET FINDING (Phase 1):
// The storage layer (dependencies.go) already validates issue existence
// BEFORE inserting into the database, so FK constraint errors don't occur
// at the storage layer. Tests PASS because AddDependency returns proper
// "not found" errors.
//
// If bugs exist, they would be in:
// 1. CLI layer (dep.go) - when ResolvePartialID has edge cases
// 2. Daemon RPC layer - if ID resolution behaves differently
// 3. Race conditions - issue deleted between resolve and add
//
// These tests serve as regression tests ensuring the storage layer
// continues to provide user-friendly error messages.
// TestDepRoutedTargetOpensReadOnly is the regression guard for the dep/link
// target-resolution invariant: a cross-rig dependency target is resolved by ID
// only, so resolveIDWithRouting must open the routed foreign store read-only,
// while resolveIDForMutation (used for the mutated source issue) opens it
// writable. Opening a dep/link target writable re-exposes GH#3231 open-time
// mutations against a foreign project.
//
// NOTE: This test uses os.Chdir and cannot run in parallel with other tests.
func TestDepRoutedTargetOpensReadOnly(t *testing.T) {
ctx := context.Background()
tmpDir := t.TempDir()
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
t.Fatalf("create town beads dir: %v", err)
}
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
t.Fatalf("create rig beads dir: %v", err)
}
townDBPath := filepath.Join(townBeadsDir, "dolt")
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
rigDBPath := filepath.Join(rigBeadsDir, "dolt")
rigStore := newTestStoreIsolatedDB(t, rigDBPath, "gt")
if err := rigStore.CreateIssue(ctx, &types.Issue{
ID: "gt-target1",
Title: "Routed dep target",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}, "test"); err != nil {
t.Fatalf("create rig issue: %v", err)
}
// Release the rig store before routing reopens it.
rigStore.Close()
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(`{"prefix":"gt-","path":"rig"}`), 0644); err != nil {
t.Fatalf("write routes.jsonl: %v", err)
}
oldDbPath := dbPath
dbPath = townDBPath
t.Cleanup(func() { dbPath = oldDbPath })
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("getwd: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("chdir: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWd) })
// Target-only resolution (the dep/link target) must open the routed store
// read-only.
roID, roStore, roCleanup, err := resolveIDWithRouting(ctx, townStore, "gt-target1")
if err != nil {
t.Fatalf("resolveIDWithRouting (target) failed: %v", err)
}
if roID != "gt-target1" {
t.Errorf("resolved target ID = %q, want gt-target1", roID)
}
roDolt, ok := roStore.(*dolt.DoltStore)
if !ok {
roCleanup()
t.Fatalf("routed target store is %T, want *dolt.DoltStore", roStore)
}
if !roDolt.IsReadOnly() {
roCleanup()
t.Fatal("dep/link target must be resolved read-only, but routed store is writable (GH#3231)")
}
roCleanup()
// Source resolution (the mutated issue's store) must open the routed store
// writable so the dependency write commits on the target head (#4141).
rwID, rwStore, rwCleanup, err := resolveIDForMutation(ctx, townStore, "gt-target1")
if err != nil {
t.Fatalf("resolveIDForMutation (source) failed: %v", err)
}
defer rwCleanup()
if rwID != "gt-target1" {
t.Errorf("resolved source ID = %q, want gt-target1", rwID)
}
rwDolt, ok := rwStore.(*dolt.DoltStore)
if !ok {
t.Fatalf("routed source store is %T, want *dolt.DoltStore", rwStore)
}
if rwDolt.IsReadOnly() {
t.Fatal("source resolution must open the routed store writable, but it is read-only")
}
}
// TestDepListCrossRigRouting tests that bd dep list resolves issues via routing
// when run from the town root for rig-level issues. This is the regression test
// for bd-ciouf: "bd dep list cross-rig routing broken from town root".
//
// NOTE: This test uses os.Chdir and cannot run in parallel with other tests.
func TestDepListCrossRigRouting(t *testing.T) {
ctx := context.Background()
// Create temp directory structure:
// tmpDir/
// .beads/
// dolt/ (town database, prefix "hq")
// routes.jsonl (routing config)
// rig/
// .beads/
// dolt/ (rig database, prefix "gt")
tmpDir := t.TempDir()
// Create town .beads directory
townBeadsDir := filepath.Join(tmpDir, ".beads")
if err := os.MkdirAll(townBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create town beads dir: %v", err)
}
// Create rig .beads directory
rigBeadsDir := filepath.Join(tmpDir, "rig", ".beads")
if err := os.MkdirAll(rigBeadsDir, 0755); err != nil {
t.Fatalf("Failed to create rig beads dir: %v", err)
}
// Initialize town database
townDBPath := filepath.Join(townBeadsDir, "dolt")
townStore := newTestStoreIsolatedDB(t, townDBPath, "hq")
// Initialize rig database
rigDBPath := filepath.Join(rigBeadsDir, "dolt")
rigStore := newTestStoreIsolatedDB(t, rigDBPath, "gt")
// Create test issues in rig database with a dependency
parent := &types.Issue{
ID: "gt-parent1",
Title: "Parent Issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
child := &types.Issue{
ID: "gt-child1",
Title: "Child Issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := rigStore.CreateIssue(ctx, parent, "test"); err != nil {
t.Fatalf("Failed to create parent issue: %v", err)
}
if err := rigStore.CreateIssue(ctx, child, "test"); err != nil {
t.Fatalf("Failed to create child issue: %v", err)
}
// gt-child1 depends on gt-parent1 (blocks relationship)
dep := &types.Dependency{
IssueID: "gt-child1",
DependsOnID: "gt-parent1",
Type: types.DepBlocks,
}
if err := rigStore.AddDependency(ctx, dep, "test"); err != nil {
t.Fatalf("Failed to add dependency: %v", err)
}
// Close rig store to release Dolt lock before routing opens it
rigStore.Close()
// Create routes.jsonl in town .beads directory
routesContent := `{"prefix":"gt-","path":"rig"}`
routesPath := filepath.Join(townBeadsDir, "routes.jsonl")
if err := os.WriteFile(routesPath, []byte(routesContent), 0644); err != nil {
t.Fatalf("Failed to write routes.jsonl: %v", err)
}
// Set up global state for routing to work
oldDbPath := dbPath
dbPath = townDBPath
t.Cleanup(func() { dbPath = oldDbPath })
// Change to tmpDir so routing can find town root via CWD
oldWd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get working directory: %v", err)
}
if err := os.Chdir(tmpDir); err != nil {
t.Fatalf("Failed to change to temp directory: %v", err)
}
t.Cleanup(func() { _ = os.Chdir(oldWd) })
// Test 1: Verify routing resolution works for the rig issue
result, err := resolveAndGetIssueWithRouting(ctx, townStore, "gt-child1")
if err != nil {
t.Fatalf("resolveAndGetIssueWithRouting failed: %v", err)
}
if result == nil || result.Issue == nil {
t.Fatal("resolveAndGetIssueWithRouting returned nil")
}
defer result.Close()
if !result.Routed {
t.Error("Expected result.Routed to be true for cross-rig lookup")
}
if result.ResolvedID != "gt-child1" {
t.Errorf("Expected resolved ID %q, got %q", "gt-child1", result.ResolvedID)
}
// Test 2: Verify dependencies can be queried from the routed store
deps, err := result.Store.GetDependenciesWithMetadata(ctx, result.ResolvedID)
if err != nil {
t.Fatalf("GetDependenciesWithMetadata on routed store failed: %v", err)
}
if len(deps) != 1 {
t.Fatalf("Expected 1 dependency, got %d", len(deps))
}
if deps[0].ID != "gt-parent1" {
t.Errorf("Expected dependency on gt-parent1, got %s", deps[0].ID)
}
// Test 3: Verify dependents (up direction) also work from routed store
dependents, err := result.Store.GetDependentsWithMetadata(ctx, "gt-parent1")
if err != nil {
t.Fatalf("GetDependentsWithMetadata on routed store failed: %v", err)
}
if len(dependents) != 1 {
t.Fatalf("Expected 1 dependent, got %d", len(dependents))
}
if dependents[0].ID != "gt-child1" {
t.Errorf("Expected dependent gt-child1, got %s", dependents[0].ID)
}
t.Log("Successfully resolved cross-rig dependencies via routing")
}