Merge pull request #2547 from coffeegoddd/db/create-issue

fix(embeddeddolt): implement create issue (not for production use)
This commit is contained in:
Dustin Brown 2026-03-13 10:55:10 -07:00 • committed by GitHub
commit 4c5a8f4f2e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 2144 additions and 160 deletions

View file

@ -0,0 +1,123 @@
//go:build embeddeddolt
package embeddeddolt
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/storage/dolt"
"github.com/steveyegge/beads/internal/types"
)
func (s *EmbeddedDoltStore) SetConfig(ctx context.Context, key, value string) error {
// Normalize issue_prefix: strip trailing hyphen to avoid double-hyphen IDs,
// matching DoltStore behavior.
if key == "issue_prefix" {
value = strings.TrimSuffix(value, "-")
}
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "REPLACE INTO config (`key`, value) VALUES (?, ?)", key, value)
return err
})
}
func (s *EmbeddedDoltStore) GetConfig(ctx context.Context, key string) (string, error) {
var value string
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", key).Scan(&value)
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return "", fmt.Errorf("embeddeddolt: get config %q: %w", key, err)
}
return value, nil
}
func (s *EmbeddedDoltStore) GetAllConfig(ctx context.Context) (map[string]string, error) {
result := make(map[string]string)
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
rows, err := tx.QueryContext(ctx, "SELECT `key`, value FROM config")
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var k, v string
if err := rows.Scan(&k, &v); err != nil {
return err
}
result[k] = v
}
return rows.Err()
})
if err != nil {
return nil, err
}
return result, nil
}
func (s *EmbeddedDoltStore) GetMetadata(ctx context.Context, key string) (string, error) {
var value string
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT value FROM metadata WHERE `key` = ?", key).Scan(&value)
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return "", fmt.Errorf("GetMetadata(%q): %w", key, err)
}
return value, nil
}
func (s *EmbeddedDoltStore) SetMetadata(ctx context.Context, key, value string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "REPLACE INTO metadata (`key`, value) VALUES (?, ?)", key, value)
return err
})
}
// GetInfraTypes returns the set of infrastructure types that should be routed
// to the wisps table. Reads from DB config "types.infra", falls back to YAML,
// then to hardcoded defaults (agent, rig, role, message).
func (s *EmbeddedDoltStore) GetInfraTypes(ctx context.Context) map[string]bool {
var typeList []string
value, err := s.GetConfig(ctx, "types.infra")
if err == nil && value != "" {
for _, t := range strings.Split(value, ",") {
t = strings.TrimSpace(t)
if t != "" {
typeList = append(typeList, t)
}
}
}
if len(typeList) == 0 {
if yamlTypes := config.GetInfraTypesFromYAML(); len(yamlTypes) > 0 {
typeList = yamlTypes
}
}
if len(typeList) == 0 {
typeList = dolt.DefaultInfraTypes()
}
result := make(map[string]bool, len(typeList))
for _, t := range typeList {
result[t] = true
}
return result
}
// IsInfraTypeCtx returns true if the issue type is an infrastructure type.
func (s *EmbeddedDoltStore) IsInfraTypeCtx(ctx context.Context, t types.IssueType) bool {
return s.GetInfraTypes(ctx)[string(t)]
}

View file

