diff --git a/cmd/bd/close.go b/cmd/bd/close.go index 3b736c0b2..a5211d282 100644 --- a/cmd/bd/close.go +++ b/cmd/bd/close.go @@ -327,7 +327,7 @@ func checkGateSatisfaction(issue *types.Issue) error { switch { case strings.HasPrefix(issue.AwaitType, "gh:run"): - resolved, escalated, reason, err = checkGHRun(issue) + resolved, escalated, reason, err = checkGHRun(issue, true) case strings.HasPrefix(issue.AwaitType, "gh:pr"): resolved, escalated, reason, err = checkGHPR(issue) case issue.AwaitType == "timer": diff --git a/cmd/bd/database_name.go b/cmd/bd/database_name.go new file mode 100644 index 000000000..791e0bc6e --- /dev/null +++ b/cmd/bd/database_name.go @@ -0,0 +1,12 @@ +package main + +import "strings" + +// sanitizeDBName replaces characters that are awkward for embedded Dolt +// database names with underscores so both cgo and no-cgo builds share the +// same normalization logic. +func sanitizeDBName(name string) string { + name = strings.ReplaceAll(name, "-", "_") + name = strings.ReplaceAll(name, ".", "_") + return name +} diff --git a/cmd/bd/database_name_test.go b/cmd/bd/database_name_test.go new file mode 100644 index 000000000..81807c8ea --- /dev/null +++ b/cmd/bd/database_name_test.go @@ -0,0 +1,27 @@ +package main + +import "testing" + +// TestSanitizeDBName lives in an untagged file so both cgo and no-cgo builds +// compile and verify the shared helper. +func TestSanitizeDBName(t *testing.T) { + tests := []struct { + input string + want string + }{ + {"my-project", "my_project"}, + {"jtbot-core", "jtbot_core"}, + {"no-hyphens-here", "no_hyphens_here"}, + {"dots.and-hyphens", "dots_and_hyphens"}, + {"already_clean", "already_clean"}, + {"beads", "beads"}, + } + for _, tt := range tests { + t.Run(tt.input, func(t *testing.T) { + got := sanitizeDBName(tt.input) + if got != tt.want { + t.Errorf("sanitizeDBName(%q) = %q, want %q", tt.input, got, tt.want) + } + }) + } +} diff --git a/cmd/bd/gate.go b/cmd/bd/gate.go index 57c5a4bff..f182f350a 100644 --- a/cmd/bd/gate.go +++ b/cmd/bd/gate.go @@ -532,7 +532,7 @@ Examples: switch { case strings.HasPrefix(gate.AwaitType, "gh:run"): - result.resolved, result.escalated, result.reason, result.err = checkGHRun(gate) + result.resolved, result.escalated, result.reason, result.err = checkGHRun(gate, !dryRun) case strings.HasPrefix(gate.AwaitType, "gh:pr"): result.resolved, result.escalated, result.reason, result.err = checkGHPR(gate) case gate.AwaitType == "timer": @@ -640,6 +640,12 @@ type ghPRStatus struct { Title string `json:"title"` } +var ( + discoverRunIDByWorkflowNameFunc = discoverRunIDByWorkflowName + updateGateAwaitIDFunc = updateGateAwaitID + checkGHRunStatusFunc = checkGHRunStatus +) + // isNumericID returns true if the string contains only digits (a GitHub run ID) func isNumericID(s string) bool { if s == "" { @@ -702,8 +708,9 @@ func discoverRunIDByWorkflowName(workflowHint string) (string, error) { return fmt.Sprintf("%d", runs[0].DatabaseID), nil } -// checkGHRun checks a GitHub Actions workflow run gate -func checkGHRun(gate *types.Issue) (resolved, escalated bool, reason string, err error) { +// checkGHRun checks a GitHub Actions workflow run gate. +// When persistDiscoveredRunID is false, workflow-name discovery stays in-memory only. +func checkGHRun(gate *types.Issue, persistDiscoveredRunID bool) (resolved, escalated bool, reason string, err error) { if gate.AwaitID == "" { return false, false, "no run ID specified - set await_id or use workflow name hint", nil } @@ -712,19 +719,25 @@ func checkGHRun(gate *types.Issue) (resolved, escalated bool, reason string, err // If await_id is a workflow name hint (non-numeric), auto-discover the run ID if !isNumericID(gate.AwaitID) { - discoveredID, discoverErr := discoverRunIDByWorkflowName(gate.AwaitID) + discoveredID, discoverErr := discoverRunIDByWorkflowNameFunc(gate.AwaitID) if discoverErr != nil { return false, false, fmt.Sprintf("workflow hint '%s': %v", gate.AwaitID, discoverErr), nil } - // Update the gate with the discovered run ID - if updateErr := updateGateAwaitID(nil, gate.ID, discoveredID); updateErr != nil { - return false, false, "", fmt.Errorf("failed to update gate with discovered run ID: %w", updateErr) + if persistDiscoveredRunID { + // Non-dry-run flows persist the numeric run ID for future checks. + if updateErr := updateGateAwaitIDFunc(nil, gate.ID, discoveredID); updateErr != nil { + return false, false, "", fmt.Errorf("failed to update gate with discovered run ID: %w", updateErr) + } } runID = discoveredID } + return checkGHRunStatusFunc(runID) +} + +func checkGHRunStatus(runID string) (resolved, escalated bool, reason string, err error) { // Run: gh run view --json status,conclusion,name cmd := exec.Command("gh", "run", "view", runID, "--json", "status,conclusion,name") // #nosec G204 -- runID is a validated GitHub run ID var stdout, stderr bytes.Buffer diff --git a/cmd/bd/gate_test.go b/cmd/bd/gate_test.go index 49b4766c2..0afda8ad1 100644 --- a/cmd/bd/gate_test.go +++ b/cmd/bd/gate_test.go @@ -1,12 +1,103 @@ package main import ( + "bytes" "context" + "errors" + "io" + "os" + "path/filepath" + "runtime" + "sync" "testing" + "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/types" ) +var gateTestStdoutMu sync.Mutex + +type gateCloseCall struct { + id string + reason string + actor string + session string +} + +type fakeGateCheckStore struct { + storage.DoltStorage + issues []*types.Issue + searchFilter types.IssueFilter + closeCalls []gateCloseCall +} + +func (f *fakeGateCheckStore) SearchIssues(_ context.Context, _ string, filter types.IssueFilter) ([]*types.Issue, error) { + f.searchFilter = filter + return f.issues, nil +} + +func (f *fakeGateCheckStore) CloseIssue(_ context.Context, id, reason, actor, session string) error { + f.closeCalls = append(f.closeCalls, gateCloseCall{ + id: id, + reason: reason, + actor: actor, + session: session, + }) + return nil +} + +func captureGateStdout(t *testing.T, fn func()) string { + t.Helper() + + gateTestStdoutMu.Lock() + defer gateTestStdoutMu.Unlock() + + old := os.Stdout + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("os.Pipe: %v", err) + } + os.Stdout = w + + var buf bytes.Buffer + done := make(chan struct{}) + go func() { + _, _ = io.Copy(&buf, r) + close(done) + }() + + fn() + + _ = w.Close() + os.Stdout = old + <-done + _ = r.Close() + + return buf.String() +} + +func resetGateCheckFlags(t *testing.T) { + t.Helper() + + if err := gateCheckCmd.Flags().Set("type", ""); err != nil { + t.Fatalf("reset type flag: %v", err) + } + if err := gateCheckCmd.Flags().Set("dry-run", "false"); err != nil { + t.Fatalf("reset dry-run flag: %v", err) + } + if err := gateCheckCmd.Flags().Set("escalate", "false"); err != nil { + t.Fatalf("reset escalate flag: %v", err) + } + if err := gateCheckCmd.Flags().Set("limit", "100"); err != nil { + t.Fatalf("reset limit flag: %v", err) + } + + gateCheckCmd.Flags().Lookup("type").Changed = false + gateCheckCmd.Flags().Lookup("dry-run").Changed = false + gateCheckCmd.Flags().Lookup("escalate").Changed = false + gateCheckCmd.Flags().Lookup("limit").Changed = false +} + func TestShouldCheckGate(t *testing.T) { tests := []struct { name string @@ -201,6 +292,323 @@ func TestGetWorkflowNameHint(t *testing.T) { } } +func TestCheckGHRun_DryRunDoesNotPersistDiscoveredRunID(t *testing.T) { + origDiscover := discoverRunIDByWorkflowNameFunc + origUpdate := updateGateAwaitIDFunc + origStatus := checkGHRunStatusFunc + t.Cleanup(func() { + discoverRunIDByWorkflowNameFunc = origDiscover + updateGateAwaitIDFunc = origUpdate + checkGHRunStatusFunc = origStatus + }) + + updateCalls := 0 + discoverRunIDByWorkflowNameFunc = func(workflowHint string) (string, error) { + if workflowHint != "release.yml" { + t.Fatalf("unexpected workflow hint %q", workflowHint) + } + return "12345", nil + } + updateGateAwaitIDFunc = func(_ interface{}, gateID, runID string) error { + updateCalls++ + t.Fatalf("unexpected await_id persistence for %s -> %s", gateID, runID) + return nil + } + checkGHRunStatusFunc = func(runID string) (bool, bool, string, error) { + if runID != "12345" { + t.Fatalf("expected discovered run ID 12345, got %q", runID) + } + return true, false, "workflow 'release' succeeded", nil + } + + resolved, escalated, reason, err := checkGHRun(&types.Issue{ + ID: "bd-gate", + AwaitID: "release.yml", + }, false) + if err != nil { + t.Fatalf("checkGHRun returned error: %v", err) + } + if !resolved { + t.Fatal("expected dry-run check to resolve using discovered run status") + } + if escalated { + t.Fatal("did not expect escalation for successful workflow") + } + if reason == "" { + t.Fatal("expected resolution reason") + } + if updateCalls != 0 { + t.Fatalf("expected no await_id updates during dry-run, got %d", updateCalls) + } +} + +func TestCheckGHRun_PersistsDiscoveredRunIDOutsideDryRun(t *testing.T) { + origDiscover := discoverRunIDByWorkflowNameFunc + origUpdate := updateGateAwaitIDFunc + origStatus := checkGHRunStatusFunc + t.Cleanup(func() { + discoverRunIDByWorkflowNameFunc = origDiscover + updateGateAwaitIDFunc = origUpdate + checkGHRunStatusFunc = origStatus + }) + + updateCalls := 0 + discoverRunIDByWorkflowNameFunc = func(workflowHint string) (string, error) { + if workflowHint != "release.yml" { + t.Fatalf("unexpected workflow hint %q", workflowHint) + } + return "67890", nil + } + updateGateAwaitIDFunc = func(_ interface{}, gateID, runID string) error { + updateCalls++ + if gateID != "bd-gate" { + t.Fatalf("expected gate ID bd-gate, got %q", gateID) + } + if runID != "67890" { + t.Fatalf("expected discovered run ID 67890, got %q", runID) + } + return nil + } + checkGHRunStatusFunc = func(runID string) (bool, bool, string, error) { + if runID != "67890" { + t.Fatalf("expected discovered run ID 67890, got %q", runID) + } + return false, false, "workflow 'release' is queued", nil + } + + resolved, escalated, reason, err := checkGHRun(&types.Issue{ + ID: "bd-gate", + AwaitID: "release.yml", + }, true) + if err != nil { + t.Fatalf("checkGHRun returned error: %v", err) + } + if resolved { + t.Fatal("did not expect queued workflow to resolve") + } + if escalated { + t.Fatal("did not expect queued workflow to escalate") + } + if reason == "" { + t.Fatal("expected pending reason") + } + if updateCalls != 1 { + t.Fatalf("expected one await_id update outside dry-run, got %d", updateCalls) + } +} + +func TestCheckGHRun_ReturnsErrorWhenPersistingDiscoveredRunIDFails(t *testing.T) { + origDiscover := discoverRunIDByWorkflowNameFunc + origUpdate := updateGateAwaitIDFunc + origStatus := checkGHRunStatusFunc + t.Cleanup(func() { + discoverRunIDByWorkflowNameFunc = origDiscover + updateGateAwaitIDFunc = origUpdate + checkGHRunStatusFunc = origStatus + }) + + discoverRunIDByWorkflowNameFunc = func(workflowHint string) (string, error) { + if workflowHint != "release.yml" { + t.Fatalf("unexpected workflow hint %q", workflowHint) + } + return "12345", nil + } + updateGateAwaitIDFunc = func(_ interface{}, gateID, runID string) error { + if gateID != "bd-gate" { + t.Fatalf("expected gate ID bd-gate, got %q", gateID) + } + if runID != "12345" { + t.Fatalf("expected discovered run ID 12345, got %q", runID) + } + return errors.New("write failed") + } + checkGHRunStatusFunc = func(runID string) (bool, bool, string, error) { + t.Fatalf("did not expect status check after await_id persistence failure, got %q", runID) + return false, false, "", nil + } + + resolved, escalated, reason, err := checkGHRun(&types.Issue{ + ID: "bd-gate", + AwaitID: "release.yml", + }, true) + if err == nil { + t.Fatal("expected checkGHRun to return an error when await_id persistence fails") + } + if resolved { + t.Fatal("did not expect resolution when await_id persistence fails") + } + if escalated { + t.Fatal("did not expect escalation when await_id persistence fails") + } + if reason != "" { + t.Fatalf("expected empty reason on persistence failure, got %q", reason) + } + if !gateTestContains(err.Error(), "failed to update gate with discovered run ID") { + t.Fatalf("expected wrapped persistence error, got %v", err) + } +} + +func TestCheckGHRunStatus_Success(t *testing.T) { + installFakeGHScript(t, `{"status":"completed","conclusion":"success","name":"release"}`) + + resolved, escalated, reason, err := checkGHRunStatus("12345") + if err != nil { + t.Fatalf("checkGHRunStatus returned error: %v", err) + } + if !resolved { + t.Fatal("expected successful workflow run to resolve the gate") + } + if escalated { + t.Fatal("did not expect successful workflow run to escalate the gate") + } + if reason != "workflow 'release' succeeded" { + t.Fatalf("checkGHRunStatus reason = %q, want %q", reason, "workflow 'release' succeeded") + } +} + +func TestGateCheck_GHRunWorkflowDiscoveryPersistence(t *testing.T) { + tests := []struct { + name string + dryRun bool + wantUpdateCalls int + wantCloseCalls int + wantOutput string + }{ + { + name: "dry run keeps discovered run ID in memory only", + dryRun: true, + wantUpdateCalls: 0, + wantCloseCalls: 0, + wantOutput: "would resolve - workflow 'release' succeeded", + }, + { + name: "live run persists discovered run ID before closing", + dryRun: false, + wantUpdateCalls: 1, + wantCloseCalls: 1, + wantOutput: "resolved - workflow 'release' succeeded", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + origStore := store + origRootCtx := rootCtx + origJSONOutput := jsonOutput + origReadonlyMode := readonlyMode + origActor := actor + origDiscover := discoverRunIDByWorkflowNameFunc + origUpdate := updateGateAwaitIDFunc + origStatus := checkGHRunStatusFunc + t.Cleanup(func() { + store = origStore + rootCtx = origRootCtx + jsonOutput = origJSONOutput + readonlyMode = origReadonlyMode + actor = origActor + discoverRunIDByWorkflowNameFunc = origDiscover + updateGateAwaitIDFunc = origUpdate + checkGHRunStatusFunc = origStatus + resetGateCheckFlags(t) + }) + + resetGateCheckFlags(t) + + fakeStore := &fakeGateCheckStore{ + issues: []*types.Issue{ + { + ID: "bd-gate", + IssueType: "gate", + AwaitType: "gh:run", + AwaitID: "release.yml", + }, + }, + } + + store = fakeStore + rootCtx = context.Background() + jsonOutput = false + readonlyMode = false + actor = "test-actor" + + if err := gateCheckCmd.Flags().Set("dry-run", map[bool]string{true: "true", false: "false"}[tt.dryRun]); err != nil { + t.Fatalf("set dry-run flag: %v", err) + } + if err := gateCheckCmd.Flags().Set("type", "gh:run"); err != nil { + t.Fatalf("set type flag: %v", err) + } + if err := gateCheckCmd.Flags().Set("escalate", "false"); err != nil { + t.Fatalf("set escalate flag: %v", err) + } + if err := gateCheckCmd.Flags().Set("limit", "100"); err != nil { + t.Fatalf("set limit flag: %v", err) + } + + updateCalls := 0 + discoverRunIDByWorkflowNameFunc = func(workflowHint string) (string, error) { + if workflowHint != "release.yml" { + t.Fatalf("unexpected workflow hint %q", workflowHint) + } + return "12345", nil + } + updateGateAwaitIDFunc = func(_ interface{}, gateID, runID string) error { + updateCalls++ + if gateID != "bd-gate" { + t.Fatalf("expected gate ID bd-gate, got %q", gateID) + } + if runID != "12345" { + t.Fatalf("expected discovered run ID 12345, got %q", runID) + } + return nil + } + checkGHRunStatusFunc = func(runID string) (bool, bool, string, error) { + if runID != "12345" { + t.Fatalf("expected discovered run ID 12345, got %q", runID) + } + return true, false, "workflow 'release' succeeded", nil + } + + output := captureGateStdout(t, func() { + gateCheckCmd.Run(gateCheckCmd, nil) + }) + + if updateCalls != tt.wantUpdateCalls { + t.Fatalf("updateGateAwaitIDFunc call count = %d, want %d", updateCalls, tt.wantUpdateCalls) + } + if len(fakeStore.closeCalls) != tt.wantCloseCalls { + t.Fatalf("CloseIssue call count = %d, want %d", len(fakeStore.closeCalls), tt.wantCloseCalls) + } + if !gateTestContains(output, tt.wantOutput) { + t.Fatalf("output %q does not contain %q", output, tt.wantOutput) + } + if !gateTestContains(output, "Checked 1 gates: 1 resolved, 0 escalated, 0 errors") { + t.Fatalf("summary output missing expected counts: %q", output) + } + if fakeStore.searchFilter.IssueType == nil || *fakeStore.searchFilter.IssueType != "gate" { + t.Fatalf("expected gate filter, got %+v", fakeStore.searchFilter) + } + if len(fakeStore.searchFilter.ExcludeStatus) != 1 || fakeStore.searchFilter.ExcludeStatus[0] != types.StatusClosed { + t.Fatalf("expected closed-status exclusion, got %+v", fakeStore.searchFilter.ExcludeStatus) + } + if fakeStore.searchFilter.Limit != 100 { + t.Fatalf("expected limit 100, got %d", fakeStore.searchFilter.Limit) + } + if tt.wantCloseCalls == 1 { + call := fakeStore.closeCalls[0] + if call.id != "bd-gate" { + t.Fatalf("expected CloseIssue for bd-gate, got %q", call.id) + } + if call.reason != "workflow 'release' succeeded" { + t.Fatalf("expected CloseIssue reason to match status, got %q", call.reason) + } + if call.actor != "test-actor" { + t.Fatalf("expected CloseIssue actor test-actor, got %q", call.actor) + } + } + }) + } +} + func TestWorkflowNameMatches(t *testing.T) { tests := []struct { name string @@ -240,6 +648,36 @@ func TestWorkflowNameMatches(t *testing.T) { } } +func installFakeGHScript(t *testing.T, stdout string) { + t.Helper() + + dir := t.TempDir() + + var ( + scriptPath string + script string + ) + + if runtime.GOOS == "windows" { + scriptPath = filepath.Join(dir, "gh.cmd") + script = "@echo off\r\necho " + stdout + "\r\n" + } else { + scriptPath = filepath.Join(dir, "gh") + script = "#!/bin/sh\ncat <<'EOF'\n" + stdout + "\nEOF\n" + } + + if err := os.WriteFile(scriptPath, []byte(script), 0o755); err != nil { + t.Fatalf("write fake gh: %v", err) + } + if runtime.GOOS != "windows" { + if err := os.Chmod(scriptPath, 0o755); err != nil { + t.Fatalf("chmod fake gh: %v", err) + } + } + + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + // gateTestContainsIgnoreCase checks if haystack contains needle (case-insensitive) func gateTestContainsIgnoreCase(haystack, needle string) bool { return gateTestContains(gateTestLowerCase(haystack), gateTestLowerCase(needle)) diff --git a/cmd/bd/store_factory_test.go b/cmd/bd/store_factory_test.go index 2588515d2..9a9994ee2 100644 --- a/cmd/bd/store_factory_test.go +++ b/cmd/bd/store_factory_test.go @@ -90,29 +90,6 @@ func TestNewDoltStoreFromConfig_HyphenatedDBName(t *testing.T) { } } -// TestSanitizeDBName verifies the sanitization logic for database names. -func TestSanitizeDBName(t *testing.T) { - tests := []struct { - input string - want string - }{ - {"my-project", "my_project"}, - {"jtbot-core", "jtbot_core"}, - {"no-hyphens-here", "no_hyphens_here"}, - {"dots.and-hyphens", "dots_and_hyphens"}, - {"already_clean", "already_clean"}, - {"beads", "beads"}, - } - for _, tt := range tests { - t.Run(tt.input, func(t *testing.T) { - got := sanitizeDBName(tt.input) - if got != tt.want { - t.Errorf("sanitizeDBName(%q) = %q, want %q", tt.input, got, tt.want) - } - }) - } -} - // TestMigrateHyphenatedDB_PersistsToMetadata verifies that migrateHyphenatedDB // updates metadata.json with the sanitized database name. func TestMigrateHyphenatedDB_PersistsToMetadata(t *testing.T) {