Beads had two implementations of most issue verbs: one for the direct route
(the CLI talking to a store it opened itself) and one for the proxied-server
route (the CLI talking through a unit of work over a running Dolt server).
They drifted — different commit messages, different transaction boundaries,
different refusals, occasionally different answers.
Seven role interfaces now live in the leaf package issueops: Lifecycle,
Reader, ReadyClaimer, BatchCloser, DependencyEditor, Commenter and Relations.
Each is reached only through a store accessor, never a constructor, because
the accessor is where the hook and telemetry decorators add their layers.
Three implementations back every role — dolt, embeddeddolt, and the
unit-of-work provider the proxied route uses. Both routes call the same role
for close, dep add/remove/list, comment, ready --claim and update.
A depguard rule (httpapi-domain-boundary) denies internal/storage/domain from
internal/httpapi, so a handler cannot reach uw.IssueUseCase() past the roles
and open a second front door one lint-clean commit at a time.
Behaviour users will notice, all in the CHANGELOG:
- bd close a b c is one Dolt commit, not three, and --claim-next moved
inside that transaction so it fires only when something landed
- the open-children guard moved into the transaction and its hand-rolled
cmd/bd copy is gone, removing a read-then-write window that made
bd close <child> <parent> depend on argument order
- bd dep add --file honours deferred version commit
- embedded bd comment writes the role's message and author
- dep verb commit messages are the role's on the direct route
Wisp-sourced dependency edges are restored. Moving bd dep add onto the role
had pinned an edge's SOURCE to the issues plane, and the two routes did not
even fail alike: direct refused with "issue <id> not found", proxied threw an
fk_dep_issue violation. The comment justifying the pin claimed the issues
plane was "the only one its unit-of-work sibling can reach" — that was false;
domain.DependencyUseCase declared a full set of wisp twins with no production
caller. All three implementations now route per edge by the edge's own
source. A mixed request stays one transaction: parent-child-first ordering
and the whole-graph cycle gate span both planes, and a refusal rolls back
both. Behind the role, three bulk add verbs collapsed into one source-routed
AddDependencies, so no plane-pinned variant is left to reach for by mistake.
Six Provenance fields with no production caller were deleted rather than
wired — CloseRequest, CloseBatchRequest, ClaimNextRequest, AddCommentRequest,
AddDependenciesRequest, RemoveDependencyRequest. Each role already composes an
id-bearing message, so a caller could only restate the default and make it
unreachable from production. Two are not caller-settable even in principle:
CloseBatchCommitMessage names what LANDED and ClaimNextCommitMessage names the
id the claim WON. UpdateRequest and ReopenRequest keep theirs; commit messages
users see are unchanged.
Verified: build, vet and gofmt clean; golangci-lint 0 issues; protocol corpus
byte-identical under BEADS_PROTOCOL_REQUIRE_DOLT=1; all twelve
DependencyEditor conformance wirings green (four contract functions against
each implementation); TestEmbeddedDepAddWispSource runs bd dep add <wisp-id>
at the front door and was demonstrated RED against the pinned routing first.
Three internal/storage/dolt failures reproduce on pristine origin/main.
Known gaps are enumerated in the PR description rather than left to be found:
comment listing is on no role, bd dep tree and bd dep cycles have no role,
bd create and bd reopen are on Lifecycle only on the direct route, per-edge
line attribution is lost in bd dep add --file, multi-store bd close
--claim-next rides only the first store's batch, and the is_blocked staging gap
(bd-2y9ke, predates this change). Seven of the eight role interfaces now have a
shared conformance contract in backend/conformance, run at all three
implementations; main's Claimer, added in parallel by #5334, is the eighth and
has none yet.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2460 lines
71 KiB
Go
2460 lines
71 KiB
Go
package dolt
|
|
|
|
import (
|
|
"context"
|
|
"crypto/rand"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"os"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/steveyegge/beads/internal/storage"
|
|
"github.com/steveyegge/beads/internal/storage/doltutil"
|
|
"github.com/steveyegge/beads/internal/testutil"
|
|
"github.com/steveyegge/beads/internal/types"
|
|
)
|
|
|
|
// testTimeout is the maximum time for any single test operation.
|
|
// The embedded Dolt driver can be slow, especially for complex JOIN queries.
|
|
// If tests are timing out, it may indicate an issue with the embedded Dolt
|
|
// driver's async operations rather than with the DoltStore implementation.
|
|
// testTimeout bounds each test's context. It must cover a cold store setup —
|
|
// container-assisted connect plus the FULL migration chain (every versioned +
|
|
// ignored migration, each Dolt-committed), which grows as migrations
|
|
// accumulate — with headroom for a loaded machine; some tests set up two
|
|
// stores under one context.
|
|
const testTimeout = 45 * time.Second
|
|
|
|
// testSem limits concurrent database-touching tests to avoid overwhelming the
|
|
// shared Dolt testcontainer. Without this, 200+ parallel tests cause a
|
|
// connection storm that crashes the container. Size 6 is conservative —
|
|
// the container handles ~10 concurrent connections but we leave headroom.
|
|
var testSem = make(chan struct{}, 2)
|
|
|
|
// acquireTestSlot blocks until a semaphore slot is available.
|
|
// Must be called AFTER t.Parallel() to avoid deadlocks (t.Parallel suspends
|
|
// the goroutine, and if it holds a semaphore slot while suspended, other
|
|
// tests can't proceed).
|
|
func acquireTestSlot() { testSem <- struct{}{} }
|
|
|
|
// releaseTestSlot returns a semaphore slot.
|
|
func releaseTestSlot() { <-testSem }
|
|
|
|
func acquireAllTestSlots() {
|
|
for i := 0; i < cap(testSem); i++ {
|
|
acquireTestSlot()
|
|
}
|
|
}
|
|
|
|
func releaseAllTestSlots() {
|
|
for i := 0; i < cap(testSem); i++ {
|
|
releaseTestSlot()
|
|
}
|
|
}
|
|
|
|
// testContext returns a context with timeout for test operations
|
|
func testContext(t *testing.T) (context.Context, context.CancelFunc) {
|
|
t.Helper()
|
|
return context.WithTimeout(context.Background(), testTimeout)
|
|
}
|
|
|
|
// skipIfNoDolt skips the test if Dolt is not installed or the test server
|
|
// is not running. This prevents tests from accidentally hitting a production
|
|
// Dolt server — tests MUST run against the isolated test server started by
|
|
// TestMain in testmain_test.go.
|
|
func skipIfNoDolt(t *testing.T) {
|
|
t.Helper()
|
|
testutil.RequireDoltBinary(t)
|
|
if testServerPort == 0 {
|
|
t.Skip("Test Dolt server not running, skipping test")
|
|
}
|
|
}
|
|
|
|
// uniqueTestDBName generates a unique database name for test isolation.
|
|
// Each test gets its own database, preventing cross-test interference and
|
|
// avoiding any risk of connecting to production data.
|
|
func uniqueTestDBName(t *testing.T) string {
|
|
t.Helper()
|
|
buf := make([]byte, 6)
|
|
if _, err := rand.Read(buf); err != nil {
|
|
t.Fatalf("failed to generate random bytes: %v", err)
|
|
}
|
|
return "testdb_" + hex.EncodeToString(buf)
|
|
}
|
|
|
|
// doltCommitCount reports how many commits the test branch has. Tests that
|
|
// care whether an operation recorded history take it before and after rather
|
|
// than reading the top of dolt_log, because two commits made inside one second
|
|
// tie on date and the ordering between them is not something to rely on.
|
|
func doltCommitCount(ctx context.Context, t *testing.T, store *DoltStore) int {
|
|
t.Helper()
|
|
var n int
|
|
if err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM dolt_log").Scan(&n); err != nil {
|
|
t.Fatalf("count dolt_log: %v", err)
|
|
}
|
|
return n
|
|
}
|
|
|
|
// doltHasCommitMessage reports whether the test branch has a commit with
|
|
// exactly this message.
|
|
func doltHasCommitMessage(ctx context.Context, t *testing.T, store *DoltStore, message string) bool {
|
|
t.Helper()
|
|
var n int
|
|
if err := store.db.QueryRowContext(ctx,
|
|
"SELECT COUNT(*) FROM dolt_log WHERE message = ?", message).Scan(&n); err != nil {
|
|
t.Fatalf("query dolt_log for %q: %v", message, err)
|
|
}
|
|
return n > 0
|
|
}
|
|
|
|
// requireCleanTables fails when any named table is still dirty in the working
|
|
// set. It is how a test says "the operation staged and committed what it
|
|
// wrote", which is the half of the staging contract a data read cannot see.
|
|
func requireCleanTables(ctx context.Context, t *testing.T, store *DoltStore, tables ...string) {
|
|
t.Helper()
|
|
for _, table := range tables {
|
|
var dirty int
|
|
if err := store.db.QueryRowContext(ctx,
|
|
"SELECT COUNT(*) FROM dolt_status WHERE table_name = ?", table).Scan(&dirty); err != nil {
|
|
t.Fatalf("query dolt_status for %s: %v", table, err)
|
|
}
|
|
if dirty != 0 {
|
|
t.Fatalf("%s is still dirty in the working set after the operation committed", table)
|
|
}
|
|
}
|
|
}
|
|
|
|
// setupTestStore creates a test store on the shared database with branch isolation.
|
|
// Each test gets its own branch (COW snapshot), preventing cross-test data leakage
|
|
// without the overhead of CREATE/DROP DATABASE per test.
|
|
//
|
|
// Automatically marks the test as safe for parallel execution since each test
|
|
// gets its own Dolt connection checked out to a unique branch.
|
|
func setupTestStore(t *testing.T) (*DoltStore, func()) {
|
|
t.Helper()
|
|
skipIfNoDolt(t)
|
|
t.Parallel()
|
|
|
|
// Acquire AFTER t.Parallel() to avoid deadlock — t.Parallel() suspends
|
|
// the goroutine until the parent test finishes its sequential phase.
|
|
acquireTestSlot()
|
|
t.Cleanup(releaseTestSlot) // guaranteed even on panic/Fatalf
|
|
|
|
if testSharedDB == "" {
|
|
t.Fatal("testSharedDB not set — TestMain did not initialize shared database")
|
|
}
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
tmpDir, err := os.MkdirTemp("", "dolt-test-*")
|
|
if err != nil {
|
|
t.Fatalf("failed to create temp dir: %v", err)
|
|
}
|
|
|
|
cfg := &Config{
|
|
Path: tmpDir,
|
|
CommitterName: "test",
|
|
CommitterEmail: "test@example.com",
|
|
Database: testSharedDB,
|
|
MaxOpenConns: 1, // Required: DOLT_CHECKOUT is session-level
|
|
}
|
|
|
|
store, err := New(ctx, cfg)
|
|
if err != nil {
|
|
os.RemoveAll(tmpDir)
|
|
t.Fatalf("failed to create Dolt store: %v", err)
|
|
}
|
|
|
|
// Create an isolated branch for this test
|
|
_, branchCleanup := testutil.StartTestBranch(t, store.db, testSharedDB)
|
|
if _, err := initSchemaOnDB(ctx, store.db); err != nil {
|
|
branchCleanup()
|
|
store.Close()
|
|
os.RemoveAll(tmpDir)
|
|
t.Fatalf("failed to initialize branch-local ignored schema: %v", err)
|
|
}
|
|
|
|
cleanup := func() {
|
|
branchCleanup()
|
|
store.Close()
|
|
os.RemoveAll(tmpDir)
|
|
}
|
|
|
|
return store, cleanup
|
|
}
|
|
|
|
// setupConcurrentTestStore creates a test store with its own database for
|
|
// concurrent tests that need multiple connections. Branch-per-test isolation
|
|
// requires MaxOpenConns=1, which prevents concurrent transactions.
|
|
// MaxOpenConns is limited to 3 to avoid overwhelming the test container.
|
|
func setupConcurrentTestStore(t *testing.T) (*DoltStore, func()) {
|
|
t.Helper()
|
|
skipIfNoDolt(t)
|
|
acquireTestSlot()
|
|
t.Cleanup(releaseTestSlot)
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
tmpDir, err := os.MkdirTemp("", "dolt-concurrent-test-*")
|
|
if err != nil {
|
|
t.Fatalf("failed to create temp dir: %v", err)
|
|
}
|
|
|
|
dbName := uniqueTestDBName(t)
|
|
|
|
cfg := &Config{
|
|
Path: tmpDir,
|
|
CommitterName: "test",
|
|
CommitterEmail: "test@example.com",
|
|
Database: dbName,
|
|
MaxOpenConns: 2, // limit to avoid overwhelming the test container
|
|
CreateIfMissing: true, // tests create fresh databases
|
|
}
|
|
|
|
store, err := New(ctx, cfg)
|
|
if err != nil {
|
|
os.RemoveAll(tmpDir)
|
|
t.Fatalf("failed to create Dolt store: %v", err)
|
|
}
|
|
// Close idle connections immediately to reduce container pressure.
|
|
store.db.SetMaxIdleConns(0)
|
|
store.db.SetConnMaxIdleTime(time.Second)
|
|
|
|
if err := store.SetConfig(ctx, "issue_prefix", "test"); err != nil {
|
|
store.Close()
|
|
os.RemoveAll(tmpDir)
|
|
t.Fatalf("failed to set prefix: %v", err)
|
|
}
|
|
|
|
cleanup := func() {
|
|
// Skip DROP DATABASE — rapid CREATE/DROP cycles crash the Dolt container.
|
|
// Orphan databases are cleaned up when the container is terminated.
|
|
store.Close()
|
|
os.RemoveAll(tmpDir)
|
|
}
|
|
|
|
return store, cleanup
|
|
}
|
|
|
|
func TestNewDoltStore(t *testing.T) {
|
|
skipIfNoDolt(t)
|
|
|
|
ctx := context.Background()
|
|
tmpDir, err := os.MkdirTemp("", "dolt-test-*")
|
|
if err != nil {
|
|
t.Fatalf("failed to create temp dir: %v", err)
|
|
}
|
|
defer os.RemoveAll(tmpDir)
|
|
|
|
dbName := uniqueTestDBName(t)
|
|
cfg := &Config{
|
|
Path: tmpDir,
|
|
CommitterName: "test",
|
|
CommitterEmail: "test@example.com",
|
|
Database: dbName,
|
|
CreateIfMissing: true, // tests create fresh databases
|
|
}
|
|
|
|
store, err := New(ctx, cfg)
|
|
if err != nil {
|
|
t.Fatalf("failed to create Dolt store: %v", err)
|
|
}
|
|
defer func() {
|
|
_, _ = store.db.ExecContext(ctx, fmt.Sprintf("DROP DATABASE IF EXISTS `%s`", dbName))
|
|
store.Close()
|
|
}()
|
|
|
|
// Verify store path
|
|
if store.Path() != tmpDir {
|
|
t.Errorf("expected path %s, got %s", tmpDir, store.Path())
|
|
}
|
|
|
|
// Verify not closed
|
|
if store.closed.Load() {
|
|
t.Error("store should not be closed")
|
|
}
|
|
}
|
|
|
|
// TestCreateIssueEventType verifies that CreateIssue accepts event type
|
|
// without requiring it in types.custom config (GH#1356).
|
|
func TestCreateIssueEventType(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// setupTestStore does not set types.custom, so this reproduces the bug
|
|
event := &types.Issue{
|
|
Title: "state change audit trail",
|
|
Status: types.StatusClosed,
|
|
Priority: 4,
|
|
IssueType: types.TypeEvent,
|
|
}
|
|
err := store.CreateIssue(ctx, event, "test-user")
|
|
if err != nil {
|
|
t.Fatalf("CreateIssue with event type should succeed without types.custom, got: %v", err)
|
|
}
|
|
|
|
got, err := store.GetIssue(ctx, event.ID)
|
|
if err != nil {
|
|
t.Fatalf("GetIssue failed: %v", err)
|
|
}
|
|
if got.IssueType != types.TypeEvent {
|
|
t.Errorf("Expected IssueType %q, got %q", types.TypeEvent, got.IssueType)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreConfig(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Test SetConfig
|
|
if err := store.SetConfig(ctx, "test_key", "test_value"); err != nil {
|
|
t.Fatalf("failed to set config: %v", err)
|
|
}
|
|
|
|
// Test GetConfig
|
|
value, err := store.GetConfig(ctx, "test_key")
|
|
if err != nil {
|
|
t.Fatalf("failed to get config: %v", err)
|
|
}
|
|
if value != "test_value" {
|
|
t.Errorf("expected 'test_value', got %q", value)
|
|
}
|
|
|
|
// Test GetAllConfig
|
|
allConfig, err := store.GetAllConfig(ctx)
|
|
if err != nil {
|
|
t.Fatalf("failed to get all config: %v", err)
|
|
}
|
|
if allConfig["test_key"] != "test_value" {
|
|
t.Errorf("expected test_key in all config")
|
|
}
|
|
|
|
// Test DeleteConfig
|
|
if err := store.DeleteConfig(ctx, "test_key"); err != nil {
|
|
t.Fatalf("failed to delete config: %v", err)
|
|
}
|
|
value, err = store.GetConfig(ctx, "test_key")
|
|
if err != nil {
|
|
t.Fatalf("failed to get deleted config: %v", err)
|
|
}
|
|
if value != "" {
|
|
t.Errorf("expected empty value after delete, got %q", value)
|
|
}
|
|
}
|
|
|
|
// TestSetConfigNormalizesIssuePrefix verifies that SetConfig strips trailing
|
|
// hyphens from issue_prefix to prevent double-hyphen bead IDs (bd-6uly).
|
|
func TestSetConfigNormalizesIssuePrefix(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Set prefix WITH trailing hyphen — should be normalized
|
|
if err := store.SetConfig(ctx, "issue_prefix", "gt-"); err != nil {
|
|
t.Fatalf("SetConfig failed: %v", err)
|
|
}
|
|
|
|
value, err := store.GetConfig(ctx, "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("GetConfig failed: %v", err)
|
|
}
|
|
if value != "gt" {
|
|
t.Errorf("expected issue_prefix 'gt' (trailing hyphen stripped), got %q", value)
|
|
}
|
|
}
|
|
|
|
// TestCreateIssueNoDoubleHyphen verifies that issue IDs don't get double
|
|
// hyphens even if the DB somehow has a trailing-hyphen prefix (bd-6uly).
|
|
func TestCreateIssueNoDoubleHyphen(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Bypass SetConfig normalization: write trailing-hyphen prefix directly to DB
|
|
_, err := store.db.ExecContext(ctx, "UPDATE config SET value = ? WHERE `key` = ?", "gt-", "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("failed to set raw prefix: %v", err)
|
|
}
|
|
|
|
issue := &types.Issue{
|
|
Title: "test double hyphen",
|
|
Status: types.StatusOpen,
|
|
Priority: 3,
|
|
IssueType: types.TypeBug,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue failed: %v", err)
|
|
}
|
|
|
|
// ID should start with "gt-" not "gt--"
|
|
if strings.Contains(issue.ID, "--") {
|
|
t.Errorf("issue ID contains double hyphen: %q", issue.ID)
|
|
}
|
|
if !strings.HasPrefix(issue.ID, "gt-") {
|
|
t.Errorf("issue ID should start with 'gt-', got %q", issue.ID)
|
|
}
|
|
}
|
|
|
|
// TestCreateWispNoDoubleHyphen verifies that wisp IDs don't get double
|
|
// hyphens even if the DB has a trailing-hyphen prefix (bd-6uly).
|
|
func TestCreateWispNoDoubleHyphen(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Bypass SetConfig normalization: write trailing-hyphen prefix directly to DB
|
|
_, err := store.db.ExecContext(ctx, "UPDATE config SET value = ? WHERE `key` = ?", "gt-", "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("failed to set raw prefix: %v", err)
|
|
}
|
|
|
|
wisp := &types.Issue{
|
|
Title: "test wisp double hyphen",
|
|
Status: types.StatusOpen,
|
|
Priority: 3,
|
|
IssueType: types.TypeBug,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, wisp, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue (wisp) failed: %v", err)
|
|
}
|
|
|
|
// Wisp ID should contain "gt-wisp-" not "gt--wisp-"
|
|
if strings.Contains(wisp.ID, "--") {
|
|
t.Errorf("wisp ID contains double hyphen: %q", wisp.ID)
|
|
}
|
|
if !strings.HasPrefix(wisp.ID, "gt-wisp-") {
|
|
t.Errorf("wisp ID should start with 'gt-wisp-', got %q", wisp.ID)
|
|
}
|
|
}
|
|
|
|
// TestCreateWispNoDoublePrefix verifies that wisps with IDPrefix="wisp" don't
|
|
// get double-prefixed as "bd-wisp-wisp-xxx" (beads-yzh).
|
|
func TestCreateWispNoDoublePrefix(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
wisp := &types.Issue{
|
|
Title: "test wisp double prefix",
|
|
Status: types.StatusOpen,
|
|
Priority: 3,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
IDPrefix: "wisp", // Set by cloneSubgraph for wisp molecules
|
|
}
|
|
if err := store.CreateIssue(ctx, wisp, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue (wisp) failed: %v", err)
|
|
}
|
|
|
|
// ID should be "<prefix>-wisp-<hash>", NOT "<prefix>-wisp-wisp-<hash>"
|
|
if strings.Contains(wisp.ID, "wisp-wisp") {
|
|
t.Errorf("wisp ID has double 'wisp' prefix: %q", wisp.ID)
|
|
}
|
|
if !strings.Contains(wisp.ID, "-wisp-") {
|
|
t.Errorf("wisp ID should contain '-wisp-', got %q", wisp.ID)
|
|
}
|
|
}
|
|
|
|
// TestTransactionCreateIssueNoDoubleHyphen verifies that issue IDs created
|
|
// within a transaction don't get double hyphens if the DB has a trailing-hyphen
|
|
// prefix (bd-6uly). This tests the transaction.go code path.
|
|
func TestTransactionCreateIssueNoDoubleHyphen(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Bypass SetConfig normalization: write trailing-hyphen prefix directly to DB
|
|
_, err := store.db.ExecContext(ctx, "UPDATE config SET value = ? WHERE `key` = ?", "gt-", "issue_prefix")
|
|
if err != nil {
|
|
t.Fatalf("failed to set raw prefix: %v", err)
|
|
}
|
|
|
|
var createdID string
|
|
err = store.RunInTransaction(ctx, "test-tx", func(tx storage.Transaction) error {
|
|
issue := &types.Issue{
|
|
Title: "test tx double hyphen",
|
|
Status: types.StatusOpen,
|
|
Priority: 3,
|
|
IssueType: types.TypeBug,
|
|
}
|
|
if err := tx.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
return err
|
|
}
|
|
createdID = issue.ID
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("RunInTransaction failed: %v", err)
|
|
}
|
|
|
|
if strings.Contains(createdID, "--") {
|
|
t.Errorf("transaction-created issue ID contains double hyphen: %q", createdID)
|
|
}
|
|
if !strings.HasPrefix(createdID, "gt-") {
|
|
t.Errorf("issue ID should start with 'gt-', got %q", createdID)
|
|
}
|
|
}
|
|
|
|
func TestGetCustomTypes(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// types.custom is set via SetConfig (not seeded by defaultConfig)
|
|
if err := store.SetConfig(ctx, "types.custom", "molecule,gate,convoy,merge-request,slot,agent,role,rig,message"); err != nil {
|
|
t.Fatalf("SetConfig(types.custom) failed: %v", err)
|
|
}
|
|
|
|
types, err := store.GetCustomTypes(ctx)
|
|
if err != nil {
|
|
t.Fatalf("GetCustomTypes failed: %v", err)
|
|
}
|
|
if len(types) == 0 {
|
|
t.Fatal("expected custom types from SetConfig, got none")
|
|
}
|
|
|
|
// Verify "agent" is among the configured types
|
|
found := false
|
|
for _, ct := range types {
|
|
if ct == "agent" {
|
|
found = true
|
|
break
|
|
}
|
|
}
|
|
if !found {
|
|
t.Errorf("expected 'agent' in custom types, got %v", types)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreIssue(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue
|
|
issue := &types.Issue{
|
|
Title: "Test Issue",
|
|
Description: "Test description",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Verify ID was generated
|
|
if issue.ID == "" {
|
|
t.Error("expected issue ID to be generated")
|
|
}
|
|
|
|
// Get the issue back
|
|
retrieved, err := store.GetIssue(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get issue: %v", err)
|
|
}
|
|
if retrieved == nil {
|
|
t.Fatal("expected to retrieve issue")
|
|
}
|
|
if retrieved.Title != issue.Title {
|
|
t.Errorf("expected title %q, got %q", issue.Title, retrieved.Title)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreIssueUpdate(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue
|
|
issue := &types.Issue{
|
|
Title: "Original Title",
|
|
Description: "Original description",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Update the issue
|
|
updates := map[string]interface{}{
|
|
"title": "Updated Title",
|
|
"priority": 1,
|
|
"status": string(types.StatusInProgress),
|
|
}
|
|
|
|
if err := store.UpdateIssue(ctx, issue.ID, updates, "tester"); err != nil {
|
|
t.Fatalf("failed to update issue: %v", err)
|
|
}
|
|
|
|
// Get the updated issue
|
|
retrieved, err := store.GetIssue(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get issue: %v", err)
|
|
}
|
|
if retrieved.Title != "Updated Title" {
|
|
t.Errorf("expected title 'Updated Title', got %q", retrieved.Title)
|
|
}
|
|
if retrieved.Priority != 1 {
|
|
t.Errorf("expected priority 1, got %d", retrieved.Priority)
|
|
}
|
|
if retrieved.Status != types.StatusInProgress {
|
|
t.Errorf("expected status in_progress, got %s", retrieved.Status)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreIssueClose(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue
|
|
issue := &types.Issue{
|
|
Title: "Issue to Close",
|
|
Description: "Will be closed",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Close the issue
|
|
if err := store.CloseIssue(ctx, issue.ID, "completed", "tester", "session123"); err != nil {
|
|
t.Fatalf("failed to close issue: %v", err)
|
|
}
|
|
|
|
// Get the closed issue
|
|
retrieved, err := store.GetIssue(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get issue: %v", err)
|
|
}
|
|
if retrieved.Status != types.StatusClosed {
|
|
t.Errorf("expected status closed, got %s", retrieved.Status)
|
|
}
|
|
if retrieved.ClosedAt == nil {
|
|
t.Error("expected closed_at to be set")
|
|
}
|
|
}
|
|
|
|
// TestCloseIssueNotFound verifies that closing a non-existent issue returns an
|
|
// error that wraps storage.ErrNotFound, for parity with GetIssue/UpdateIssue/
|
|
// DeleteIssue. Guards against the regression where CloseIssue returned a bare
|
|
// fmt.Errorf that errors.Is(err, storage.ErrNotFound) could not match (mybd-fv7r).
|
|
func TestCloseIssueNotFound(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
err := store.CloseIssue(ctx, "does-not-exist", "completed", "tester", "session123")
|
|
if err == nil {
|
|
t.Fatal("expected error closing non-existent issue, got nil")
|
|
}
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected error to wrap storage.ErrNotFound, got: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestClosePromotedWisp verifies that bd close works for wisps that were
|
|
// promoted to the issues table via PromoteFromEphemeral (bd-ftc).
|
|
// Promoted wisps have -wisp- in their ID but live in the issues table,
|
|
// so routing must fall through from the wisps table.
|
|
func TestClosePromotedWisp(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create a wisp (goes to wisps table)
|
|
wisp := &types.Issue{
|
|
Title: "Wisp to promote and close",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, wisp, "tester"); err != nil {
|
|
t.Fatalf("CreateIssue (wisp) failed: %v", err)
|
|
}
|
|
got, err := store.GetIssue(ctx, wisp.ID)
|
|
if err != nil {
|
|
t.Fatalf("GetIssue failed for promoted wisp: %v", err)
|
|
}
|
|
if got.ID != wisp.ID {
|
|
t.Fatalf("GetIssue returned wrong ID: %q vs %q", got.ID, wisp.ID)
|
|
}
|
|
if !IsEphemeralID(wisp.ID) {
|
|
t.Fatalf("expected wisp ID to match ephemeral pattern, got %q", wisp.ID)
|
|
}
|
|
|
|
// Promote the wisp (moves from wisps table to issues table)
|
|
if err := store.PromoteFromEphemeral(ctx, wisp.ID, "tester"); err != nil {
|
|
t.Fatalf("PromoteFromEphemeral failed: %v", err)
|
|
}
|
|
|
|
// Verify wisp is no longer in wisps table but findable via GetIssue
|
|
if store.isActiveWisp(ctx, wisp.ID) {
|
|
t.Fatal("promoted wisp should not be active in wisps table")
|
|
}
|
|
got, err = store.GetIssue(ctx, wisp.ID)
|
|
if err != nil {
|
|
t.Fatalf("GetIssue failed for promoted wisp: %v", err)
|
|
}
|
|
if got.ID != wisp.ID {
|
|
t.Fatalf("GetIssue returned wrong ID: %q vs %q", got.ID, wisp.ID)
|
|
}
|
|
|
|
// Close the promoted wisp — this was failing before bd-ftc fix
|
|
if err := store.CloseIssue(ctx, wisp.ID, "completed", "tester", "session1"); err != nil {
|
|
t.Fatalf("CloseIssue failed for promoted wisp: %v", err)
|
|
}
|
|
|
|
// Verify it was closed
|
|
closed, err := store.GetIssue(ctx, wisp.ID)
|
|
if err != nil {
|
|
t.Fatalf("GetIssue failed after close: %v", err)
|
|
}
|
|
if closed.Status != types.StatusClosed {
|
|
t.Errorf("expected status closed, got %s", closed.Status)
|
|
}
|
|
if closed.ClosedAt == nil {
|
|
t.Error("expected closed_at to be set")
|
|
}
|
|
|
|
// Also verify GetIssuesByIDs works (the batch path that was broken)
|
|
batch, err := store.GetIssuesByIDs(ctx, []string{wisp.ID})
|
|
if err != nil {
|
|
t.Fatalf("GetIssuesByIDs failed for promoted wisp: %v", err)
|
|
}
|
|
if len(batch) != 1 {
|
|
t.Fatalf("GetIssuesByIDs returned %d issues, want 1", len(batch))
|
|
}
|
|
if batch[0].ID != wisp.ID {
|
|
t.Errorf("GetIssuesByIDs returned wrong ID: %q", batch[0].ID)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreLabels(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue
|
|
issue := &types.Issue{
|
|
Title: "Issue with Labels",
|
|
Description: "Test labels",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Add labels
|
|
if err := store.AddLabel(ctx, issue.ID, "bug", "tester"); err != nil {
|
|
t.Fatalf("failed to add label: %v", err)
|
|
}
|
|
if err := store.AddLabel(ctx, issue.ID, "priority", "tester"); err != nil {
|
|
t.Fatalf("failed to add second label: %v", err)
|
|
}
|
|
|
|
// Get labels
|
|
labels, err := store.GetLabels(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get labels: %v", err)
|
|
}
|
|
if len(labels) != 2 {
|
|
t.Errorf("expected 2 labels, got %d", len(labels))
|
|
}
|
|
|
|
// Remove label
|
|
if err := store.RemoveLabel(ctx, issue.ID, "bug", "tester"); err != nil {
|
|
t.Fatalf("failed to remove label: %v", err)
|
|
}
|
|
|
|
// Verify removal
|
|
labels, err = store.GetLabels(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get labels after removal: %v", err)
|
|
}
|
|
if len(labels) != 1 {
|
|
t.Errorf("expected 1 label after removal, got %d", len(labels))
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreDependencies(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create parent and child issues (both tasks for a same-type blocks
|
|
// pair; cross-type blocks edges are now allowed for unrelated issues).
|
|
parent := &types.Issue{
|
|
ID: "test-parent",
|
|
Title: "Parent Issue",
|
|
Description: "Parent description",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
child := &types.Issue{
|
|
ID: "test-child",
|
|
Title: "Child Issue",
|
|
Description: "Child description",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, parent, "tester"); err != nil {
|
|
t.Fatalf("failed to create parent issue: %v", err)
|
|
}
|
|
if err := store.CreateIssue(ctx, child, "tester"); err != nil {
|
|
t.Fatalf("failed to create child issue: %v", err)
|
|
}
|
|
|
|
// Add dependency (child depends on parent)
|
|
dep := &types.Dependency{
|
|
IssueID: child.ID,
|
|
DependsOnID: parent.ID,
|
|
Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dependency: %v", err)
|
|
}
|
|
|
|
// Get dependencies
|
|
deps, err := store.GetDependencies(ctx, child.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get dependencies: %v", err)
|
|
}
|
|
if len(deps) != 1 {
|
|
t.Errorf("expected 1 dependency, got %d", len(deps))
|
|
}
|
|
if deps[0].ID != parent.ID {
|
|
t.Errorf("expected dependency on %s, got %s", parent.ID, deps[0].ID)
|
|
}
|
|
|
|
// Get dependents
|
|
dependents, err := store.GetDependents(ctx, parent.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get dependents: %v", err)
|
|
}
|
|
if len(dependents) != 1 {
|
|
t.Errorf("expected 1 dependent, got %d", len(dependents))
|
|
}
|
|
|
|
// Check if blocked
|
|
blocked, blockers, err := store.IsBlocked(ctx, child.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to check if blocked: %v", err)
|
|
}
|
|
if !blocked {
|
|
t.Error("expected child to be blocked")
|
|
}
|
|
if len(blockers) != 1 || blockers[0] != parent.ID {
|
|
t.Errorf("expected blocker %s, got %v", parent.ID, blockers)
|
|
}
|
|
|
|
// Remove dependency
|
|
if err := store.RemoveDependency(ctx, child.ID, parent.ID, "tester"); err != nil {
|
|
t.Fatalf("failed to remove dependency: %v", err)
|
|
}
|
|
|
|
// Verify removal
|
|
deps, err = store.GetDependencies(ctx, child.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get dependencies after removal: %v", err)
|
|
}
|
|
if len(deps) != 0 {
|
|
t.Errorf("expected 0 dependencies after removal, got %d", len(deps))
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreSearch(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create multiple issues
|
|
issues := []*types.Issue{
|
|
{
|
|
ID: "test-search-1",
|
|
Title: "Search test one",
|
|
Description: "First issue description",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
},
|
|
{
|
|
ID: "test-search-2",
|
|
Title: "Search test two",
|
|
Description: "Second issue description",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeBug,
|
|
},
|
|
{
|
|
ID: "test-search-3",
|
|
Title: "Third Issue",
|
|
Description: "Different content",
|
|
Status: types.StatusClosed,
|
|
Priority: 3,
|
|
IssueType: types.TypeTask,
|
|
},
|
|
}
|
|
|
|
for _, issue := range issues {
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", issue.ID, err)
|
|
}
|
|
}
|
|
|
|
// Search by query
|
|
results, err := store.SearchIssues(ctx, "Search test", types.IssueFilter{})
|
|
if err != nil {
|
|
t.Fatalf("failed to search issues: %v", err)
|
|
}
|
|
if len(results) != 2 {
|
|
t.Errorf("expected 2 results for 'Search test', got %d", len(results))
|
|
}
|
|
|
|
// Search with status filter
|
|
openStatus := types.StatusOpen
|
|
results, err = store.SearchIssues(ctx, "", types.IssueFilter{Status: &openStatus})
|
|
if err != nil {
|
|
t.Fatalf("failed to search with status filter: %v", err)
|
|
}
|
|
if len(results) != 2 {
|
|
t.Errorf("expected 2 open issues, got %d", len(results))
|
|
}
|
|
|
|
// Search by issue type
|
|
bugType := types.TypeBug
|
|
results, err = store.SearchIssues(ctx, "", types.IssueFilter{IssueType: &bugType})
|
|
if err != nil {
|
|
t.Fatalf("failed to search by type: %v", err)
|
|
}
|
|
if len(results) != 1 {
|
|
t.Errorf("expected 1 bug, got %d", len(results))
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreCreateIssues(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create multiple issues in batch
|
|
issues := []*types.Issue{
|
|
{
|
|
ID: "test-batch-1",
|
|
Title: "Batch Issue 1",
|
|
Description: "First batch issue",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
},
|
|
{
|
|
ID: "test-batch-2",
|
|
Title: "Batch Issue 2",
|
|
Description: "Second batch issue",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
},
|
|
}
|
|
|
|
if err := store.CreateIssues(ctx, issues, "tester"); err != nil {
|
|
t.Fatalf("failed to create issues: %v", err)
|
|
}
|
|
|
|
// Verify all issues were created
|
|
for _, issue := range issues {
|
|
retrieved, err := store.GetIssue(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get issue %s: %v", issue.ID, err)
|
|
}
|
|
if retrieved == nil {
|
|
t.Errorf("expected to retrieve issue %s", issue.ID)
|
|
}
|
|
if retrieved.Title != issue.Title {
|
|
t.Errorf("expected title %q, got %q", issue.Title, retrieved.Title)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreComments(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue
|
|
issue := &types.Issue{
|
|
ID: "test-comment-issue",
|
|
Title: "Issue with Comments",
|
|
Description: "Test comments",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Add comments
|
|
comment1, err := store.AddIssueComment(ctx, issue.ID, "user1", "First comment")
|
|
if err != nil {
|
|
t.Fatalf("failed to add first comment: %v", err)
|
|
}
|
|
if comment1.ID == "" {
|
|
t.Error("expected comment ID to be generated")
|
|
}
|
|
|
|
_, err = store.AddIssueComment(ctx, issue.ID, "user2", "Second comment")
|
|
if err != nil {
|
|
t.Fatalf("failed to add second comment: %v", err)
|
|
}
|
|
|
|
// Get comments
|
|
comments, err := store.GetIssueComments(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("failed to get comments: %v", err)
|
|
}
|
|
if len(comments) != 2 {
|
|
t.Errorf("expected 2 comments, got %d", len(comments))
|
|
}
|
|
if comments[0].Text != "First comment" {
|
|
t.Errorf("expected 'First comment', got %q", comments[0].Text)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreEvents(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue (this creates a creation event)
|
|
issue := &types.Issue{
|
|
ID: "test-event-issue",
|
|
Title: "Issue with Events",
|
|
Description: "Test events",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Add a comment event
|
|
if err := store.AddComment(ctx, issue.ID, "user1", "A comment"); err != nil {
|
|
t.Fatalf("failed to add comment: %v", err)
|
|
}
|
|
|
|
// Get events
|
|
events, err := store.GetEvents(ctx, issue.ID, 10)
|
|
if err != nil {
|
|
t.Fatalf("failed to get events: %v", err)
|
|
}
|
|
if len(events) < 2 {
|
|
t.Errorf("expected at least 2 events, got %d", len(events))
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreDeleteIssue(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an issue
|
|
issue := &types.Issue{
|
|
ID: "test-delete-issue",
|
|
Title: "Issue to Delete",
|
|
Description: "Will be deleted",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
|
|
// Verify it exists
|
|
retrieved, err := store.GetIssue(ctx, issue.ID)
|
|
if err != nil || retrieved == nil {
|
|
t.Fatalf("issue should exist before delete")
|
|
}
|
|
|
|
// Delete the issue
|
|
if err := store.DeleteIssue(ctx, issue.ID); err != nil {
|
|
t.Fatalf("failed to delete issue: %v", err)
|
|
}
|
|
|
|
// Verify it's gone
|
|
_, err = store.GetIssue(ctx, issue.ID)
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected ErrNotFound after delete, got: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesBatchPerformance verifies that batch deletion works correctly
|
|
// with a large number of issues and chain dependencies. This exercises the batched
|
|
// IN-clause query paths that prevent N+1 hangs on embedded Dolt (steveyegge/beads#1692).
|
|
func TestDeleteIssuesBatchPerformance(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
const issueCount = 25
|
|
|
|
// Create issues with chain dependencies: issue-1 <- issue-2 <- ... <- issue-N
|
|
for i := 1; i <= issueCount; i++ {
|
|
issue := &types.Issue{
|
|
ID: fmt.Sprintf("batch-del-%d", i),
|
|
Title: fmt.Sprintf("Batch Delete Issue %d", i),
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %d: %v", i, err)
|
|
}
|
|
if i > 1 {
|
|
dep := &types.Dependency{
|
|
IssueID: fmt.Sprintf("batch-del-%d", i),
|
|
DependsOnID: fmt.Sprintf("batch-del-%d", i-1),
|
|
Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dependency %d: %v", i, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Cascade delete from the root — should delete all 100 issues
|
|
result, err := store.DeleteIssues(ctx, []string{"batch-del-1"}, true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("batch cascade delete failed: %v", err)
|
|
}
|
|
|
|
if result.DeletedCount != issueCount {
|
|
t.Errorf("expected %d deleted, got %d", issueCount, result.DeletedCount)
|
|
}
|
|
if result.DependenciesCount < issueCount-1 {
|
|
t.Errorf("expected at least %d dependencies, got %d", issueCount-1, result.DependenciesCount)
|
|
}
|
|
|
|
// Verify all issues are actually gone
|
|
for i := 1; i <= issueCount; i++ {
|
|
_, err := store.GetIssue(ctx, fmt.Sprintf("batch-del-%d", i))
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected ErrNotFound for issue %d after delete, got: %v", i, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesEmptyInput verifies that DeleteIssues handles empty input gracefully.
|
|
func TestDeleteIssuesEmptyInput(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
result, err := store.DeleteIssues(ctx, []string{}, false, false, false)
|
|
if err != nil {
|
|
t.Fatalf("expected no error for empty input, got: %v", err)
|
|
}
|
|
if result == nil {
|
|
t.Fatal("expected non-nil result for empty input")
|
|
}
|
|
if result.DeletedCount != 0 {
|
|
t.Errorf("expected 0 deleted, got %d", result.DeletedCount)
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesNonCascadeWithExternalDeps verifies that deleting an issue with
|
|
// external dependents (without --cascade or --force) returns an error identifying
|
|
// the blocking issue and does not delete anything.
|
|
func TestDeleteIssuesNonCascadeWithExternalDeps(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create parent issue and a dependent that will NOT be in the deletion set
|
|
parent := &types.Issue{
|
|
ID: "nc-parent", Title: "Parent", Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
child := &types.Issue{
|
|
ID: "nc-child", Title: "Child", Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
for _, iss := range []*types.Issue{parent, child} {
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", iss.ID, err)
|
|
}
|
|
}
|
|
dep := &types.Dependency{
|
|
IssueID: "nc-child", DependsOnID: "nc-parent", Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dependency: %v", err)
|
|
}
|
|
|
|
// Try to delete parent only (child depends on it, not in deletion set)
|
|
result, err := store.DeleteIssues(ctx, []string{"nc-parent"}, false, false, false)
|
|
if err == nil {
|
|
t.Fatal("expected error when deleting issue with external dependents")
|
|
}
|
|
if result == nil {
|
|
t.Fatal("expected non-nil result even on error (for OrphanedIssues inspection)")
|
|
}
|
|
if len(result.OrphanedIssues) == 0 {
|
|
t.Error("expected OrphanedIssues to be populated on error")
|
|
}
|
|
|
|
// Verify error message identifies the issue
|
|
errMsg := err.Error()
|
|
if !strings.Contains(errMsg, "nc-parent") {
|
|
t.Errorf("error should identify issue nc-parent, got: %s", errMsg)
|
|
}
|
|
if !strings.Contains(errMsg, "dependents not in deletion set") {
|
|
t.Errorf("error should mention external dependents, got: %s", errMsg)
|
|
}
|
|
|
|
// Verify nothing was deleted
|
|
got, err := store.GetIssue(ctx, "nc-parent")
|
|
if err != nil {
|
|
t.Fatalf("failed to get issue after failed delete: %v", err)
|
|
}
|
|
if got == nil {
|
|
t.Error("parent issue should still exist after failed non-cascade delete")
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesDryRun verifies that dry-run mode computes stats without deleting.
|
|
func TestDeleteIssuesDryRun(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create 3 issues with chain deps and a label
|
|
for i := 1; i <= 3; i++ {
|
|
iss := &types.Issue{
|
|
ID: fmt.Sprintf("dry-%d", i), Title: fmt.Sprintf("Dry %d", i),
|
|
Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
if i > 1 {
|
|
dep := &types.Dependency{
|
|
IssueID: fmt.Sprintf("dry-%d", i), DependsOnID: fmt.Sprintf("dry-%d", i-1),
|
|
Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dep: %v", err)
|
|
}
|
|
}
|
|
}
|
|
if err := store.AddLabel(ctx, "dry-1", "test-label", "tester"); err != nil {
|
|
t.Fatalf("failed to add label: %v", err)
|
|
}
|
|
|
|
// Dry-run cascade delete from root
|
|
result, err := store.DeleteIssues(ctx, []string{"dry-1"}, true, false, true)
|
|
if err != nil {
|
|
t.Fatalf("dry-run failed: %v", err)
|
|
}
|
|
if result.DeletedCount != 3 {
|
|
t.Errorf("dry-run: expected 3 deleted count, got %d", result.DeletedCount)
|
|
}
|
|
if result.DependenciesCount < 2 {
|
|
t.Errorf("dry-run: expected at least 2 deps, got %d", result.DependenciesCount)
|
|
}
|
|
if result.LabelsCount < 1 {
|
|
t.Errorf("dry-run: expected at least 1 label, got %d", result.LabelsCount)
|
|
}
|
|
|
|
// Verify nothing was actually deleted
|
|
for i := 1; i <= 3; i++ {
|
|
got, err := store.GetIssue(ctx, fmt.Sprintf("dry-%d", i))
|
|
if err != nil {
|
|
t.Fatalf("failed to get issue after dry-run: %v", err)
|
|
}
|
|
if got == nil {
|
|
t.Errorf("issue dry-%d should still exist after dry-run", i)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesForceWithOrphans verifies that force mode correctly identifies
|
|
// and reports orphaned external dependents without blocking deletion.
|
|
func TestDeleteIssuesForceWithOrphans(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create: parent, child1 (in deletion set), child2 (external dependent)
|
|
for _, id := range []string{"f-parent", "f-child1", "f-child2"} {
|
|
iss := &types.Issue{
|
|
ID: id, Title: id, Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create %s: %v", id, err)
|
|
}
|
|
}
|
|
// child1 and child2 both depend on parent
|
|
for _, childID := range []string{"f-child1", "f-child2"} {
|
|
dep := &types.Dependency{
|
|
IssueID: childID, DependsOnID: "f-parent", Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dep for %s: %v", childID, err)
|
|
}
|
|
}
|
|
|
|
// Force-delete parent and child1 (child2 is external dependent)
|
|
result, err := store.DeleteIssues(ctx, []string{"f-parent", "f-child1"}, false, true, false)
|
|
if err != nil {
|
|
t.Fatalf("force delete failed: %v", err)
|
|
}
|
|
if len(result.OrphanedIssues) == 0 {
|
|
t.Error("expected OrphanedIssues to contain f-child2")
|
|
}
|
|
foundOrphan := false
|
|
for _, id := range result.OrphanedIssues {
|
|
if id == "f-child2" {
|
|
foundOrphan = true
|
|
}
|
|
}
|
|
if !foundOrphan {
|
|
t.Errorf("expected f-child2 in OrphanedIssues, got: %v", result.OrphanedIssues)
|
|
}
|
|
|
|
// Verify parent and child1 are deleted
|
|
for _, id := range []string{"f-parent", "f-child1"} {
|
|
_, err := store.GetIssue(ctx, id)
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected ErrNotFound for %s, got: %v", id, err)
|
|
}
|
|
}
|
|
// child2 should still exist
|
|
got, err := store.GetIssue(ctx, "f-child2")
|
|
if err != nil {
|
|
t.Fatalf("failed to get f-child2: %v", err)
|
|
}
|
|
if got == nil {
|
|
t.Error("f-child2 should still exist (orphaned, not deleted)")
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesBatchBoundary exercises the exact batch boundary (deleteBatchSize=50):
|
|
// 50 issues (one full batch) and 51 issues (one full batch + one remainder).
|
|
func TestDeleteIssuesBatchBoundary(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
for _, count := range []int{deleteBatchSize, deleteBatchSize + 1} {
|
|
t.Run(fmt.Sprintf("count_%d", count), func(t *testing.T) {
|
|
ids := make([]string, count)
|
|
for i := 0; i < count; i++ {
|
|
id := fmt.Sprintf("bb-%d-%d", count, i)
|
|
ids[i] = id
|
|
iss := &types.Issue{
|
|
ID: id, Title: id, Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", id, err)
|
|
}
|
|
if i > 0 {
|
|
dep := &types.Dependency{
|
|
IssueID: id, DependsOnID: ids[i-1], Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dep: %v", err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// Cascade delete from root
|
|
result, err := store.DeleteIssues(ctx, []string{ids[0]}, true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("cascade delete failed for count %d: %v", count, err)
|
|
}
|
|
if result.DeletedCount != count {
|
|
t.Errorf("expected %d deleted, got %d", count, result.DeletedCount)
|
|
}
|
|
if result.DependenciesCount < count-1 {
|
|
t.Errorf("expected at least %d deps, got %d", count-1, result.DependenciesCount)
|
|
}
|
|
|
|
// Verify all gone
|
|
for _, id := range ids {
|
|
_, err := store.GetIssue(ctx, id)
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected ErrNotFound for %s, got: %v", id, err)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesCircularDeps verifies that cascade delete handles circular
|
|
// dependencies without infinite loops (the BFS visited set prevents revisiting).
|
|
func TestDeleteIssuesCircularDeps(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create A -> B -> C -> A (circular)
|
|
for _, id := range []string{"circ-a", "circ-b", "circ-c"} {
|
|
iss := &types.Issue{
|
|
ID: id, Title: id, Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create %s: %v", id, err)
|
|
}
|
|
}
|
|
// B depends on A, C depends on B (these two are acyclic, use normal API)
|
|
for _, d := range []struct{ from, to string }{
|
|
{"circ-b", "circ-a"},
|
|
{"circ-c", "circ-b"},
|
|
} {
|
|
dep := &types.Dependency{
|
|
IssueID: d.from, DependsOnID: d.to, Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dep %s->%s: %v", d.from, d.to, err)
|
|
}
|
|
}
|
|
// A depends on C completes the cycle. Insert directly via SQL to bypass
|
|
// the cycle detection in AddDependency -- this test exercises DeleteIssues'
|
|
// ability to handle cycles that may exist in the database, not AddDependency.
|
|
if _, err := store.execContext(ctx, `
|
|
INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_at, created_by, metadata)
|
|
VALUES (UUID(), ?, ?, 'blocks', NOW(), 'tester', '{}')
|
|
`, "circ-a", "circ-c"); err != nil {
|
|
t.Fatalf("failed to insert cycle-completing dep circ-a->circ-c: %v", err)
|
|
}
|
|
|
|
// Cascade delete from A should find B and C via the cycle
|
|
result, err := store.DeleteIssues(ctx, []string{"circ-a"}, true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("cascade delete with circular deps failed: %v", err)
|
|
}
|
|
if result.DeletedCount != 3 {
|
|
t.Errorf("expected 3 deleted (all in cycle), got %d", result.DeletedCount)
|
|
}
|
|
|
|
// Verify all deleted
|
|
for _, id := range []string{"circ-a", "circ-b", "circ-c"} {
|
|
_, err := store.GetIssue(ctx, id)
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected ErrNotFound for %s, got: %v", id, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesDiamondDeps verifies that cascade delete handles diamond
|
|
// dependency graphs correctly (each issue discovered only once).
|
|
func TestDeleteIssuesDiamondDeps(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Diamond: root <- left, root <- right, left <- bottom, right <- bottom
|
|
for _, id := range []string{"dia-root", "dia-left", "dia-right", "dia-bottom"} {
|
|
iss := &types.Issue{
|
|
ID: id, Title: id, Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create %s: %v", id, err)
|
|
}
|
|
}
|
|
deps := []struct{ from, to string }{
|
|
{"dia-left", "dia-root"},
|
|
{"dia-right", "dia-root"},
|
|
{"dia-bottom", "dia-left"},
|
|
{"dia-bottom", "dia-right"},
|
|
}
|
|
for _, d := range deps {
|
|
dep := &types.Dependency{
|
|
IssueID: d.from, DependsOnID: d.to, Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dep: %v", err)
|
|
}
|
|
}
|
|
|
|
// Cascade delete from root should find all 4
|
|
result, err := store.DeleteIssues(ctx, []string{"dia-root"}, true, false, false)
|
|
if err != nil {
|
|
t.Fatalf("diamond cascade delete failed: %v", err)
|
|
}
|
|
if result.DeletedCount != 4 {
|
|
t.Errorf("expected 4 deleted, got %d", result.DeletedCount)
|
|
}
|
|
|
|
for _, id := range []string{"dia-root", "dia-left", "dia-right", "dia-bottom"} {
|
|
_, err := store.GetIssue(ctx, id)
|
|
if !errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected ErrNotFound for %s, got: %v", id, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestDeleteIssuesDepsCountAccuracy verifies that the dependency count does not
|
|
// double-count rows that span across batches. Uses a cross-batch dependency where
|
|
// issue_id is in one batch and depends_on_id is in another.
|
|
func TestDeleteIssuesDepsCountAccuracy(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create 2 issues with 1 dependency between them
|
|
for _, id := range []string{"dc-a", "dc-b"} {
|
|
iss := &types.Issue{
|
|
ID: id, Title: id, Status: types.StatusOpen,
|
|
Priority: 1, IssueType: types.TypeTask,
|
|
}
|
|
if err := store.CreateIssue(ctx, iss, "tester"); err != nil {
|
|
t.Fatalf("failed to create %s: %v", id, err)
|
|
}
|
|
}
|
|
dep := &types.Dependency{
|
|
IssueID: "dc-b", DependsOnID: "dc-a", Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dep: %v", err)
|
|
}
|
|
|
|
// Dry-run to check stats only
|
|
result, err := store.DeleteIssues(ctx, []string{"dc-a", "dc-b"}, false, true, true)
|
|
if err != nil {
|
|
t.Fatalf("dry-run failed: %v", err)
|
|
}
|
|
// There is exactly 1 dependency row: (dc-b, dc-a). It should be counted once.
|
|
if result.DependenciesCount != 1 {
|
|
t.Errorf("expected exactly 1 dependency, got %d (possible double-counting)", result.DependenciesCount)
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreStatistics(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create some issues
|
|
issues := []*types.Issue{
|
|
{ID: "test-stat-1", Title: "Open 1", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeTask},
|
|
{ID: "test-stat-2", Title: "Open 2", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
|
|
{ID: "test-stat-3", Title: "Closed", Status: types.StatusClosed, Priority: 1, IssueType: types.TypeTask},
|
|
}
|
|
|
|
for _, issue := range issues {
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue: %v", err)
|
|
}
|
|
}
|
|
|
|
// Get statistics
|
|
stats, err := store.GetStatistics(ctx)
|
|
if err != nil {
|
|
t.Fatalf("failed to get statistics: %v", err)
|
|
}
|
|
|
|
if stats.OpenIssues < 2 {
|
|
t.Errorf("expected at least 2 open issues, got %d", stats.OpenIssues)
|
|
}
|
|
if stats.ClosedIssues < 1 {
|
|
t.Errorf("expected at least 1 closed issue, got %d", stats.ClosedIssues)
|
|
}
|
|
}
|
|
|
|
// Test SQL injection protection
|
|
|
|
func TestValidateRef(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
ref string
|
|
wantErr bool
|
|
}{
|
|
{"valid hash", "abc123def456", false},
|
|
{"valid branch", "main", false},
|
|
{"valid with underscore", "feature_branch", false},
|
|
{"valid with dash", "feature-branch", false},
|
|
{"valid with dot", "release.v2", false},
|
|
{"valid with slash", "release/v2.0", false},
|
|
{"valid nested slash", "feature/auth/login", false},
|
|
{"valid dot and slash", "feature/auth.flow", false},
|
|
{"empty", "", true},
|
|
{"too long", string(make([]byte, 200)), true},
|
|
{"with SQL injection", "main'; DROP TABLE issues; --", true},
|
|
{"with quotes", "main'test", true},
|
|
{"with semicolon", "main;test", true},
|
|
{"with space", "main test", true},
|
|
{"with backtick", "main`test", true},
|
|
{"with backslash", `main\test`, true},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
err := validateRef(tt.ref)
|
|
if (err != nil) != tt.wantErr {
|
|
t.Errorf("validateRef(%q) error = %v, wantErr %v", tt.ref, err, tt.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestValidateTableName(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
tableName string
|
|
wantErr bool
|
|
}{
|
|
{"valid table", "issues", false},
|
|
{"valid with underscore", "child_counters", false},
|
|
{"valid with numbers", "table123", false},
|
|
{"empty", "", true},
|
|
{"too long", string(make([]byte, 100)), true},
|
|
{"starts with number", "123table", true},
|
|
{"with SQL injection", "issues'; DROP TABLE issues; --", true},
|
|
{"with space", "my table", true},
|
|
{"with dash", "my-table", true},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
err := validateTableName(tt.tableName)
|
|
if (err != nil) != tt.wantErr {
|
|
t.Errorf("validateTableName(%q) error = %v, wantErr %v", tt.tableName, err, tt.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestValidateDatabaseName(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
dbName string
|
|
wantErr bool
|
|
}{
|
|
{"valid simple", "beads", false},
|
|
{"valid with underscore", "beads_test", false},
|
|
{"valid with hyphen", "beads-test", false},
|
|
{"valid with numbers", "beads123", false},
|
|
{"empty", "", true},
|
|
{"too long", string(make([]byte, 100)), true},
|
|
{"starts with number", "123beads", true},
|
|
{"with backtick injection", "beads`; DROP DATABASE beads; --", true},
|
|
{"with space", "my database", true},
|
|
{"with semicolon", "beads;evil", true},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
err := ValidateDatabaseName(tt.dbName)
|
|
if (err != nil) != tt.wantErr {
|
|
t.Errorf("ValidateDatabaseName(%q) error = %v, wantErr %v", tt.dbName, err, tt.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestIsTestDatabaseName(t *testing.T) {
|
|
tests := []struct {
|
|
name string
|
|
dbName string
|
|
want bool
|
|
}{
|
|
{"exact test db", "beads_test", true},
|
|
{"test db with suffix", "beads_test_123", true},
|
|
{"testdb prefix", "testdb_foo", true},
|
|
{"doctest prefix", "doctest_bar", true},
|
|
{"doctortest prefix", "doctortest_baz", true},
|
|
{"beads_pt prefix", "beads_pt_xyz", true},
|
|
{"beads_vr prefix", "beads_vr_abc", true},
|
|
{"production db", "beads", false},
|
|
{"project prefix ta", "beads_ta", false},
|
|
{"project prefix tabula", "beads_tabula", false},
|
|
{"project prefix tr", "beads_tr", false},
|
|
{"project prefix tools", "beads_tools", false},
|
|
{"project prefix vulcan", "beads_vulcan", false},
|
|
{"unrelated name", "mydb", false},
|
|
}
|
|
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
got := isTestDatabaseName(tt.dbName)
|
|
if got != tt.want {
|
|
t.Errorf("isTestDatabaseName(%q) = %v, want %v", tt.dbName, got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreGetReadyWork(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create issues: one blocked, one ready
|
|
blocker := &types.Issue{
|
|
ID: "test-blocker",
|
|
Title: "Blocker",
|
|
Description: "Blocks another issue",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
blocked := &types.Issue{
|
|
ID: "test-blocked",
|
|
Title: "Blocked",
|
|
Description: "Is blocked",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
ready := &types.Issue{
|
|
ID: "test-ready",
|
|
Title: "Ready",
|
|
Description: "Is ready",
|
|
Status: types.StatusOpen,
|
|
Priority: 3,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
for _, issue := range []*types.Issue{blocker, blocked, ready} {
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", issue.ID, err)
|
|
}
|
|
}
|
|
|
|
// Add blocking dependency
|
|
dep := &types.Dependency{
|
|
IssueID: blocked.ID,
|
|
DependsOnID: blocker.ID,
|
|
Type: types.DepBlocks,
|
|
}
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add dependency: %v", err)
|
|
}
|
|
|
|
// Get ready work
|
|
readyWork, err := store.GetReadyWork(ctx, types.WorkFilter{})
|
|
if err != nil {
|
|
t.Fatalf("failed to get ready work: %v", err)
|
|
}
|
|
|
|
// Should include blocker and ready, but not blocked
|
|
foundBlocker := false
|
|
foundBlocked := false
|
|
foundReady := false
|
|
for _, issue := range readyWork {
|
|
switch issue.ID {
|
|
case blocker.ID:
|
|
foundBlocker = true
|
|
case blocked.ID:
|
|
foundBlocked = true
|
|
case ready.ID:
|
|
foundReady = true
|
|
}
|
|
}
|
|
|
|
if !foundBlocker {
|
|
t.Error("expected blocker to be in ready work")
|
|
}
|
|
if foundBlocked {
|
|
t.Error("expected blocked issue to NOT be in ready work")
|
|
}
|
|
if !foundReady {
|
|
t.Error("expected ready issue to be in ready work")
|
|
}
|
|
|
|
// Test ephemeral filtering: create an ephemeral issue
|
|
ephemeral := &types.Issue{
|
|
ID: "test-ephemeral",
|
|
Title: "Ephemeral Task",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, ephemeral, "tester"); err != nil {
|
|
t.Fatalf("failed to create ephemeral issue: %v", err)
|
|
}
|
|
|
|
// Default filter should exclude ephemeral
|
|
readyDefault, err := store.GetReadyWork(ctx, types.WorkFilter{})
|
|
if err != nil {
|
|
t.Fatalf("failed to get ready work (default): %v", err)
|
|
}
|
|
for _, issue := range readyDefault {
|
|
if issue.ID == ephemeral.ID {
|
|
t.Error("expected ephemeral issue to be excluded by default")
|
|
}
|
|
}
|
|
|
|
// IncludeEphemeral should include it
|
|
readyWithEph, err := store.GetReadyWork(ctx, types.WorkFilter{IncludeEphemeral: true})
|
|
if err != nil {
|
|
t.Fatalf("failed to get ready work (include-ephemeral): %v", err)
|
|
}
|
|
foundEphemeral := false
|
|
for _, issue := range readyWithEph {
|
|
if issue.ID == ephemeral.ID {
|
|
foundEphemeral = true
|
|
}
|
|
}
|
|
if !foundEphemeral {
|
|
t.Error("expected ephemeral issue to be included when IncludeEphemeral=true")
|
|
}
|
|
}
|
|
|
|
func TestDoltStoreGetReadyWorkWaitsForChildrenOfSpawner(t *testing.T) {
|
|
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
implement := &types.Issue{
|
|
ID: "test-implement",
|
|
Title: "Implement",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
review := &types.Issue{
|
|
ID: "test-review",
|
|
Title: "Review",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
otherSpawner := &types.Issue{
|
|
ID: "test-other-spawner",
|
|
Title: "Other spawner",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
implChild := &types.Issue{
|
|
ID: "test-implement.1",
|
|
Title: "Implement child",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
otherChild := &types.Issue{
|
|
ID: "test-other-spawner.1",
|
|
Title: "Unrelated child",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
}
|
|
|
|
for _, issue := range []*types.Issue{implement, review, otherSpawner, implChild, otherChild} {
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", issue.ID, err)
|
|
}
|
|
}
|
|
|
|
for _, dep := range []*types.Dependency{
|
|
{IssueID: implChild.ID, DependsOnID: implement.ID, Type: types.DepParentChild},
|
|
{IssueID: otherChild.ID, DependsOnID: otherSpawner.ID, Type: types.DepParentChild},
|
|
} {
|
|
if err := store.AddDependency(ctx, dep, "tester"); err != nil {
|
|
t.Fatalf("failed to add parent-child dependency %s -> %s: %v", dep.IssueID, dep.DependsOnID, err)
|
|
}
|
|
}
|
|
|
|
metaJSON, err := json.Marshal(types.WaitsForMeta{Gate: types.WaitsForAllChildren})
|
|
if err != nil {
|
|
t.Fatalf("failed to marshal waits-for metadata: %v", err)
|
|
}
|
|
if err := store.AddDependency(ctx, &types.Dependency{
|
|
IssueID: review.ID,
|
|
DependsOnID: implement.ID,
|
|
Type: types.DepWaitsFor,
|
|
Metadata: string(metaJSON),
|
|
}, "tester"); err != nil {
|
|
t.Fatalf("failed to add waits-for dependency: %v", err)
|
|
}
|
|
|
|
hasReadyID := func(issues []*types.Issue, id string) bool {
|
|
for _, issue := range issues {
|
|
if issue.ID == id {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
t.Run("blocked-before-child-close", func(t *testing.T) {
|
|
readyBefore, err := store.GetReadyWork(ctx, types.WorkFilter{})
|
|
if err != nil {
|
|
t.Fatalf("failed to get ready work (before close): %v", err)
|
|
}
|
|
if hasReadyID(readyBefore, review.ID) {
|
|
t.Fatalf("expected %s to be blocked by open child of %s", review.ID, implement.ID)
|
|
}
|
|
})
|
|
|
|
t.Run("ready-after-child-close", func(t *testing.T) {
|
|
if err := store.CloseIssue(ctx, implChild.ID, "done", "tester", "session-test"); err != nil {
|
|
t.Fatalf("failed to close child issue: %v", err)
|
|
}
|
|
|
|
readyAfter, err := store.GetReadyWork(ctx, types.WorkFilter{})
|
|
if err != nil {
|
|
t.Fatalf("failed to get ready work (after close): %v", err)
|
|
}
|
|
if !hasReadyID(readyAfter, review.ID) {
|
|
t.Fatalf("expected %s to become ready after children of %s close", review.ID, implement.ID)
|
|
}
|
|
})
|
|
}
|
|
|
|
// TestCloseWithTimeout tests the close timeout helper function
|
|
func TestCloseWithTimeout(t *testing.T) {
|
|
// Test 1: Fast close succeeds
|
|
t.Run("fast close succeeds", func(t *testing.T) {
|
|
err := doltutil.CloseWithTimeout("test", func() error {
|
|
return nil
|
|
})
|
|
if err != nil {
|
|
t.Errorf("expected no error, got: %v", err)
|
|
}
|
|
})
|
|
|
|
// Test 2: Fast close with error returns error
|
|
t.Run("fast close with error", func(t *testing.T) {
|
|
expectedErr := context.Canceled
|
|
err := doltutil.CloseWithTimeout("test", func() error {
|
|
return expectedErr
|
|
})
|
|
if err != expectedErr {
|
|
t.Errorf("expected %v, got: %v", expectedErr, err)
|
|
}
|
|
})
|
|
|
|
// Test 3: Slow close times out (use shorter timeout for test)
|
|
t.Run("slow close times out", func(t *testing.T) {
|
|
// Save original timeout and restore after test
|
|
originalTimeout := doltutil.CloseTimeout
|
|
// Note: CloseTimeout is a const, so we can't actually change it
|
|
// This test verifies the timeout mechanism works conceptually
|
|
// In practice, the 5s timeout is reasonable for production use
|
|
|
|
// This test would take 5+ seconds with the real timeout,
|
|
// so we just verify the function signature works correctly
|
|
start := time.Now()
|
|
err := doltutil.CloseWithTimeout("test", func() error {
|
|
// Return immediately for this test
|
|
return nil
|
|
})
|
|
elapsed := time.Since(start)
|
|
|
|
if err != nil {
|
|
t.Errorf("expected no error for fast close, got: %v", err)
|
|
}
|
|
if elapsed > time.Second {
|
|
t.Errorf("fast close took too long: %v", elapsed)
|
|
}
|
|
_ = originalTimeout // silence unused warning
|
|
})
|
|
}
|
|
|
|
// TestGetReadyWorkSortPolicy verifies that GetReadyWork respects the SortPolicy
|
|
// field and that result ordering is preserved through the scanIssueIDs pipeline.
|
|
func TestGetReadyWorkSortPolicy(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
now := time.Now().UTC()
|
|
|
|
// Create issues with distinct priorities and creation times.
|
|
// "old-p3" is 3 days old (outside the 48h hybrid window).
|
|
// The "recent-*" issues are recent (within 48h).
|
|
issues := []*types.Issue{
|
|
{
|
|
ID: "test-old-p3",
|
|
Title: "Old P3",
|
|
Status: types.StatusOpen,
|
|
Priority: 3,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-72 * time.Hour), // 3 days ago
|
|
},
|
|
{
|
|
ID: "test-recent-p1-older",
|
|
Title: "Recent P1 Older",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-90 * time.Minute), // 90 min ago
|
|
},
|
|
{
|
|
ID: "test-recent-p2",
|
|
Title: "Recent P2",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-1 * time.Hour), // 1 hour ago
|
|
},
|
|
{
|
|
ID: "test-recent-p1",
|
|
Title: "Recent P1",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-30 * time.Minute), // 30 min ago
|
|
},
|
|
}
|
|
|
|
for _, issue := range issues {
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", issue.ID, err)
|
|
}
|
|
}
|
|
|
|
t.Run("SortPolicyPriority", func(t *testing.T) {
|
|
result, err := store.GetReadyWork(ctx, types.WorkFilter{
|
|
SortPolicy: types.SortPolicyPriority,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("GetReadyWork failed: %v", err)
|
|
}
|
|
|
|
ids := issueIDs(result)
|
|
// Priority order: P1 < P2 < P3, FIFO within the same priority.
|
|
assertOrder(t, ids, "test-recent-p1-older", "test-recent-p1", "test-recent-p2", "test-old-p3")
|
|
})
|
|
|
|
t.Run("SortPolicyOldest", func(t *testing.T) {
|
|
result, err := store.GetReadyWork(ctx, types.WorkFilter{
|
|
SortPolicy: types.SortPolicyOldest,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("GetReadyWork failed: %v", err)
|
|
}
|
|
|
|
ids := issueIDs(result)
|
|
// Oldest first, regardless of priority.
|
|
assertOrder(t, ids, "test-old-p3", "test-recent-p1-older", "test-recent-p2", "test-recent-p1")
|
|
})
|
|
|
|
t.Run("SortPolicyHybrid", func(t *testing.T) {
|
|
result, err := store.GetReadyWork(ctx, types.WorkFilter{
|
|
SortPolicy: types.SortPolicyHybrid,
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("GetReadyWork failed: %v", err)
|
|
}
|
|
|
|
ids := issueIDs(result)
|
|
// Hybrid: recent bucket (P1 before P2) first, then old bucket
|
|
assertOrder(t, ids, "test-recent-p1-older", "test-recent-p1", "test-recent-p2", "test-old-p3")
|
|
})
|
|
|
|
t.Run("DefaultSortIsHybrid", func(t *testing.T) {
|
|
result, err := store.GetReadyWork(ctx, types.WorkFilter{})
|
|
if err != nil {
|
|
t.Fatalf("GetReadyWork failed: %v", err)
|
|
}
|
|
|
|
ids := issueIDs(result)
|
|
// Default (empty string) behaves like hybrid
|
|
assertOrder(t, ids, "test-recent-p1-older", "test-recent-p1", "test-recent-p2", "test-old-p3")
|
|
})
|
|
}
|
|
|
|
func TestDoltStoreClaimReadyIssuePriorityFIFO(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
now := time.Now().UTC()
|
|
issues := []*types.Issue{
|
|
{
|
|
ID: "claim-ready-first",
|
|
Title: "First task",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-2 * time.Hour),
|
|
},
|
|
{
|
|
ID: "claim-ready-second",
|
|
Title: "Second task",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-1 * time.Hour),
|
|
},
|
|
{
|
|
ID: "claim-ready-third",
|
|
Title: "Third task",
|
|
Status: types.StatusOpen,
|
|
Priority: 1,
|
|
IssueType: types.TypeTask,
|
|
CreatedAt: now.Add(-30 * time.Minute),
|
|
},
|
|
}
|
|
for _, issue := range issues {
|
|
if err := store.CreateIssue(ctx, issue, "tester"); err != nil {
|
|
t.Fatalf("failed to create issue %s: %v", issue.ID, err)
|
|
}
|
|
}
|
|
|
|
claimed, err := store.ClaimReadyIssue(ctx, types.WorkFilter{
|
|
SortPolicy: types.SortPolicyPriority,
|
|
}, "agent")
|
|
if err != nil {
|
|
t.Fatalf("ClaimReadyIssue failed: %v", err)
|
|
}
|
|
if claimed == nil {
|
|
t.Fatal("ClaimReadyIssue returned nil")
|
|
}
|
|
if claimed.ID != "claim-ready-first" {
|
|
t.Fatalf("ClaimReadyIssue claimed %s, want claim-ready-first", claimed.ID)
|
|
}
|
|
}
|
|
|
|
// issueIDs extracts IDs from a slice of issues.
|
|
func issueIDs(issues []*types.Issue) []string {
|
|
ids := make([]string, len(issues))
|
|
for i, issue := range issues {
|
|
ids[i] = issue.ID
|
|
}
|
|
return ids
|
|
}
|
|
|
|
// assertOrder verifies that the expected IDs appear in order within ids.
|
|
// Other IDs may be interspersed (e.g., from other tests).
|
|
func assertOrder(t *testing.T, ids []string, expected ...string) {
|
|
t.Helper()
|
|
pos := 0
|
|
for _, id := range ids {
|
|
if pos < len(expected) && id == expected[pos] {
|
|
pos++
|
|
}
|
|
}
|
|
if pos != len(expected) {
|
|
t.Errorf("expected order %v but got %v (matched %d of %d)", expected, ids, pos, len(expected))
|
|
}
|
|
}
|
|
|
|
// TestEphemeralExplicitID_GetIssue verifies that GetIssue finds ephemeral beads
|
|
// created with explicit (non-wisp) IDs. Regression test for GH#2053.
|
|
func TestEphemeralExplicitID_GetIssue(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
// Create an ephemeral bead with an explicit ID (no -wisp- in name)
|
|
issue := &types.Issue{
|
|
ID: "test-agent-emma",
|
|
Title: "Agent: test-agent-emma",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue (ephemeral with explicit ID) failed: %v", err)
|
|
}
|
|
|
|
// GetIssue should find it (this was the GH#2053 bug)
|
|
got, err := store.GetIssue(ctx, "test-agent-emma")
|
|
if err != nil {
|
|
t.Fatalf("GetIssue failed for ephemeral bead with explicit ID: %v", err)
|
|
}
|
|
if got.ID != "test-agent-emma" {
|
|
t.Errorf("Expected ID %q, got %q", "test-agent-emma", got.ID)
|
|
}
|
|
if !got.Ephemeral {
|
|
t.Error("Expected Ephemeral=true")
|
|
}
|
|
}
|
|
|
|
func TestGetIssue_WispLabelTableErrorPropagates(t *testing.T) {
|
|
store, cleanup := setupConcurrentTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
wisp := &types.Issue{
|
|
ID: "test-wisp-label-error",
|
|
Title: "Wisp with missing labels table",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, wisp, "tester"); err != nil {
|
|
t.Fatalf("CreateIssue: %v", err)
|
|
}
|
|
if _, err := store.db.ExecContext(ctx, "DROP TABLE wisp_labels"); err != nil {
|
|
t.Fatalf("drop wisp_labels: %v", err)
|
|
}
|
|
|
|
_, err := store.GetIssue(ctx, wisp.ID)
|
|
if err == nil {
|
|
t.Fatal("expected error for missing wisp_labels table")
|
|
}
|
|
if errors.Is(err, storage.ErrNotFound) {
|
|
t.Fatalf("expected table error, got ErrNotFound: %v", err)
|
|
}
|
|
if !strings.Contains(err.Error(), "wisp_labels") {
|
|
t.Fatalf("expected error to mention wisp_labels, got: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestEphemeralExplicitID_UpdateIssue verifies that UpdateIssue works on
|
|
// ephemeral beads created with explicit IDs. Regression test for GH#2053.
|
|
func TestEphemeralExplicitID_UpdateIssue(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
issue := &types.Issue{
|
|
ID: "test-ephemeral-update",
|
|
Title: "Ephemeral: test-ephemeral-update",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue failed: %v", err)
|
|
}
|
|
|
|
// UpdateIssue should work (this was broken per GH#2053)
|
|
updates := map[string]interface{}{
|
|
"title": "Updated ephemeral title",
|
|
}
|
|
if err := store.UpdateIssue(ctx, "test-ephemeral-update", updates, "test-user"); err != nil {
|
|
t.Fatalf("UpdateIssue failed for ephemeral bead with explicit ID: %v", err)
|
|
}
|
|
|
|
// Verify the update persisted
|
|
got, err := store.GetIssue(ctx, "test-ephemeral-update")
|
|
if err != nil {
|
|
t.Fatalf("GetIssue after update failed: %v", err)
|
|
}
|
|
if got.Title != "Updated ephemeral title" {
|
|
t.Errorf("Expected title %q, got %q", "Updated ephemeral title", got.Title)
|
|
}
|
|
}
|
|
|
|
// TestEphemeralExplicitID_SearchIssues verifies that SearchIssues finds
|
|
// ephemeral beads with explicit IDs (this already worked pre-fix via wisp merge).
|
|
func TestEphemeralExplicitID_SearchIssues(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
issue := &types.Issue{
|
|
ID: "test-agent-furiosa",
|
|
Title: "Agent: test-agent-furiosa",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue failed: %v", err)
|
|
}
|
|
|
|
// SearchIssues with nil Ephemeral filter should find it (merges wisps)
|
|
results, err := store.SearchIssues(ctx, "", types.IssueFilter{
|
|
IDs: []string{"test-agent-furiosa"},
|
|
})
|
|
if err != nil {
|
|
t.Fatalf("SearchIssues failed: %v", err)
|
|
}
|
|
if len(results) != 1 {
|
|
t.Fatalf("Expected 1 result, got %d", len(results))
|
|
}
|
|
if results[0].ID != "test-agent-furiosa" {
|
|
t.Errorf("Expected ID %q, got %q", "test-agent-furiosa", results[0].ID)
|
|
}
|
|
}
|
|
|
|
// TestCreateEphemeralAutoID verifies that CreateIssue generates a non-empty
|
|
// wisp-prefixed ID for ephemeral issues when no explicit ID is provided.
|
|
// Regression test for GH#2087: bd create --ephemeral generated empty IDs.
|
|
func TestCreateEphemeralAutoID(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
issue := &types.Issue{
|
|
Title: "Ephemeral auto ID test",
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue (ephemeral, no explicit ID) failed: %v", err)
|
|
}
|
|
|
|
// ID must not be empty (the GH#2087 bug)
|
|
if issue.ID == "" {
|
|
t.Fatal("ephemeral issue got empty ID — GH#2087 regression")
|
|
}
|
|
|
|
// ID should contain the wisp infix
|
|
if !strings.Contains(issue.ID, "-wisp-") {
|
|
t.Errorf("expected wisp-prefixed ID, got %q", issue.ID)
|
|
}
|
|
|
|
// Verify the issue is retrievable from the wisps table
|
|
got, err := store.GetIssue(ctx, issue.ID)
|
|
if err != nil {
|
|
t.Fatalf("GetIssue(%q) failed: %v", issue.ID, err)
|
|
}
|
|
if got.Title != "Ephemeral auto ID test" {
|
|
t.Errorf("title mismatch: got %q", got.Title)
|
|
}
|
|
if !got.Ephemeral {
|
|
t.Error("expected Ephemeral=true on retrieved issue")
|
|
}
|
|
}
|
|
|
|
// TestCreateMultipleEphemeralAutoIDs verifies that multiple ephemeral issues
|
|
// created without explicit IDs each get unique, non-empty IDs.
|
|
// Regression test for GH#2087: second insert hit UNIQUE constraint on empty ID.
|
|
func TestCreateMultipleEphemeralAutoIDs(t *testing.T) {
|
|
store, cleanup := setupTestStore(t)
|
|
defer cleanup()
|
|
|
|
ctx, cancel := testContext(t)
|
|
defer cancel()
|
|
|
|
ids := make(map[string]bool)
|
|
for i := 0; i < 5; i++ {
|
|
issue := &types.Issue{
|
|
Title: fmt.Sprintf("Ephemeral #%d", i),
|
|
Status: types.StatusOpen,
|
|
Priority: 2,
|
|
IssueType: types.TypeTask,
|
|
Ephemeral: true,
|
|
}
|
|
if err := store.CreateIssue(ctx, issue, "test-user"); err != nil {
|
|
t.Fatalf("CreateIssue #%d failed: %v", i, err)
|
|
}
|
|
if issue.ID == "" {
|
|
t.Fatalf("ephemeral issue #%d got empty ID", i)
|
|
}
|
|
if ids[issue.ID] {
|
|
t.Fatalf("duplicate ID %q on issue #%d", issue.ID, i)
|
|
}
|
|
ids[issue.ID] = true
|
|
}
|
|
}
|