@ -0,0 +1,71 @@
//go:build embeddeddolt
package embeddeddolt
import (
"context"
"database/sql"
"fmt"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/storage/issueops"
"github.com/steveyegge/beads/internal/types"
)
func (s *EmbeddedDoltStore) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error {
if issue == nil {
return fmt.Errorf("issue must not be nil")
}
// Route infra types to wisps, matching DoltStore.CreateIssue behavior.
if s.IsInfraTypeCtx(ctx, issue.IssueType) {
issue.Ephemeral = true
}
return s.withConn(ctx, true, func(tx *sql.Tx) error {
// SkipPrefixValidation matches DoltStore.CreateIssue, which does not
// validate prefixes for explicit IDs on the single-issue path.
bc, err := issueops.NewBatchContext(ctx, tx, storage.BatchCreateOptions{
SkipPrefixValidation: true,
})
if err != nil {
return err
}
return issueops.CreateIssueInTx(ctx, tx, bc, issue, actor)
})
}
func (s *EmbeddedDoltStore) CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error {
return s.CreateIssuesWithFullOptions(ctx, issues, actor, storage.BatchCreateOptions{
OrphanHandling: storage.OrphanAllow,
SkipPrefixValidation: false,
})
}
func (s *EmbeddedDoltStore) CreateIssuesWithFullOptions(ctx context.Context, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error {
if len(issues) == 0 {
return nil
}
// All-ephemeral fast path: create each wisp individually within
// its own transaction, threading opts through so that callers'
// SkipPrefixValidation / OrphanHandling settings are respected.
if issueops.AllEphemeral(issues) {
for _, issue := range issues {
issue.Ephemeral = true
if err := s.withConn(ctx, true, func(tx *sql.Tx) error {
bc, err := issueops.NewBatchContext(ctx, tx, opts)
if err != nil {
return err
}
return issueops.CreateIssueInTx(ctx, tx, bc, issue, actor)
}); err != nil {
return err
}
}
return nil
}
return s.withConn(ctx, true, func(tx *sql.Tx) error {
return issueops.CreateIssuesInTx(ctx, tx, issues, actor, opts)
})
}

View file

@ -0,0 +1,924 @@
//go:build embeddeddolt
package embeddeddolt_test
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/steveyegge/beads/internal/storage/embeddeddolt"
"github.com/steveyegge/beads/internal/types"
)
// testEnv bundles a store with the paths needed to open raw SQL connections.
type testEnv struct {
store *embeddeddolt.EmbeddedDoltStore
dataDir string
database string
}
// newTestEnv creates an initialized EmbeddedDoltStore in a temp directory,
// sets the issue_prefix config, and returns a testEnv with raw SQL access.
func newTestEnv(t *testing.T, prefix string) *testEnv {
t.Helper()
ctx := t.Context()
beadsDir := filepath.Join(t.TempDir(), ".beads")
store, err := embeddeddolt.New(ctx, beadsDir, prefix, "main")
if err != nil {
t.Fatalf("New: %v", err)
}
t.Cleanup(func() { store.Close() })
if err := store.SetConfig(ctx, "issue_prefix", prefix); err != nil {
t.Fatalf("SetConfig(issue_prefix): %v", err)
}
if err := store.Commit(ctx, "bd init"); err != nil {
t.Fatalf("Commit: %v", err)
}
return &testEnv{
store: store,
dataDir: filepath.Join(beadsDir, "embeddeddolt"),
database: prefix,
}
}
// queryScalar opens a short-lived raw SQL connection, runs a single-row query,
// scans the results into dest, and closes the connection immediately.
func (te *testEnv) queryScalar(t *testing.T, ctx context.Context, query string, args []any, dest ...any) {
t.Helper()
db, cleanup, err := embeddeddolt.OpenSQL(ctx, te.dataDir, te.database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer cleanup()
if err := db.QueryRowContext(ctx, query, args...).Scan(dest...); err != nil {
t.Fatalf("queryScalar %q: %v", query, err)
}
}
// exec opens a short-lived raw SQL connection, executes a statement, and closes immediately.
func (te *testEnv) exec(t *testing.T, ctx context.Context, stmt string, args ...any) {
t.Helper()
db, cleanup, err := embeddeddolt.OpenSQL(ctx, te.dataDir, te.database, "main")
if err != nil {
t.Fatalf("OpenSQL: %v", err)
}
defer cleanup()
if _, err := db.ExecContext(ctx, stmt, args...); err != nil {
t.Fatalf("exec %q: %v", stmt, err)
}
}
// assertRowExists verifies a row exists in the given table with the given ID.
func (te *testEnv) assertRowExists(t *testing.T, ctx context.Context, table, id string) {
t.Helper()
var count int
te.queryScalar(t, ctx, fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id = ?", table), []any{id}, &count)
if count == 0 {
t.Errorf("expected row in %s with id=%q, found none", table, id)
}
}
// assertRowNotExists verifies no row exists in the given table with the given ID.
func (te *testEnv) assertRowNotExists(t *testing.T, ctx context.Context, table, id string) {
t.Helper()
var count int
te.queryScalar(t, ctx, fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE id = ?", table), []any{id}, &count)
if count != 0 {
t.Errorf("expected no row in %s with id=%q, found %d", table, id, count)
}
}
// assertIssueTitle verifies the title of an issue in the given table.
func (te *testEnv) assertIssueTitle(t *testing.T, ctx context.Context, table, id, wantTitle string) {
t.Helper()
var got string
te.queryScalar(t, ctx, fmt.Sprintf("SELECT title FROM %s WHERE id = ?", table), []any{id}, &got)
if got != wantTitle {
t.Errorf("title for %s: got %q, want %q", id, got, wantTitle)
}
}
// assertEventCount verifies the number of events for an issue.
func (te *testEnv) assertEventCount(t *testing.T, ctx context.Context, table, issueID, eventType string, wantCount int) {
t.Helper()
var count int
te.queryScalar(t, ctx,
fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE issue_id = ? AND event_type = ?", table),
[]any{issueID, eventType}, &count)
if count != wantCount {
t.Errorf("event count for %s/%s: got %d, want %d", issueID, eventType, count, wantCount)
}
}
// assertLabelCount verifies the number of labels for an issue.
func (te *testEnv) assertLabelCount(t *testing.T, ctx context.Context, table, issueID string, wantCount int) {
t.Helper()
var count int
te.queryScalar(t, ctx,
fmt.Sprintf("SELECT COUNT(*) FROM %s WHERE issue_id = ?", table),
[]any{issueID}, &count)
if count != wantCount {
t.Errorf("label count for %s: got %d, want %d", issueID, count, wantCount)
}
}
// assertChildCounter verifies the last_child value in child_counters.
func (te *testEnv) assertChildCounter(t *testing.T, ctx context.Context, parentID string, wantLastChild int) {
t.Helper()
var lastChild int
te.queryScalar(t, ctx,
"SELECT last_child FROM child_counters WHERE parent_id = ?",
[]any{parentID}, &lastChild)
if lastChild != wantLastChild {
t.Errorf("last_child for %s: got %d, want %d", parentID, lastChild, wantLastChild)
}
}
func skipUnlessEmbeddedDolt(t *testing.T) {
t.Helper()
if os.Getenv("BEADS_TEST_EMBEDDED_DOLT") != "1" {
t.Skip("set BEADS_TEST_EMBEDDED_DOLT=1 to run embedded dolt tests")
}
}
func TestCreateIssue(t *testing.T) {
skipUnlessEmbeddedDolt(t)
t.Run("basic", func(t *testing.T) {
te := newTestEnv(t, "ci")
ctx := t.Context()
issue := &types.Issue{
Title: "Test issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.ID == "" {
t.Fatal("expected issue ID to be generated")
}
if issue.ContentHash == "" {
t.Error("expected content hash to be computed")
}
if issue.CreatedAt.IsZero() {
t.Error("expected created_at to be set")
}
te.assertRowExists(t, ctx, "issues", issue.ID)
})
t.Run("nil_issue_errors", func(t *testing.T) {
te := newTestEnv(t, "ni")
ctx := t.Context()
err := te.store.CreateIssue(ctx, nil, "tester")
if err == nil {
t.Fatal("expected error for nil issue")
}
})
t.Run("with_explicit_id", func(t *testing.T) {
te := newTestEnv(t, "ex")
ctx := t.Context()
issue := &types.Issue{
ID: "ex-manual1",
Title: "Explicit ID issue",
Status: types.StatusOpen,
Priority: 1,
IssueType: types.TypeBug,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.ID != "ex-manual1" {
t.Errorf("ID: got %q, want %q", issue.ID, "ex-manual1")
}
te.assertRowExists(t, ctx, "issues", "ex-manual1")
})
t.Run("missing_prefix_errors", func(t *testing.T) {
ctx := t.Context()
beadsDir := filepath.Join(t.TempDir(), ".beads")
store, err := embeddeddolt.New(ctx, beadsDir, "noprefix", "main")
if err != nil {
t.Fatalf("New: %v", err)
}
t.Cleanup(func() { store.Close() })
issue := &types.Issue{
Title: "Should fail",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
err = store.CreateIssue(ctx, issue, "tester")
if err == nil {
t.Fatal("expected error for missing issue_prefix")
}
if !strings.Contains(err.Error(), "issue_prefix config is missing") {
t.Errorf("expected ErrNotInitialized, got: %v", err)
}
})
t.Run("closed_gets_closed_at", func(t *testing.T) {
te := newTestEnv(t, "cc")
ctx := t.Context()
issue := &types.Issue{
Title: "Closed issue",
Status: types.StatusClosed,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.ClosedAt == nil {
t.Error("expected closed_at to be set for closed issue")
}
})
t.Run("timestamps_utc", func(t *testing.T) {
te := newTestEnv(t, "tz")
ctx := t.Context()
loc := time.FixedZone("Test", 5*3600)
nonUTC := time.Date(2025, 1, 15, 12, 0, 0, 0, loc)
issue := &types.Issue{
Title: "Timezone test",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
CreatedAt: nonUTC,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.CreatedAt.Location() != time.UTC {
t.Errorf("expected UTC, got %v", issue.CreatedAt.Location())
}
})
t.Run("upsert_on_duplicate", func(t *testing.T) {
te := newTestEnv(t, "up")
ctx := t.Context()
issue := &types.Issue{
ID: "up-dup1",
Title: "Original title",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("first CreateIssue: %v", err)
}
issue2 := &types.Issue{
ID: "up-dup1",
Title: "Updated title",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue2, "tester"); err != nil {
t.Fatalf("second CreateIssue (upsert): %v", err)
}
te.assertIssueTitle(t, ctx, "issues", "up-dup1", "Updated title")
})
t.Run("event_recorded", func(t *testing.T) {
te := newTestEnv(t, "ev")
ctx := t.Context()
issue := &types.Issue{
ID: "ev-evt1",
Title: "Event test",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
te.assertEventCount(t, ctx, "events", "ev-evt1", "created", 1)
})
t.Run("ephemeral_routes_to_wisps", func(t *testing.T) {
te := newTestEnv(t, "ew")
ctx := t.Context()
issue := &types.Issue{
ID: "ew-wisp1",
Title: "Ephemeral issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
Ephemeral: true,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
te.assertRowExists(t, ctx, "wisps", "ew-wisp1")
te.assertRowNotExists(t, ctx, "issues", "ew-wisp1")
})
t.Run("ephemeral_auto_id", func(t *testing.T) {
te := newTestEnv(t, "ea")
ctx := t.Context()
issue := &types.Issue{
Title: "Ephemeral auto ID test",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
Ephemeral: true,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.ID == "" {
t.Fatal("ephemeral issue got empty ID")
}
if !strings.Contains(issue.ID, "-wisp-") {
t.Errorf("expected wisp-prefixed ID, got %q", issue.ID)
}
te.assertRowExists(t, ctx, "wisps", issue.ID)
})
t.Run("multiple_ephemeral_auto_ids_unique", func(t *testing.T) {
te := newTestEnv(t, "mu")
ctx := t.Context()
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 := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue #%d: %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
}
})
t.Run("counter_mode", func(t *testing.T) {
te := newTestEnv(t, "cm")
ctx := t.Context()
if err := te.store.SetConfig(ctx, "issue_id_mode", "counter"); err != nil {
t.Fatalf("SetConfig(issue_id_mode): %v", err)
}
if err := te.store.Commit(ctx, "enable counter mode"); err != nil {
t.Fatalf("Commit: %v", err)
}
issue1 := &types.Issue{
Title: "Counter issue 1",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue1, "tester"); err != nil {
t.Fatalf("CreateIssue 1: %v", err)
}
if issue1.ID != "cm-1" {
t.Errorf("first counter ID: got %q, want %q", issue1.ID, "cm-1")
}
issue2 := &types.Issue{
Title: "Counter issue 2",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue2, "tester"); err != nil {
t.Fatalf("CreateIssue 2: %v", err)
}
if issue2.ID != "cm-2" {
t.Errorf("second counter ID: got %q, want %q", issue2.ID, "cm-2")
}
})
t.Run("counter_explicit_id_overrides", func(t *testing.T) {
te := newTestEnv(t, "co")
ctx := t.Context()
if err := te.store.SetConfig(ctx, "issue_id_mode", "counter"); err != nil {
t.Fatalf("SetConfig: %v", err)
}
if err := te.store.Commit(ctx, "enable counter mode"); err != nil {
t.Fatalf("Commit: %v", err)
}
issue := &types.Issue{
ID: "co-explicit",
Title: "Explicit ID issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.ID != "co-explicit" {
t.Errorf("expected co-explicit, got %q", issue.ID)
}
})
t.Run("counter_seeds_from_existing", func(t *testing.T) {
te := newTestEnv(t, "cs")
ctx := t.Context()
// Create issues with explicit sequential IDs before enabling counter mode.
for _, id := range []string{"cs-5", "cs-10", "cs-3"} {
issue := &types.Issue{
ID: id,
Title: "Pre-existing " + id,
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue %s: %v", id, err)
}
}
if err := te.store.SetConfig(ctx, "issue_id_mode", "counter"); err != nil {
t.Fatalf("SetConfig: %v", err)
}
if err := te.store.Commit(ctx, "enable counter mode"); err != nil {
t.Fatalf("Commit: %v", err)
}
next := &types.Issue{
Title: "First counter-mode issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, next, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if next.ID != "cs-11" {
t.Errorf("expected cs-11 (seeded from max existing id 10), got %q", next.ID)
}
})
t.Run("counter_seeds_from_mixed", func(t *testing.T) {
te := newTestEnv(t, "sm")
ctx := t.Context()
// Create a mix: one hash-based ID and one numeric ID.
for _, iss := range []*types.Issue{
{ID: "sm-a3f2", Title: "Hash-based", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "sm-7", Title: "Numeric", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
} {
if err := te.store.CreateIssue(ctx, iss, "tester"); err != nil {
t.Fatalf("CreateIssue %s: %v", iss.ID, err)
}
}
if err := te.store.SetConfig(ctx, "issue_id_mode", "counter"); err != nil {
t.Fatalf("SetConfig: %v", err)
}
if err := te.store.Commit(ctx, "enable counter mode"); err != nil {
t.Fatalf("Commit: %v", err)
}
next := &types.Issue{
Title: "First counter-mode issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, next, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if next.ID != "sm-8" {
t.Errorf("expected sm-8 (seeded from max numeric id 7, ignoring hash id), got %q", next.ID)
}
})
t.Run("counter_already_seeded", func(t *testing.T) {
te := newTestEnv(t, "as")
ctx := t.Context()
// Manually seed counter at 20.
te.exec(t, ctx, "INSERT INTO issue_counter (prefix, last_id) VALUES (?, ?)", "as", 20)
// Create a manually-specified issue with a higher ID.
high := &types.Issue{
ID: "as-99",
Title: "High manual ID",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, high, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if err := te.store.SetConfig(ctx, "issue_id_mode", "counter"); err != nil {
t.Fatalf("SetConfig: %v", err)
}
if err := te.store.Commit(ctx, "enable counter mode"); err != nil {
t.Fatalf("Commit: %v", err)
}
// Counter was at 20; seeding must NOT override existing row.
next := &types.Issue{
Title: "Next counter issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, next, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if next.ID != "as-21" {
t.Errorf("expected as-21 (counter must not re-seed over existing row), got %q", next.ID)
}
})
t.Run("hash_mode_default", func(t *testing.T) {
te := newTestEnv(t, "hm")
ctx := t.Context()
issue := &types.Issue{
Title: "Hash ID issue",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
if issue.ID == "" {
t.Error("expected non-empty ID in hash mode")
}
// Hash mode IDs should NOT be sequential integers.
if issue.ID == "hm-1" || issue.ID == "hm-2" {
t.Errorf("hash mode should not generate sequential IDs, got %q", issue.ID)
}
})
t.Run("no_double_hyphen", func(t *testing.T) {
te := newTestEnv(t, "gt")
ctx := t.Context()
// Write trailing-hyphen prefix directly to DB to bypass normalization.
te.exec(t, ctx, "UPDATE config SET value = ? WHERE `key` = ?", "gt-", "issue_prefix")
issue := &types.Issue{
Title: "test double hyphen",
Status: types.StatusOpen,
Priority: 3,
IssueType: types.TypeBug,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
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)
}
})
t.Run("event_type_without_custom_config", func(t *testing.T) {
te := newTestEnv(t, "et")
ctx := t.Context()
issue := &types.Issue{
Title: "state change audit trail",
Status: types.StatusClosed,
Priority: 4,
IssueType: types.TypeEvent,
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue with event type should succeed, got: %v", err)
}
te.assertRowExists(t, ctx, "issues", issue.ID)
})
t.Run("validation_fails_for_bad_issue", func(t *testing.T) {
te := newTestEnv(t, "vf")
ctx := t.Context()
issue := &types.Issue{
Title: "",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.TypeTask,
}
err := te.store.CreateIssue(ctx, issue, "tester")
if err == nil {
t.Fatal("expected validation error for empty title")
}
})
t.Run("wisp_validation_parity", func(t *testing.T) {
te := newTestEnv(t, "wv")
ctx := t.Context()
tests := []struct {
name string
issue *types.Issue
wantErr string
}{
{
name: "valid wisp",
issue: &types.Issue{
Title: "a valid wisp", Status: types.StatusOpen,
Priority: 2, IssueType: types.TypeTask, Ephemeral: true,
},
},
{
name: "empty title rejected",
issue: &types.Issue{
Title: "", Status: types.StatusOpen,
Priority: 2, IssueType: types.TypeTask, Ephemeral: true,
},
wantErr: "title is required",
},
{
name: "invalid status rejected",
issue: &types.Issue{
Title: "bad status", Status: types.Status("bogus"),
Priority: 2, IssueType: types.TypeTask, Ephemeral: true,
},
wantErr: "invalid status",
},
{
name: "invalid type rejected",
issue: &types.Issue{
Title: "bad type", Status: types.StatusOpen,
Priority: 2, IssueType: types.IssueType("nonexistent"), Ephemeral: true,
},
wantErr: "invalid issue type",
},
{
name: "event type accepted",
issue: &types.Issue{
Title: "wisp event", Status: types.StatusOpen,
Priority: 4, IssueType: types.TypeEvent, Ephemeral: true,
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := te.store.CreateIssue(ctx, tt.issue, "tester")
if tt.wantErr == "" {
if err != nil {
t.Fatalf("expected success, got: %v", err)
}
} else {
if err == nil {
t.Fatalf("expected error containing %q, got nil", tt.wantErr)
}
if !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("error %q does not contain %q", err.Error(), tt.wantErr)
}
}
})
}
})
t.Run("infra_type_routes_to_wisps", func(t *testing.T) {
te := newTestEnv(t, "ir")
ctx := t.Context()
// "agent" is an infra type but not a built-in issue type,
// so it must be configured as a custom type to pass validation.
if err := te.store.SetConfig(ctx, "types.custom", "agent"); err != nil {
t.Fatalf("SetConfig: %v", err)
}
issue := &types.Issue{
Title: "Agent wisp",
Status: types.StatusOpen,
Priority: 2,
IssueType: types.IssueType("agent"),
}
if err := te.store.CreateIssue(ctx, issue, "tester"); err != nil {
t.Fatalf("CreateIssue: %v", err)
}
// Infra type should have been marked ephemeral and routed to wisps table.
if !issue.Ephemeral {
t.Fatal("expected issue.Ephemeral to be set for infra type")
}
te.assertRowExists(t, ctx, "wisps", issue.ID)
te.assertRowNotExists(t, ctx, "issues", issue.ID)
})
}
func TestCreateIssues(t *testing.T) {
skipUnlessEmbeddedDolt(t)
t.Run("empty_slice", func(t *testing.T) {
te := newTestEnv(t, "es")
ctx := t.Context()
if err := te.store.CreateIssues(ctx, nil, "tester"); err != nil {
t.Fatalf("CreateIssues(nil): %v", err)
}
})
t.Run("multiple_issues", func(t *testing.T) {
te := newTestEnv(t, "mi")
ctx := t.Context()
issues := []*types.Issue{
{ID: "mi-aaa", Title: "First", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "mi-bbb", Title: "Second", Status: types.StatusOpen, Priority: 1, IssueType: types.TypeBug},
{ID: "mi-ccc", Title: "Third", Status: types.StatusClosed, Priority: 3, IssueType: types.TypeTask},
}
if err := te.store.CreateIssues(ctx, issues, "tester"); err != nil {
t.Fatalf("CreateIssues: %v", err)
}
for _, iss := range issues {
te.assertRowExists(t, ctx, "issues", iss.ID)
}
stats, err := te.store.GetStatistics(ctx)
if err != nil {
t.Fatalf("GetStatistics: %v", err)
}
if stats.TotalIssues != 3 {
t.Errorf("TotalIssues: got %d, want 3", stats.TotalIssues)
}
if stats.ClosedIssues != 1 {
t.Errorf("ClosedIssues: got %d, want 1", stats.ClosedIssues)
}
})
t.Run("upsert_skips_duplicate_events", func(t *testing.T) {
te := newTestEnv(t, "ud")
ctx := t.Context()
issues := []*types.Issue{
{ID: "ud-dup", Title: "Original", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
if err := te.store.CreateIssues(ctx, issues, "tester"); err != nil {
t.Fatalf("first CreateIssues: %v", err)
}
te.assertEventCount(t, ctx, "events", "ud-dup", "created", 1)
// Re-import same ID — should upsert without extra event.
issues2 := []*types.Issue{
{ID: "ud-dup", Title: "Updated", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
if err := te.store.CreateIssues(ctx, issues2, "tester"); err != nil {
t.Fatalf("second CreateIssues: %v", err)
}
te.assertIssueTitle(t, ctx, "issues", "ud-dup", "Updated")
te.assertEventCount(t, ctx, "events", "ud-dup", "created", 1) // still just 1
})
t.Run("all_ephemeral", func(t *testing.T) {
te := newTestEnv(t, "ae")
ctx := t.Context()
issues := []*types.Issue{
{ID: "ae-wisp-1", Title: "Wisp 1", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true},
{ID: "ae-wisp-2", Title: "Wisp 2", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true},
}
if err := te.store.CreateIssues(ctx, issues, "tester"); err != nil {
t.Fatalf("CreateIssues: %v", err)
}
for _, iss := range issues {
te.assertRowExists(t, ctx, "wisps", iss.ID)
te.assertRowNotExists(t, ctx, "issues", iss.ID)
}
})
t.Run("mixed_ephemeral_and_regular", func(t *testing.T) {
te := newTestEnv(t, "mx")
ctx := t.Context()
issues := []*types.Issue{
{ID: "mx-reg1", Title: "Regular", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "mx-wisp-1", Title: "Wisp", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask, Ephemeral: true},
}
if err := te.store.CreateIssues(ctx, issues, "tester"); err != nil {
t.Fatalf("CreateIssues: %v", err)
}
te.assertRowExists(t, ctx, "issues", "mx-reg1")
te.assertRowExists(t, ctx, "wisps", "mx-wisp-1")
te.assertRowNotExists(t, ctx, "issues", "mx-wisp-1")
})
t.Run("with_labels", func(t *testing.T) {
te := newTestEnv(t, "lb")
ctx := t.Context()
issues := []*types.Issue{
{
ID: "lb-lbl1", Title: "Labeled", Status: types.StatusOpen,
Priority: 2, IssueType: types.TypeTask,
Labels: []string{"bug", "urgent"},
},
}
if err := te.store.CreateIssues(ctx, issues, "tester"); err != nil {
t.Fatalf("CreateIssues: %v", err)
}
te.assertRowExists(t, ctx, "issues", "lb-lbl1")
te.assertLabelCount(t, ctx, "labels", "lb-lbl1", 2)
})
t.Run("hierarchical_child_counters", func(t *testing.T) {
te := newTestEnv(t, "hc")
ctx := t.Context()
issues := []*types.Issue{
{ID: "hc-parent", Title: "Parent", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "hc-parent.1", Title: "Child 1", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "hc-parent.2", Title: "Child 2", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
{ID: "hc-parent.5", Title: "Child 5", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
if err := te.store.CreateIssues(ctx, issues, "tester"); err != nil {
t.Fatalf("CreateIssues: %v", err)
}
for _, iss := range issues {
te.assertRowExists(t, ctx, "issues", iss.ID)
}
te.assertChildCounter(t, ctx, "hc-parent", 5)
})
t.Run("prefix_validation_rejects_mismatch", func(t *testing.T) {
te := newTestEnv(t, "pv")
ctx := t.Context()
issues := []*types.Issue{
{ID: "wrong-prefix-1", Title: "Bad prefix", Status: types.StatusOpen, Priority: 2, IssueType: types.TypeTask},
}
err := te.store.CreateIssues(ctx, issues, "tester")
if err == nil {
t.Fatal("expected prefix validation error")
}
if !strings.Contains(err.Error(), "prefix") {
t.Errorf("expected prefix error, got: %v", err)
}
})
}

View file

@ -0,0 +1,51 @@
//go:build embeddeddolt
package embeddeddolt
import (
"context"
"database/sql"
"fmt"
"github.com/steveyegge/beads/internal/types"
)
func (s *EmbeddedDoltStore) GetStatistics(ctx context.Context) (*types.Statistics, error) {
stats := &types.Statistics{}
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
if err := tx.QueryRowContext(ctx, `
SELECT
COUNT(*) AS total,
COALESCE(SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'deferred' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN pinned = 1 THEN 1 ELSE 0 END), 0)
FROM issues
`).Scan(
&stats.TotalIssues,
&stats.OpenIssues,
&stats.InProgressIssues,
&stats.ClosedIssues,
&stats.DeferredIssues,
&stats.PinnedIssues,
); err != nil {
return err
}
blockedIDs, err := computeBlockedIDs(ctx, tx, true)
if err != nil {
return err
}
stats.BlockedIssues = len(blockedIDs)
stats.ReadyIssues = stats.OpenIssues - stats.BlockedIssues
if stats.ReadyIssues < 0 {
stats.ReadyIssues = 0
}
return nil
})
if err != nil {
return nil, fmt.Errorf("embeddeddolt: get statistics: %w", err)
}
return stats, nil
}

View file

@ -9,7 +9,6 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"sync/atomic"
"time"
@ -188,14 +187,6 @@ func (s *EmbeddedDoltStore) initSchema(ctx context.Context) error {
})
}
func (s *EmbeddedDoltStore) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error {
panic("embeddeddolt: CreateIssue not implemented")
}
func (s *EmbeddedDoltStore) CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error {
panic("embeddeddolt: CreateIssues not implemented")
}
func (s *EmbeddedDoltStore) GetIssue(ctx context.Context, id string) (*types.Issue, error) {
panic("embeddeddolt: GetIssue not implemented")
}
@ -296,95 +287,6 @@ func (s *EmbeddedDoltStore) GetAllEventsSince(ctx context.Context, sinceID int64
panic("embeddeddolt: GetAllEventsSince not implemented")
}
func (s *EmbeddedDoltStore) GetStatistics(ctx context.Context) (*types.Statistics, error) {
stats := &types.Statistics{}
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
if err := tx.QueryRowContext(ctx, `
SELECT
COUNT(*) AS total,
COALESCE(SUM(CASE WHEN status = 'open' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'in_progress' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'closed' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN status = 'deferred' THEN 1 ELSE 0 END), 0),
COALESCE(SUM(CASE WHEN pinned = 1 THEN 1 ELSE 0 END), 0)
FROM issues
`).Scan(
&stats.TotalIssues,
&stats.OpenIssues,
&stats.InProgressIssues,
&stats.ClosedIssues,
&stats.DeferredIssues,
&stats.PinnedIssues,
); err != nil {
return err
}
blockedIDs, err := computeBlockedIDs(ctx, tx, true)
if err != nil {
return err
}
stats.BlockedIssues = len(blockedIDs)
stats.ReadyIssues = stats.OpenIssues - stats.BlockedIssues
if stats.ReadyIssues < 0 {
stats.ReadyIssues = 0
}
return nil
})
if err != nil {
return nil, fmt.Errorf("embeddeddolt: get statistics: %w", err)
}
return stats, nil
}
func (s *EmbeddedDoltStore) SetConfig(ctx context.Context, key, value string) error {
// Normalize issue_prefix: strip trailing hyphen to avoid double-hyphen IDs,
// matching DoltStore behavior.
if key == "issue_prefix" {
value = strings.TrimSuffix(value, "-")
}
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "REPLACE INTO config (`key`, value) VALUES (?, ?)", key, value)
return err
})
}
func (s *EmbeddedDoltStore) GetConfig(ctx context.Context, key string) (string, error) {
var value string
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", key).Scan(&value)
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return "", fmt.Errorf("embeddeddolt: get config %q: %w", key, err)
}
return value, nil
}
func (s *EmbeddedDoltStore) GetAllConfig(ctx context.Context) (map[string]string, error) {
result := make(map[string]string)
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
rows, err := tx.QueryContext(ctx, "SELECT `key`, value FROM config")
if err != nil {
return err
}
defer rows.Close()
for rows.Next() {
var k, v string
if err := rows.Scan(&k, &v); err != nil {
return err
}
result[k] = v
}
return rows.Err()
})
if err != nil {
return nil, err
}
return result, nil
}
func (s *EmbeddedDoltStore) RunInTransaction(ctx context.Context, commitMsg string, fn func(tx storage.Transaction) error) error {
panic("embeddeddolt: RunInTransaction not implemented")
}
@ -420,18 +322,6 @@ func (s *EmbeddedDoltStore) ListBranches(ctx context.Context) ([]string, error)
panic("embeddeddolt: ListBranches not implemented")
}
func (s *EmbeddedDoltStore) Commit(ctx context.Context, message string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx, "CALL DOLT_ADD('-A')"); err != nil {
return fmt.Errorf("dolt add: %w", err)
}
if _, err := tx.ExecContext(ctx, "CALL DOLT_COMMIT('-m', ?)", message); err != nil {
return fmt.Errorf("dolt commit: %w", err)
}
return nil
})
}
func (s *EmbeddedDoltStore) CommitPending(ctx context.Context, actor string) (bool, error) {
panic("embeddeddolt: CommitPending not implemented")
}
@ -484,28 +374,10 @@ func (s *EmbeddedDoltStore) Diff(ctx context.Context, fromRef, toRef string) ([]
// storage.RemoteStore
// ---------------------------------------------------------------------------
func (s *EmbeddedDoltStore) AddRemote(ctx context.Context, name, url string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "CALL DOLT_REMOTE('add', ?, ?)", name, url)
return err
})
}
func (s *EmbeddedDoltStore) RemoveRemote(ctx context.Context, name string) error {
panic("embeddeddolt: RemoveRemote not implemented")
}
func (s *EmbeddedDoltStore) HasRemote(ctx context.Context, name string) (bool, error) {
var count int
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT count(*) FROM dolt_remotes WHERE name = ?", name).Scan(&count)
})
if err != nil {
return false, err
}
return count > 0, nil
}
func (s *EmbeddedDoltStore) ListRemotes(ctx context.Context) ([]storage.RemoteInfo, error) {
panic("embeddeddolt: ListRemotes not implemented")
}
@ -570,9 +442,7 @@ func (s *EmbeddedDoltStore) RemoveFederationPeer(ctx context.Context, name strin
// storage.BulkIssueStore
// ---------------------------------------------------------------------------
func (s *EmbeddedDoltStore) CreateIssuesWithFullOptions(ctx context.Context, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error {
panic("embeddeddolt: CreateIssuesWithFullOptions not implemented")
}
// CreateIssuesWithFullOptions is implemented in create_issue.go.
func (s *EmbeddedDoltStore) DeleteIssues(ctx context.Context, ids []string, cascade bool, force bool, dryRun bool) (*types.DeleteIssuesResult, error) {
panic("embeddeddolt: DeleteIssues not implemented")
@ -674,27 +544,6 @@ func (s *EmbeddedDoltStore) GetLabelsForIssues(ctx context.Context, issueIDs []s
// storage.ConfigMetadataStore
// ---------------------------------------------------------------------------
func (s *EmbeddedDoltStore) GetMetadata(ctx context.Context, key string) (string, error) {
var value string
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT value FROM metadata WHERE `key` = ?", key).Scan(&value)
})
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return "", nil
}
return "", fmt.Errorf("GetMetadata(%q): %w", key, err)
}
return value, nil
}
func (s *EmbeddedDoltStore) SetMetadata(ctx context.Context, key, value string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "REPLACE INTO metadata (`key`, value) VALUES (?, ?)", key, value)
return err
})
}
func (s *EmbeddedDoltStore) DeleteConfig(ctx context.Context, key string) error {
panic("embeddeddolt: DeleteConfig not implemented")
}
@ -707,14 +556,6 @@ func (s *EmbeddedDoltStore) GetCustomTypes(ctx context.Context) ([]string, error
panic("embeddeddolt: GetCustomTypes not implemented")
}
func (s *EmbeddedDoltStore) GetInfraTypes(ctx context.Context) map[string]bool {
panic("embeddeddolt: GetInfraTypes not implemented")
}
func (s *EmbeddedDoltStore) IsInfraTypeCtx(ctx context.Context, t types.IssueType) bool {
panic("embeddeddolt: IsInfraTypeCtx not implemented")
}
// ---------------------------------------------------------------------------
// storage.CompactionStore
// ---------------------------------------------------------------------------

View file

@ -0,0 +1,39 @@
//go:build embeddeddolt
package embeddeddolt
import (
"context"
"database/sql"
"fmt"
)
func (s *EmbeddedDoltStore) Commit(ctx context.Context, message string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
if _, err := tx.ExecContext(ctx, "CALL DOLT_ADD('-A')"); err != nil {
return fmt.Errorf("dolt add: %w", err)
}
if _, err := tx.ExecContext(ctx, "CALL DOLT_COMMIT('-m', ?)", message); err != nil {
return fmt.Errorf("dolt commit: %w", err)
}
return nil
})
}
func (s *EmbeddedDoltStore) AddRemote(ctx context.Context, name, url string) error {
return s.withConn(ctx, true, func(tx *sql.Tx) error {
_, err := tx.ExecContext(ctx, "CALL DOLT_REMOTE('add', ?, ?)", name, url)
return err
})
}
func (s *EmbeddedDoltStore) HasRemote(ctx context.Context, name string) (bool, error) {
var count int
err := s.withConn(ctx, false, func(tx *sql.Tx) error {
return tx.QueryRowContext(ctx, "SELECT count(*) FROM dolt_remotes WHERE name = ?", name).Scan(&count)
})
if err != nil {
return false, err
}
return count > 0, nil
}

View file

@ -0,0 +1,367 @@
package issueops
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// BatchContext holds per-batch state read once and reused for every issue.
type BatchContext struct {
CustomStatuses []string
CustomTypes []string
ConfigPrefix string
AllowedPrefixes string
Opts storage.BatchCreateOptions
}
// NewBatchContext reads config from the database and returns a BatchContext.
func NewBatchContext(ctx context.Context, tx *sql.Tx, opts storage.BatchCreateOptions) (*BatchContext, error) {
customStatuses, err := GetCustomStatusesTx(ctx, tx)
if err != nil {
return nil, fmt.Errorf("failed to get custom statuses: %w", err)
}
customTypes, err := GetCustomTypesTx(ctx, tx)
if err != nil {
return nil, fmt.Errorf("failed to get custom types: %w", err)
}
configPrefix, err := ReadConfigPrefix(ctx, tx)
if err != nil {
return nil, err
}
var allowedPrefixes string
_ = tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "allowed_prefixes").Scan(&allowedPrefixes)
return &BatchContext{
CustomStatuses: customStatuses,
CustomTypes: customTypes,
ConfigPrefix: configPrefix,
AllowedPrefixes: allowedPrefixes,
Opts: opts,
}, nil
}
// CreateIssueInTx handles a single issue within a transaction:
// prepare, resolve prefix, generate ID, validate prefix, check orphans,
// insert, record event, persist labels/comments.
// Returns nil if the issue was skipped (e.g., orphan skip mode).
func CreateIssueInTx(ctx context.Context, tx *sql.Tx, bc *BatchContext, issue *types.Issue, actor string) error {
if err := PrepareIssueForInsert(issue, bc.CustomStatuses, bc.CustomTypes); err != nil {
return err
}
issueTable, eventTable := TableRouting(issue)
// Resolve prefix and generate ID if needed.
if issue.ID == "" {
prefix := bc.ConfigPrefix
if issue.PrefixOverride != "" {
prefix = issue.PrefixOverride
} else if issue.IDPrefix != "" {
prefix = bc.ConfigPrefix + "-" + issue.IDPrefix
} else if IsWisp(issue) {
prefix = bc.ConfigPrefix + "-wisp"
}
var err error
issue.ID, err = GenerateIssueIDInTable(ctx, tx, issueTable, prefix, issue, actor)
if err != nil {
return fmt.Errorf("failed to generate issue ID: %w", err)
}
} else if !bc.Opts.SkipPrefixValidation {
if err := ValidateIssueIDPrefix(issue.ID, bc.ConfigPrefix, bc.AllowedPrefixes); err != nil {
return fmt.Errorf("prefix validation failed for %s: %w", issue.ID, err)
}
}
if skip, err := CheckOrphan(ctx, tx, issue, issueTable, bc.Opts.OrphanHandling); err != nil {
return err
} else if skip {
return nil
}
isNew, err := InsertIssueIfNew(ctx, tx, issueTable, issue)
if err != nil {
return err
}
if isNew {
if err := RecordEventInTable(ctx, tx, eventTable, issue.ID, types.EventCreated, actor, ""); err != nil {
return fmt.Errorf("failed to record event for %s: %w", issue.ID, err)
}
}
if err := PersistLabels(ctx, tx, issue); err != nil {
return err
}
return PersistComments(ctx, tx, issue)
}
// CreateIssuesInTx creates multiple issues within a single transaction.
// Handles the first pass (insert each issue), second pass (dependencies),
// and child counter reconciliation. Does NOT handle dolt versioning.
func CreateIssuesInTx(ctx context.Context, tx *sql.Tx, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error {
bc, err := NewBatchContext(ctx, tx, opts)
if err != nil {
return err
}
for _, issue := range issues {
if err := CreateIssueInTx(ctx, tx, bc, issue, actor); err != nil {
return err
}
}
if err := PersistDependencies(ctx, tx, issues, actor); err != nil {
return err
}
return ReconcileChildCounters(ctx, tx, issues)
}
// PrepareIssueForInsert normalizes timestamps, validates, and computes the content hash.
func PrepareIssueForInsert(issue *types.Issue, customStatuses, customTypes []string) error {
if err := ValidateMetadataIfConfigured(issue.Metadata); err != nil {
return fmt.Errorf("metadata validation failed for issue %s: %w", issue.ID, err)
}
// Normalize timestamps to UTC, defaulting to now.
now := time.Now().UTC()
if issue.CreatedAt.IsZero() {
issue.CreatedAt = now
} else {
issue.CreatedAt = issue.CreatedAt.UTC()
}
if issue.UpdatedAt.IsZero() {
issue.UpdatedAt = now
} else {
issue.UpdatedAt = issue.UpdatedAt.UTC()
}
// Ensure closed issues have a closed_at timestamp.
if issue.Status == types.StatusClosed && issue.ClosedAt == nil {
maxTime := issue.CreatedAt
if issue.UpdatedAt.After(maxTime) {
maxTime = issue.UpdatedAt
}
closedAt := maxTime.Add(time.Second)
issue.ClosedAt = &closedAt
}
if err := issue.ValidateWithCustom(customStatuses, customTypes); err != nil {
return fmt.Errorf("validation failed for issue %s: %w", issue.ID, err)
}
if issue.ContentHash == "" {
issue.ContentHash = issue.ComputeContentHash()
}
return nil
}
// ValidateIssueIDPrefix validates that the issue ID matches the configured prefix
// or any of the allowed_prefixes.
func ValidateIssueIDPrefix(id, prefix, allowedPrefixes string) error {
if strings.HasPrefix(id, prefix+"-") {
return nil
}
if allowedPrefixes != "" {
for _, allowed := range strings.Split(allowedPrefixes, ",") {
allowed = strings.TrimSpace(allowed)
if allowed != "" && strings.HasPrefix(id, allowed+"-") {
return nil
}
}
}
return fmt.Errorf("%w: issue ID %s does not match configured prefix %s", storage.ErrPrefixMismatch, id, prefix)
}
// ParseHierarchicalID checks if an ID is hierarchical (e.g., "bd-abc.1")
// and returns the parent ID and child number.
func ParseHierarchicalID(id string) (parentID string, childNum int, ok bool) {
lastDot := strings.LastIndex(id, ".")
if lastDot == -1 {
return "", 0, false
}
parentID = id[:lastDot]
var num int
if _, err := fmt.Sscanf(id[lastDot+1:], "%d", &num); err != nil {
return "", 0, false
}
return parentID, num, true
}
// AllEphemeral returns true if every issue in the slice is ephemeral.
func AllEphemeral(issues []*types.Issue) bool {
for _, issue := range issues {
if !issue.Ephemeral {
return false
}
}
return true
}
// CheckOrphan handles orphan detection for hierarchical IDs.
// Returns (skip=true, nil) if the issue should be skipped.
//
//nolint:gosec // G201: table is a hardcoded constant
func CheckOrphan(ctx context.Context, tx *sql.Tx, issue *types.Issue, issueTable string, handling storage.OrphanHandling) (skip bool, err error) {
if issue.ID == "" {
return false, nil
}
parentID, _, ok := ParseHierarchicalID(issue.ID)
if !ok {
return false, nil
}
var parentCount int
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ?`, issueTable), parentID).Scan(&parentCount); err != nil {
return false, fmt.Errorf("failed to check parent existence: %w", err)
}
if parentCount > 0 {
return false, nil
}
switch handling {
case storage.OrphanStrict:
return false, fmt.Errorf("parent issue %s does not exist (strict mode)", parentID)
case storage.OrphanSkip:
return true, nil
default: // OrphanAllow, OrphanResurrect
return false, nil
}
}
// InsertIssueIfNew inserts the issue and returns whether it was genuinely new.
//
//nolint:gosec // G201: table is a hardcoded constant
func InsertIssueIfNew(ctx context.Context, tx *sql.Tx, issueTable string, issue *types.Issue) (isNew bool, err error) {
var existingCount int
if issue.ID != "" {
if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ?`, issueTable), issue.ID).Scan(&existingCount); err != nil {
return false, fmt.Errorf("failed to check issue existence for %s: %w", issue.ID, err)
}
}
if err := InsertIssueIntoTable(ctx, tx, issueTable, issue); err != nil {
return false, fmt.Errorf("failed to insert issue %s: %w", issue.ID, err)
}
return existingCount == 0, nil
}
// PersistLabels writes issue.Labels into the appropriate labels table.
func PersistLabels(ctx context.Context, tx *sql.Tx, issue *types.Issue) error {
if len(issue.Labels) == 0 {
return nil
}
labelTable := "labels"
if IsWisp(issue) {
labelTable = "wisp_labels"
}
for _, label := range issue.Labels {
//nolint:gosec // G201: table is determined by ephemeral flag
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (issue_id, label)
VALUES (?, ?)
ON DUPLICATE KEY UPDATE label = label
`, labelTable), issue.ID, label)
if err != nil {
return fmt.Errorf("failed to insert label %q for %s: %w", label, issue.ID, err)
}
}
return nil
}
// PersistComments writes issue.Comments into the appropriate comments table.
// Note: ON DUPLICATE KEY UPDATE is a no-op here since the comments table uses
// an auto-increment PK. Kept for consistency with DoltStore (GH#2061).
func PersistComments(ctx context.Context, tx *sql.Tx, issue *types.Issue) error {
if len(issue.Comments) == 0 {
return nil
}
commentTable := "comments"
if IsWisp(issue) {
commentTable = "wisp_comments"
}
for _, comment := range issue.Comments {
createdAt := comment.CreatedAt
if createdAt.IsZero() {
createdAt = time.Now().UTC()
}
//nolint:gosec // G201: table is determined by ephemeral flag
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (issue_id, author, text, created_at)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE text = VALUES(text)
`, commentTable), issue.ID, comment.Author, comment.Text, createdAt)
if err != nil {
return fmt.Errorf("failed to insert comment for %s: %w", issue.ID, err)
}
}
return nil
}
// PersistDependencies inserts dependencies for all issues (second pass).
func PersistDependencies(ctx context.Context, tx *sql.Tx, issues []*types.Issue, actor string) error {
for _, issue := range issues {
if len(issue.Dependencies) == 0 {
continue
}
depTable := "dependencies"
lookupTable := "issues"
if IsWisp(issue) {
depTable = "wisp_dependencies"
lookupTable = "wisps"
}
for _, dep := range issue.Dependencies {
// Skip if target doesn't exist.
var exists int
//nolint:gosec // G201: table is determined by isWisp flag
if err := tx.QueryRowContext(ctx, fmt.Sprintf("SELECT 1 FROM %s WHERE id = ?", lookupTable), dep.DependsOnID).Scan(&exists); err != nil {
continue
}
createdAt := dep.CreatedAt
if createdAt.IsZero() {
createdAt = time.Now().UTC()
}
//nolint:gosec // G201: table is determined by isWisp flag
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (issue_id, depends_on_id, type, created_by, created_at)
VALUES (?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE type = type
`, depTable), dep.IssueID, dep.DependsOnID, dep.Type, actor, createdAt)
if err != nil {
return fmt.Errorf("failed to insert dependency %s -> %s: %w", dep.IssueID, dep.DependsOnID, err)
}
}
}
return nil
}
// ReconcileChildCounters updates child_counters so that subsequent
// bd create --parent doesn't collide with imported hierarchical IDs.
func ReconcileChildCounters(ctx context.Context, tx *sql.Tx, issues []*types.Issue) error {
childMaxMap := make(map[string]int)
for _, issue := range issues {
if parentID, childNum, ok := ParseHierarchicalID(issue.ID); ok {
if childNum > childMaxMap[parentID] {
childMaxMap[parentID] = childNum
}
}
}
for parentID, maxChild := range childMaxMap {
var parentExists int
if err := tx.QueryRowContext(ctx, "SELECT 1 FROM issues WHERE id = ?", parentID).Scan(&parentExists); err != nil {
continue // parent not in issues table — skip counter
}
_, err := tx.ExecContext(ctx, `
INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?)
ON DUPLICATE KEY UPDATE last_child = GREATEST(last_child, ?)
`, parentID, maxChild, maxChild)
if err != nil {
return fmt.Errorf("failed to reconcile child counter for %s: %w", parentID, err)
}
}
return nil
}

View file

@ -0,0 +1,568 @@
// Package issueops provides shared transaction-scoped SQL operations for
// issue creation and management. Both DoltStore and EmbeddedDoltStore call
// into these functions, passing their own *sql.Tx obtained through their
// respective connection lifecycle patterns.
package issueops
import (
"context"
"database/sql"
"encoding/json"
"fmt"
"math"
"os"
"strconv"
"strings"
"github.com/steveyegge/beads/internal/config"
"github.com/steveyegge/beads/internal/idgen"
"github.com/steveyegge/beads/internal/storage"
"github.com/steveyegge/beads/internal/types"
)
// IsWisp returns true if the issue should be routed to the wisps table.
// Matches the DoltStore check: issue.Ephemeral || ID contains "-wisp-".
func IsWisp(issue *types.Issue) bool {
return issue.Ephemeral || strings.Contains(issue.ID, "-wisp-")
}
// TableRouting returns the issue and event table names for an issue,
// routing ephemeral issues to the wisps tables.
func TableRouting(issue *types.Issue) (issueTable, eventTable string) {
if IsWisp(issue) {
return "wisps", "wisp_events"
}
return "issues", "events"
}
// InsertIssueIntoTable inserts an issue into the specified table ("issues" or "wisps"),
// using ON DUPLICATE KEY UPDATE to handle pre-existing records gracefully.
//
//nolint:gosec // G201: table is a hardcoded constant ("issues" or "wisps")
func InsertIssueIntoTable(ctx context.Context, tx *sql.Tx, table string, issue *types.Issue) error {
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (
id, content_hash, title, description, design, acceptance_criteria, notes,
status, priority, issue_type, assignee, estimated_minutes,
created_at, created_by, owner, updated_at, closed_at, external_ref, spec_id,
compaction_level, compacted_at, compacted_at_commit, original_size,
sender, ephemeral, wisp_type, pinned, is_template, crystallizes,
mol_type, work_type, quality_score, source_system, source_repo, close_reason,
event_kind, actor, target, payload,
await_type, await_id, timeout_ns, waiters,
hook_bead, role_bead, agent_state, last_activity, role_type, rig,
due_at, defer_until, metadata
) VALUES (
?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?,
?, ?, ?, ?, ?, ?,
?, ?, ?
)
ON DUPLICATE KEY UPDATE
content_hash = VALUES(content_hash),
title = VALUES(title),
description = VALUES(description),
design = VALUES(design),
acceptance_criteria = VALUES(acceptance_criteria),
notes = VALUES(notes),
status = VALUES(status),
priority = VALUES(priority),
issue_type = VALUES(issue_type),
assignee = VALUES(assignee),
estimated_minutes = VALUES(estimated_minutes),
updated_at = VALUES(updated_at),
closed_at = VALUES(closed_at),
external_ref = VALUES(external_ref),
source_repo = VALUES(source_repo),
close_reason = VALUES(close_reason),
metadata = VALUES(metadata)
`, table),
issue.ID, issue.ContentHash, issue.Title, issue.Description, issue.Design, issue.AcceptanceCriteria, issue.Notes,
issue.Status, issue.Priority, issue.IssueType, NullString(issue.Assignee), NullInt(issue.EstimatedMinutes),
issue.CreatedAt, issue.CreatedBy, issue.Owner, issue.UpdatedAt, issue.ClosedAt, NullStringPtr(issue.ExternalRef), issue.SpecID,
issue.CompactionLevel, issue.CompactedAt, NullStringPtr(issue.CompactedAtCommit), NullIntVal(issue.OriginalSize),
issue.Sender, issue.Ephemeral, issue.WispType, issue.Pinned, issue.IsTemplate, issue.Crystallizes,
issue.MolType, issue.WorkType, issue.QualityScore, issue.SourceSystem, issue.SourceRepo, issue.CloseReason,
issue.EventKind, issue.Actor, issue.Target, issue.Payload,
issue.AwaitType, issue.AwaitID, issue.Timeout.Nanoseconds(), FormatJSONStringArray(issue.Waiters),
issue.HookBead, issue.RoleBead, issue.AgentState, issue.LastActivity, issue.RoleType, issue.Rig,
issue.DueAt, issue.DeferUntil, JSONMetadata(issue.Metadata),
)
if err != nil {
return fmt.Errorf("insert issue into %s: %w", table, err)
}
return nil
}
// RecordEventInTable records an event in the specified events table.
//
//nolint:gosec // G201: table is a hardcoded constant ("events" or "wisp_events")
func RecordEventInTable(ctx context.Context, tx *sql.Tx, table, issueID string, eventType types.EventType, actor, newValue string) error {
_, err := tx.ExecContext(ctx, fmt.Sprintf(`
INSERT INTO %s (issue_id, event_type, actor, old_value, new_value)
VALUES (?, ?, ?, ?, ?)
`, table), issueID, eventType, actor, "", newValue)
if err != nil {
return fmt.Errorf("record event in %s: %w", table, err)
}
return nil
}
// GenerateIssueIDInTable generates a unique ID, checking for collisions
// in the specified table. Supports counter mode for non-ephemeral issues.
//
//nolint:gosec // G201: table is a hardcoded constant
func GenerateIssueIDInTable(ctx context.Context, tx *sql.Tx, table, prefix string, issue *types.Issue, actor string) (string, error) {
// Counter mode only applies to the issues table (not wisps).
if table == "issues" {
counterMode, err := IsCounterModeTx(ctx, tx)
if err != nil {
return "", err
}
if counterMode {
return NextCounterIDTx(ctx, tx, prefix)
}
}
// Default hash-based ID generation
baseLength, err := GetAdaptiveIDLengthTx(ctx, tx, table, prefix)
if err != nil {
baseLength = 6
}
maxLength := 8
if baseLength > maxLength {
baseLength = maxLength
}
for length := baseLength; length <= maxLength; length++ {
for nonce := 0; nonce < 10; nonce++ {
candidate := idgen.GenerateHashID(prefix, issue.Title, issue.Description, actor, issue.CreatedAt, length, nonce)
var count int
err = tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT COUNT(*) FROM %s WHERE id = ?`, table), candidate).Scan(&count)
if err != nil {
return "", fmt.Errorf("failed to check for ID collision: %w", err)
}
if count == 0 {
return candidate, nil
}
}
}
return "", fmt.Errorf("failed to generate unique ID after trying lengths %d-%d with 10 nonces each", baseLength, maxLength)
}
// IsCounterModeTx checks whether issue_id_mode=counter is configured.
func IsCounterModeTx(ctx context.Context, tx *sql.Tx) (bool, error) {
var idMode string
err := tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "issue_id_mode").Scan(&idMode)
if err != nil && err != sql.ErrNoRows {
return false, fmt.Errorf("failed to read issue_id_mode config: %w", err)
}
return idMode == "counter", nil
}
// NextCounterIDTx atomically increments and returns the next sequential issue ID.
func NextCounterIDTx(ctx context.Context, tx *sql.Tx, prefix string) (string, error) {
res, err := tx.ExecContext(ctx, "UPDATE issue_counter SET last_id = last_id + 1 WHERE prefix = ?", prefix)
if err != nil {
return "", fmt.Errorf("failed to increment issue counter for prefix %q: %w", prefix, err)
}
rowsAffected, err := res.RowsAffected()
if err != nil {
return "", fmt.Errorf("failed to check rows affected for issue counter prefix %q: %w", prefix, err)
}
if rowsAffected == 0 {
if seedErr := SeedCounterFromExistingIssuesTx(ctx, tx, prefix); seedErr != nil {
return "", fmt.Errorf("failed to seed issue counter for prefix %q: %w", prefix, seedErr)
}
res, err = tx.ExecContext(ctx, "UPDATE issue_counter SET last_id = last_id + 1 WHERE prefix = ?", prefix)
if err != nil {
return "", fmt.Errorf("failed to increment issue counter after seeding for prefix %q: %w", prefix, err)
}
rowsAffected, err = res.RowsAffected()
if err != nil {
return "", fmt.Errorf("failed to check rows affected after seeding for prefix %q: %w", prefix, err)
}
if rowsAffected == 0 {
_, err = tx.ExecContext(ctx, "INSERT INTO issue_counter (prefix, last_id) VALUES (?, 1)", prefix)
if err != nil {
return "", fmt.Errorf("failed to insert initial issue counter for prefix %q: %w", prefix, err)
}
}
}
var nextID int
err = tx.QueryRowContext(ctx, "SELECT last_id FROM issue_counter WHERE prefix = ?", prefix).Scan(&nextID)
if err != nil {
return "", fmt.Errorf("failed to read issue counter after increment for prefix %q: %w", prefix, err)
}
return fmt.Sprintf("%s-%d", prefix, nextID), nil
}
// SeedCounterFromExistingIssuesTx scans existing issues to find the highest numeric suffix
// for the given prefix, then seeds the issue_counter table if no row exists yet.
func SeedCounterFromExistingIssuesTx(ctx context.Context, tx *sql.Tx, prefix string) error {
var existing int
err := tx.QueryRowContext(ctx, "SELECT last_id FROM issue_counter WHERE prefix = ?", prefix).Scan(&existing)
if err == nil {
return nil // already seeded
}
if err != sql.ErrNoRows {
return fmt.Errorf("failed to check existing counter for prefix %q: %w", prefix, err)
}
// Find max numeric suffix among existing issues
rows, err := tx.QueryContext(ctx, `SELECT id FROM issues WHERE id LIKE CONCAT(?, '-%')`, prefix)
if err != nil {
return fmt.Errorf("failed to scan existing issues for prefix %q: %w", prefix, err)
}
defer rows.Close()
maxNum := 0
pfxDash := prefix + "-"
for rows.Next() {
var id string
if err := rows.Scan(&id); err != nil {
continue
}
suffix := strings.TrimPrefix(id, pfxDash)
if strings.Contains(suffix, ".") {
continue // skip child IDs
}
if n, err := strconv.Atoi(suffix); err == nil && n > maxNum {
maxNum = n
}
}
if err := rows.Err(); err != nil {
return fmt.Errorf("failed to iterate issues for prefix %q: %w", prefix, err)
}
if maxNum > 0 {
_, err = tx.ExecContext(ctx, "INSERT INTO issue_counter (prefix, last_id) VALUES (?, ?)", prefix, maxNum)
if err != nil {
return fmt.Errorf("failed to seed issue counter for prefix %q at %d: %w", prefix, maxNum, err)
}
}
return nil
}
// GetAdaptiveIDLengthTx returns the appropriate hash length based on database size.
//
//nolint:gosec // G201: table is a hardcoded constant
func GetAdaptiveIDLengthTx(ctx context.Context, tx *sql.Tx, table, prefix string) (int, error) {
var count int
err := tx.QueryRowContext(ctx, fmt.Sprintf(`
SELECT COUNT(*)
FROM %s
WHERE id LIKE CONCAT(?, '-%%')
AND INSTR(SUBSTRING(id, LENGTH(?) + 2), '.') = 0
`, table), prefix, prefix).Scan(&count)
if err != nil {
return 6, err
}
cfg := GetAdaptiveConfigTx(ctx, tx)
return ComputeAdaptiveLength(count, cfg), nil
}
// AdaptiveIDConfig holds configuration for adaptive ID length computation.
type AdaptiveIDConfig struct {
MaxCollisionProbability float64
MinLength int
MaxLength int
}
// DefaultAdaptiveConfig returns the default adaptive ID configuration.
func DefaultAdaptiveConfig() AdaptiveIDConfig {
return AdaptiveIDConfig{
MaxCollisionProbability: 0.25,
MinLength: 3,
MaxLength: 8,
}
}
// GetAdaptiveConfigTx reads adaptive ID config from the database.
func GetAdaptiveConfigTx(ctx context.Context, tx *sql.Tx) AdaptiveIDConfig {
cfg := DefaultAdaptiveConfig()
var probStr string
err := tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "max_collision_prob").Scan(&probStr)
if err == nil && probStr != "" {
if prob, err := strconv.ParseFloat(probStr, 64); err == nil {
cfg.MaxCollisionProbability = prob
}
}
var minLenStr string
err = tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "min_hash_length").Scan(&minLenStr)
if err == nil && minLenStr != "" {
if minLen, err := strconv.Atoi(minLenStr); err == nil {
cfg.MinLength = minLen
}
}
var maxLenStr string
err = tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "max_hash_length").Scan(&maxLenStr)
if err == nil && maxLenStr != "" {
if maxLen, err := strconv.Atoi(maxLenStr); err == nil {
cfg.MaxLength = maxLen
}
}
return cfg
}
// ComputeAdaptiveLength uses the birthday paradox to pick a hash length
// that keeps collision probability below the configured threshold.
func ComputeAdaptiveLength(numIssues int, cfg AdaptiveIDConfig) int {
const base = 36.0
for length := cfg.MinLength; length <= cfg.MaxLength; length++ {
totalPossibilities := math.Pow(base, float64(length))
exponent := -float64(numIssues*numIssues) / (2.0 * totalPossibilities)
prob := 1.0 - math.Exp(exponent)
if prob <= cfg.MaxCollisionProbability {
return length
}
}
return cfg.MaxLength
}
// GetCustomStatusesTx reads custom statuses from config within a transaction.
func GetCustomStatusesTx(ctx context.Context, tx *sql.Tx) ([]string, error) {
var raw string
err := tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "status.custom").Scan(&raw)
if err == sql.ErrNoRows || raw == "" {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("failed to read status.custom config: %w", err)
}
var statuses []string
if err := json.Unmarshal([]byte(raw), &statuses); err != nil {
// Try comma-separated fallback
for _, s := range strings.Split(raw, ",") {
s = strings.TrimSpace(s)
if s != "" {
statuses = append(statuses, s)
}
}
}
return statuses, nil
}
// GetCustomTypesTx reads custom types from config within a transaction.
func GetCustomTypesTx(ctx context.Context, tx *sql.Tx) ([]string, error) {
var raw string
err := tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "types.custom").Scan(&raw)
if err == sql.ErrNoRows || raw == "" {
return nil, nil
}
if err != nil {
return nil, fmt.Errorf("failed to read custom_types config: %w", err)
}
var customTypes []string
if err := json.Unmarshal([]byte(raw), &customTypes); err != nil {
for _, s := range strings.Split(raw, ",") {
s = strings.TrimSpace(s)
if s != "" {
customTypes = append(customTypes, s)
}
}
}
return customTypes, nil
}
// ValidateMetadataIfConfigured checks metadata against the schema from config.
func ValidateMetadataIfConfigured(metadata json.RawMessage) error {
mode := config.MetadataValidationMode()
if mode == "none" || mode == "" {
return nil
}
rawFields := config.MetadataSchemaFields()
if rawFields == nil {
return nil
}
fields := make(map[string]storage.MetadataFieldSchema)
for name, raw := range rawFields {
fieldMap, ok := raw.(map[string]interface{})
if !ok {
continue
}
schema := ParseFieldSchema(fieldMap)
fields[name] = schema
}
if len(fields) == 0 {
return nil
}
schemaCfg := storage.MetadataSchemaConfig{
Mode: mode,
Fields: fields,
}
errs := storage.ValidateMetadataSchema(metadata, schemaCfg)
if len(errs) == 0 {
return nil
}
if mode == "warn" {
for _, e := range errs {
fmt.Fprintf(os.Stderr, "warning: %s\n", e.Error())
}
return nil
}
return fmt.Errorf("metadata schema violation: %s", errs[0].Error())
}
// ParseFieldSchema converts a raw config map into a MetadataFieldSchema.
func ParseFieldSchema(m map[string]interface{}) storage.MetadataFieldSchema {
schema := storage.MetadataFieldSchema{}
if t, ok := m["type"].(string); ok {
schema.Type = storage.MetadataFieldType(t)
}
if req, ok := m["required"].(bool); ok {
schema.Required = req
}
if vals, ok := m["values"]; ok {
switch v := vals.(type) {
case []interface{}:
for _, item := range v {
if s, ok := item.(string); ok {
schema.Values = append(schema.Values, s)
}
}
case string:
for _, s := range strings.Split(v, ",") {
s = strings.TrimSpace(s)
if s != "" {
schema.Values = append(schema.Values, s)
}
}
}
}
if min, ok := toFloat64(m["min"]); ok {
schema.Min = &min
}
if max, ok := toFloat64(m["max"]); ok {
schema.Max = &max
}
return schema
}
func toFloat64(v interface{}) (float64, bool) {
if v == nil {
return 0, false
}
switch n := v.(type) {
case float64:
return n, true
case int:
return float64(n), true
case int64:
return float64(n), true
default:
return 0, false
}
}
// IsDoltNothingToCommit returns true if the error is the benign
// "nothing to commit" Dolt message.
func IsDoltNothingToCommit(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "nothing to commit") ||
(strings.Contains(s, "no changes") && strings.Contains(s, "commit"))
}
// ReadConfigPrefix reads and normalizes issue_prefix from the config table.
func ReadConfigPrefix(ctx context.Context, tx *sql.Tx) (string, error) {
var configPrefix string
err := tx.QueryRowContext(ctx, "SELECT value FROM config WHERE `key` = ?", "issue_prefix").Scan(&configPrefix)
if err == sql.ErrNoRows || configPrefix == "" {
return "", fmt.Errorf("%w: issue_prefix config is missing (run 'bd init --prefix <prefix>' first)", storage.ErrNotInitialized)
} else if err != nil {
return "", fmt.Errorf("failed to get config: %w", err)
}
return strings.TrimSuffix(configPrefix, "-"), nil
}
// ---------------------------------------------------------------------------
// Nullable value helpers
// ---------------------------------------------------------------------------
// NullString returns nil for empty strings, otherwise the string value.
func NullString(s string) interface{} {
if s == "" {
return nil
}
return s
}
// NullStringPtr returns nil for nil pointers, otherwise the pointed-to string.
func NullStringPtr(s *string) interface{} {
if s == nil {
return nil
}
return *s
}
// NullInt returns nil for nil pointers, otherwise the pointed-to int.
func NullInt(i *int) interface{} {
if i == nil {
return nil
}
return *i
}
// NullIntVal returns nil for zero values, otherwise the int.
func NullIntVal(i int) interface{} {
if i == 0 {
return nil
}
return i
}
// JSONMetadata returns the metadata as a JSON string, defaulting to "{}".
func JSONMetadata(m []byte) string {
if len(m) == 0 {
return "{}"
}
if !json.Valid(m) {
fmt.Fprintf(os.Stderr, "Warning: invalid JSON metadata, using empty object\n")
return "{}"
}
return string(m)
}
// FormatJSONStringArray marshals a string slice to JSON, returning "" for empty/nil.
func FormatJSONStringArray(arr []string) string {
if len(arr) == 0 {
return ""
}
data, err := json.Marshal(arr)
if err != nil {
return ""
}
return string(data)
}