diff --git a/.claude/test-strategy.md b/.claude/test-strategy.md index d7ea17979..3b3709ec5 100644 --- a/.claude/test-strategy.md +++ b/.claude/test-strategy.md @@ -29,7 +29,7 @@ # Test specific package ./scripts/test.sh ./cmd/bd/... -./scripts/test.sh ./internal/storage/sqlite/... +./scripts/test.sh ./internal/storage/embeddeddolt/... # Test specific feature ./scripts/test.sh -run TestCreate ./cmd/bd/... diff --git a/.github/workflows/conformance.yml b/.github/workflows/conformance.yml index 76cfc9caf..a629b38ef 100644 --- a/.github/workflows/conformance.yml +++ b/.github/workflows/conformance.yml @@ -1,12 +1,7 @@ name: Conformance -# Runs the two-tier storage-backend conformance suite against REAL databases — -# the same scripts/conformance.sh developers run locally, so local == CI. Tier 1 -# is the in-process store suite plus the wedge gates; Tier 2 is the end-to-end -# `bd init` + CLI differential (every SQL backend compared to the Dolt reference). -# Postgres and MySQL run as service containers; Dolt (embedded) and SQLite are -# in-process. The deep bts-rs 523-scenario oracle stays on-demand (CONFORMANCE_DEEP), -# not in this per-PR job. +# Runs the same two-tier storage conformance suite developers run locally: +# the in-process store corpus and the real-binary CLI harness. on: pull_request: @@ -23,40 +18,8 @@ env: jobs: conformance: - name: Storage backend conformance (real DBs) + name: Storage backend conformance (embedded Dolt oracle) runs-on: ubuntu-latest - services: - postgres: - image: postgres:16 - env: - POSTGRES_USER: bts - POSTGRES_PASSWORD: bts - POSTGRES_DB: bdwedge - # Code-point collation parity with Dolt (utf8mb4_0900_bin). The pg backend - # provisions per-workspace SCHEMAS inside this one database and can't set - # per-column COLLATE "C" (it breaks the shared recursive CTEs; see - # internal/storage/postgres/schema.go), so byte-order parity has to be - # guaranteed at DB-creation time via a C-locale cluster. - POSTGRES_INITDB_ARGS: "--lc-collate=C --lc-ctype=C" - ports: - - 5432:5432 - options: >- - --health-cmd "pg_isready -U bts -d bdwedge" - --health-interval 5s - --health-timeout 5s - --health-retries 20 - mysql: - image: mysql:8 - env: - MYSQL_ROOT_PASSWORD: bts - MYSQL_DATABASE: bdwedge - ports: - - 3306:3306 - options: >- - --health-cmd "mysqladmin ping -uroot -pbts --silent" - --health-interval 5s - --health-timeout 5s - --health-retries 30 steps: - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v6 @@ -65,23 +28,5 @@ jobs: with: go-version-file: 'go.mod' - # The MySQL image's root only auths from localhost inside the container; the - # backend connects over TCP as a distinct host, so create a TCP-reachable user - # matching BEADS_MYSQL_TEST_URL. - - name: Provision MySQL user - run: | - mysql -h 127.0.0.1 -P 3306 -uroot -pbts -e " - CREATE USER IF NOT EXISTS 'bts'@'%' IDENTIFIED BY 'bts'; - GRANT ALL PRIVILEGES ON *.* TO 'bts'@'%' WITH GRANT OPTION; - FLUSH PRIVILEGES;" - - - name: Run conformance (Dolt + Postgres + MySQL + SQLite) - env: - BEADS_PG_TEST_URL: "postgres://bts:bts@127.0.0.1:5432/bdwedge" - BEADS_PG_PASSWORD: "bts" - BEADS_MYSQL_TEST_URL: "bts:bts@tcp(127.0.0.1:3306)/" - # Hard-fail (Tier 1 run_sql_conformance + Tier 2 e2e) if either real backend - # is absent, so removing/renaming a *_TEST_URL can't silently drop coverage - # while the gate still reports green. - BEADS_CONFORMANCE_REQUIRE: "postgres,mysql" + - name: Run conformance (embedded Dolt oracle) run: ./scripts/conformance.sh diff --git a/.golangci.yml b/.golangci.yml index 9982d481c..09cf666fb 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -158,6 +158,14 @@ linters: linters: - gosec text: "G705" + # G705: XSS via taint in CLI progress/warning/error output — every flagged + # sink is fmt.Fprint* to the terminal (os.Stderr or cobra's stdout/stderr + # writers), never a browser context (surfaced by the gosec bundled with + # golangci-lint v2.10) + - path: 'cmd/bd/(ado|doctor|errors|github|gitlab|hooks|jira|linear|main|notion|sync_push_pull)\.go' + linters: + - gosec + text: "G705" # errcheck: fmt.Fprintf errors are noise in CLI help text generation - path: 'cmd/bd/help_all\.go' linters: @@ -174,11 +182,6 @@ linters: linters: - unparam text: 'reimportConflicts|resolveConflictsByTimestamp' - # unparam: readOnly param kept for API symmetry with fix/sqlite_open.go - - path: 'cmd/bd/doctor/sqlite_open\.go' - linters: - - unparam - text: 'readOnly' # unparam: childrenMap return computed for future parent-child display - path: 'cmd/bd/list\.go' linters: diff --git a/CHANGELOG.md b/CHANGELOG.md index b94004485..f6391c4e4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- **Storage backend scope simplified** (bd-sadcd). The recently merged direct + PostgreSQL and MySQL adapters have been rolled back before entering a tagged + release. Supporting additional general-purpose server databases introduced + dialect, credential, schema-lifecycle, migration, CI, and operational + complexity at odds with our goal of keeping Beads as simple as possible and + consuming as few resources as possible. The storage interface, shared issue + core, SQLite implementation, and conformance harness remain; embedded Dolt, + Dolt server, and SQLite are the supported storage paths. Dolt server mode and + its use of the MySQL wire protocol are unchanged. Existing PostgreSQL or + MySQL workspaces stop before their configured databases are opened or + modified; see the [migration + guide](docs/architecture/storage-backends.md#existing-postgresql-or-mysql-workspaces). - **Cross-type blocking dependencies are now allowed** (bd-wg7ve, [#4034](https://github.com/gastownhall/beads/pull/4034)). `bd dep add ` — gating a work item on an epic (program) diff --git a/PROPOSAL-pluggable-storage-backends.md b/PROPOSAL-pluggable-storage-backends.md index 16e2edda3..0fc04a82d 100644 --- a/PROPOSAL-pluggable-storage-backends.md +++ b/PROPOSAL-pluggable-storage-backends.md @@ -1,6 +1,6 @@ # PROPOSAL: Pluggable Storage Backends -**Status:** Draft for review (survived one adversarial review round; defects folded in) +**Status:** Historical — partially implemented, then superseded on 2026-07-16 **Date:** 2026-07-02 **Informed by:** the bts-rs Rust spike (a from-scratch Rust reimplementation of the gc-contract surface that validated a backend-agnostic storage seam at 299/299 byte-parity @@ -8,6 +8,21 @@ across two radically different backends), a five-dimension recon of this repo's architecture, and a two-reviewer adversarial verification pass. All file:line citations verified against `worktree-beads-new`. +> **Superseded scope:** This proposal is retained as the design record for the +> storage interface, shared issue core, SQLite adapter, and differential +> conformance work that grew from it. Those pieces remain. The direct +> PostgreSQL and MySQL adapters were rolled back before entering a tagged +> release because supporting additional general-purpose server databases adds +> substantial dialect, credential, schema-lifecycle, migration, CI, and +> operational complexity. Our goal is to keep Beads as simple as possible and +> consume as few resources as possible. The supported paths are now embedded +> Dolt, Dolt server, and SQLite; Dolt server's use of the MySQL wire protocol is +> unchanged. See [Storage Backends](docs/architecture/storage-backends.md) for +> the current design. + +Everything below this notice is retained as historical design material, not as +current backend support or migration guidance. + --- ## 1. End state diff --git a/beads.go b/beads.go index 2976ce3d3..d7dea43b9 100644 --- a/beads.go +++ b/beads.go @@ -11,6 +11,7 @@ import ( "context" "github.com/steveyegge/beads/internal/beads" + "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/types" @@ -19,6 +20,15 @@ import ( // Storage is the interface for beads storage operations type Storage = beads.Storage +func configuredBackendUnavailable(backend string) error { + switch backend { + case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite: + return configfile.RemovedBackendError(backend) + default: + return configfile.UnknownBackendError(backend) + } +} + // Transaction provides atomic multi-operation support within a database transaction. // Use Storage.RunInTransaction() to obtain a Transaction instance. type Transaction = beads.Transaction @@ -64,9 +74,9 @@ func Open(ctx context.Context, dbPath string) (Storage, error) { return dolt.New(ctx, &dolt.Config{Path: dbPath, CreateIfMissing: true}) } -// OpenFromConfig opens a beads database using configuration from metadata.json. -// Unlike Open, this respects Dolt server mode settings and database name -// configuration, connecting to the Dolt SQL server when dolt_mode is "server". +// OpenFromConfig opens the Dolt implementation using configuration from +// metadata.json. Unlike Open, this respects Dolt server mode settings and database +// name configuration. // beadsDir is the path to the .beads directory. func OpenFromConfig(ctx context.Context, beadsDir string) (Storage, error) { return dolt.NewFromConfigWithOptions(ctx, beadsDir, &dolt.Config{CreateIfMissing: true}) diff --git a/beads_cgo.go b/beads_cgo.go index a5736e73c..e63bc0742 100644 --- a/beads_cgo.go +++ b/beads_cgo.go @@ -4,6 +4,7 @@ package beads import ( "context" + "fmt" "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/storage/dolt" @@ -14,15 +15,25 @@ import ( // for the given .beads directory. It reads metadata.json to determine the // configured mode: // -// - Embedded mode (default): Opens via the CGo embedded Dolt engine. -// - Server mode: Connects to an external dolt sql-server via OpenFromConfig. +// - Embedded Dolt (default): Opens via the CGo embedded Dolt engine. +// - Dolt server: Connects to a dolt sql-server via OpenFromConfig. // // The returned Storage must be closed when no longer needed. // // beadsDir is the path to the .beads directory. func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) { cfg, err := configfile.Load(beadsDir) - if err == nil && cfg != nil && cfg.IsDoltServerMode() { + if err != nil { + return nil, fmt.Errorf("loading storage metadata: %w", err) + } + if cfg == nil { + cfg = configfile.DefaultConfig() + } + if !configfile.IsSupportedBackend(cfg.Backend) { + return nil, configuredBackendUnavailable(cfg.Backend) + } + + if cfg.IsDoltServerMode() { store, err := dolt.NewFromConfig(ctx, beadsDir) if err != nil { return nil, err diff --git a/beads_nocgo.go b/beads_nocgo.go index 58ebdab77..b5afdd83b 100644 --- a/beads_nocgo.go +++ b/beads_nocgo.go @@ -11,13 +11,23 @@ import ( ) // OpenBestAvailable opens a beads database using the best available backend -// for the given .beads directory. In non-CGO builds, only server mode is -// supported; embedded mode returns an error directing the user to server mode. +// for the given .beads directory. In non-CGO builds, only Dolt server mode is +// supported; embedded Dolt returns an error directing the user to server mode. // // beadsDir is the path to the .beads directory. func OpenBestAvailable(ctx context.Context, beadsDir string) (Storage, error) { cfg, err := configfile.Load(beadsDir) - if err == nil && cfg != nil && cfg.IsDoltServerMode() { + if err != nil { + return nil, fmt.Errorf("loading storage metadata: %w", err) + } + if cfg == nil { + cfg = configfile.DefaultConfig() + } + if !configfile.IsSupportedBackend(cfg.Backend) { + return nil, configuredBackendUnavailable(cfg.Backend) + } + + if cfg.IsDoltServerMode() { store, err := dolt.NewFromConfig(ctx, beadsDir) if err != nil { return nil, err diff --git a/cmd/bd/backend_support.go b/cmd/bd/backend_support.go new file mode 100644 index 000000000..52977054e --- /dev/null +++ b/cmd/bd/backend_support.go @@ -0,0 +1,45 @@ +package main + +import ( + "fmt" + + "github.com/steveyegge/beads/internal/configfile" +) + +func validateConfiguredBackend(cfg *configfile.Config) error { + if cfg == nil { + return nil + } + switch cfg.Backend { + case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite: + return configfile.RemovedBackendError(cfg.Backend) + case "", configfile.BackendDolt: + return nil + default: + return configfile.UnknownBackendError(cfg.Backend) + } +} + +func requireDoltBackend(cfg *configfile.Config) error { + if err := validateConfiguredBackend(cfg); err != nil { + return err + } + if cfg != nil && cfg.GetBackend() != configfile.BackendDolt { + return fmt.Errorf("not using Dolt backend (configured backend %q)", cfg.GetBackend()) + } + return nil +} + +func loadDoltBackendConfig(beadsDir string) (*configfile.Config, error) { + cfg, err := configfile.Load(beadsDir) + if err != nil { + return nil, fmt.Errorf("loading config: %w", err) + } + if cfg == nil { + cfg = configfile.DefaultConfig() + } + if err := requireDoltBackend(cfg); err != nil { + return nil, err + } + return cfg, nil +} diff --git a/cmd/bd/bootstrap.go b/cmd/bd/bootstrap.go index 3d0db9667..e06e29ecd 100644 --- a/cmd/bd/bootstrap.go +++ b/cmd/bd/bootstrap.go @@ -191,12 +191,21 @@ Examples: // name (e.g. dolt_database). Without this, server-mode rigs get the // default name "beads" instead of their configured name. (GH#3029) cfg, err := configfile.Load(beadsDir) - if err != nil || cfg == nil { - cfg = findParentConfig(beadsDir) + if err != nil { + return HandleError("failed to load %s: %v; no storage database was opened or modified; fix or restore metadata.json and retry", configfile.ConfigPath(beadsDir), err) + } + if cfg == nil { + cfg, err = findParentConfig(beadsDir) + if err != nil { + return HandleError("failed to load ancestor storage metadata: %v; no storage database was opened or modified; fix or restore metadata.json and retry", err) + } } if cfg == nil { cfg = configfile.DefaultConfig() } + if err := requireBootstrapDoltBackend(cfg); err != nil { + return HandleError("%v", err) + } resolvedCfg, repairMsg, err := applyBootstrapMetadataRepair(beadsDir, cfg, !dryRun) if err != nil { @@ -270,6 +279,13 @@ func noWorkspaceBootstrapPayload() map[string]interface{} { } } +func requireBootstrapDoltBackend(cfg *configfile.Config) error { + if err := validateConfiguredBackend(cfg); err != nil { + return err + } + return nil +} + func detectBootstrapAction(beadsDir string, cfg *configfile.Config) BootstrapPlan { plan := BootstrapPlan{ BeadsDir: beadsDir, @@ -513,6 +529,9 @@ func confirmPrompt(message string, nonInteractive bool) bool { } func executeBootstrapPlan(plan BootstrapPlan, cfg *configfile.Config, nonInteractive bool) error { + if err := requireBootstrapDoltBackend(cfg); err != nil { + return err + } if !confirmPrompt("Proceed?", nonInteractive) { fmt.Fprintf(os.Stderr, "Aborted.\n") return nil @@ -955,8 +974,10 @@ func isNonInteractiveBootstrap(flagValue bool) bool { // findParentConfig walks up from beadsDir's parent looking for a // .beads/metadata.json in ancestor directories. This handles the case where a // rig subdirectory (its own git repo) doesn't have a local .beads but its -// parent workspace does. Returns nil if no parent config is found. -func findParentConfig(beadsDir string) *configfile.Config { +// parent workspace does. Returns nil if no parent config is found. A malformed +// or unreadable ancestor metadata file is authoritative and returned as an error; +// bootstrap must not skip it and select a more distant workspace or defaults. +func findParentConfig(beadsDir string) (*configfile.Config, error) { // Start from the parent of beadsDir's enclosing directory. // beadsDir is typically "/.beads", so we start from 's parent. start := filepath.Dir(filepath.Dir(beadsDir)) @@ -964,8 +985,12 @@ func findParentConfig(beadsDir string) *configfile.Config { for dir := start; dir != "/" && dir != "."; { candidate := filepath.Join(dir, ".beads") - if cfg, err := configfile.Load(candidate); err == nil && cfg != nil { - return cfg + cfg, err := configfile.Load(candidate) + if err != nil { + return nil, fmt.Errorf("%s: %w", configfile.ConfigPath(candidate), err) + } + if cfg != nil { + return cfg, nil } // Don't search above $HOME @@ -979,7 +1004,7 @@ func findParentConfig(beadsDir string) *configfile.Config { } dir = parent } - return nil + return nil, nil } func init() { diff --git a/cmd/bd/bootstrap_backend_guard_test.go b/cmd/bd/bootstrap_backend_guard_test.go new file mode 100644 index 000000000..238602a1d --- /dev/null +++ b/cmd/bd/bootstrap_backend_guard_test.go @@ -0,0 +1,295 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/configfile" +) + +func TestBootstrapRejectsRemovedBackendsBeforeWorkspaceWrites(t *testing.T) { + bd := buildBDForInitTests(t) + + for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} { + backend := backend + for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} { + args := args + mode := "execute" + if len(args) > 1 && args[1] == "--dry-run" { + mode = "dry-run" + } + + t.Run(backend+"/"+mode, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + + metadata := []byte(fmt.Sprintf("{\n \"database\": \"legacy.db\",\n \"backend\": %q,\n \"project_id\": \"legacy-project\"\n}\n", backend)) + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil { + t.Fatalf("write metadata.json: %v", err) + } + + cmd := exec.Command(bd, args...) + cmd.Dir = root + cmd.Env = bootstrapBackendGuardEnv(root, beadsDir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Errorf("bd %s unexpectedly succeeded for removed backend %q:\n%s", strings.Join(args, " "), backend, out) + } + + message := strings.ToLower(string(out)) + for _, want := range removedBackendWantSubstrings(backend) { + if !strings.Contains(message, want) { + t.Errorf("bd %s error for %q missing %q:\n%s", strings.Join(args, " "), backend, want, message) + } + } + + after, readErr := os.ReadFile(metadataPath) + if readErr != nil { + t.Fatalf("read metadata.json after rejected bootstrap: %v", readErr) + } + if !bytes.Equal(after, metadata) { + t.Errorf("bd %s rewrote metadata.json for removed backend %q:\nbefore:\n%s\nafter:\n%s", strings.Join(args, " "), backend, metadata, after) + } + assertNoBootstrapStorageArtifacts(t, beadsDir) + }) + } + } +} + +func TestBootstrapRejectsUnknownBackendBeforeWorkspaceWrites(t *testing.T) { + bd := buildBDForInitTests(t) + + for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} { + mode := "execute" + if args[1] == "--dry-run" { + mode = "dry-run" + } + + t.Run(mode, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + + metadata := []byte("{\n \"backend\": \"mystery\",\n \"project_id\": \"legacy-project\"\n}\n") + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil { + t.Fatalf("write metadata.json: %v", err) + } + + cmd := exec.Command(bd, args...) + cmd.Dir = root + cmd.Env = bootstrapBackendGuardEnv(root, beadsDir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Errorf("bd %s unexpectedly accepted an unknown backend:\n%s", strings.Join(args, " "), out) + } + message := string(out) + for _, want := range []string{"not recognized", "no storage database was opened or modified", "dolt"} { + if !strings.Contains(message, want) { + t.Errorf("bd %s error missing %q:\n%s", strings.Join(args, " "), want, message) + } + } + + after, readErr := os.ReadFile(metadataPath) + if readErr != nil { + t.Fatalf("read metadata.json after rejected bootstrap: %v", readErr) + } + if !bytes.Equal(after, metadata) { + t.Errorf("bd %s rewrote unknown-backend metadata:\nbefore:\n%s\nafter:\n%s", strings.Join(args, " "), metadata, after) + } + assertNoBootstrapStorageArtifacts(t, beadsDir) + }) + } +} + +func TestBootstrapRejectsCorruptMetadataBeforeWorkspaceWrites(t *testing.T) { + bd := buildBDForInitTests(t) + + for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} { + mode := "execute" + if args[1] == "--dry-run" { + mode = "dry-run" + } + + t.Run(mode, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + + metadata := []byte("{\n") + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil { + t.Fatalf("write corrupt metadata.json: %v", err) + } + + cmd := exec.Command(bd, args...) + cmd.Dir = root + cmd.Env = bootstrapBackendGuardEnv(root, beadsDir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("bd %s unexpectedly ignored corrupt metadata:\n%s", strings.Join(args, " "), out) + } + message := strings.ToLower(string(out)) + for _, want := range []string{"metadata.json", "no storage database was opened or modified"} { + if !strings.Contains(message, want) { + t.Errorf("bd %s error missing %q:\n%s", strings.Join(args, " "), want, out) + } + } + + after, readErr := os.ReadFile(metadataPath) + if readErr != nil { + t.Fatalf("read corrupt metadata after rejected bootstrap: %v", readErr) + } + if !bytes.Equal(after, metadata) { + t.Errorf("bd %s rewrote corrupt metadata:\nbefore: %q\nafter: %q", strings.Join(args, " "), metadata, after) + } + assertNoBootstrapStorageArtifacts(t, beadsDir) + }) + } +} + +func TestBootstrapDoesNotConvertExistingSQLiteWorkspace(t *testing.T) { + bd := buildBDForInitTests(t) + + for _, args := range [][]string{{"bootstrap", "--dry-run"}, {"bootstrap", "--yes"}} { + args := args + mode := "execute" + if len(args) > 1 && args[1] == "--dry-run" { + mode = "dry-run" + } + + t.Run(mode, func(t *testing.T) { + root := t.TempDir() + for _, gitArgs := range [][]string{ + {"init", "-q"}, + {"config", "user.email", "test@test.com"}, + {"config", "user.name", "Test"}, + {"config", "core.hooksPath", ".git/hooks"}, + } { + runGitForBootstrapTest(t, root, gitArgs...) + } + + // Hand-seed a workspace created by an earlier build's SQLite backend: + // metadata selecting the removed backend plus its database file. The + // guard must reject it without reading or rewriting either. + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + metadataBefore := []byte("{\n \"database\": \"beads.db\",\n \"backend\": \"sqlite\",\n \"sqlite_path\": \"beads.db\",\n \"project_id\": \"sqlite-guard\"\n}\n") + if err := os.WriteFile(metadataPath, metadataBefore, 0o600); err != nil { + t.Fatalf("write metadata.json: %v", err) + } + databasePath := filepath.Join(beadsDir, "beads.db") + databaseContent := []byte("sqlite-guard database placeholder") + if err := os.WriteFile(databasePath, databaseContent, 0o600); err != nil { + t.Fatalf("write beads.db: %v", err) + } + databaseBefore := sha256.Sum256(databaseContent) + localVersionBefore, hadLocalVersion := readOptionalBootstrapGuardFile(t, filepath.Join(beadsDir, ".local_version")) + + cmd := exec.Command(bd, args...) + cmd.Dir = root + cmd.Env = bootstrapBackendGuardEnv(root, beadsDir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Errorf("bd %s unexpectedly accepted an existing SQLite workspace:\n%s", strings.Join(args, " "), out) + } + + message := strings.ToLower(string(out)) + if !strings.Contains(message, "sqlite") { + t.Errorf("bd %s should name the rejected backend:\n%s", strings.Join(args, " "), out) + } + for _, want := range removedBackendWantSubstrings(configfile.BackendSQLite) { + if !strings.Contains(message, want) { + t.Errorf("bd %s error missing %q:\n%s", strings.Join(args, " "), want, out) + } + } + + metadataAfter := readBootstrapGuardFile(t, metadataPath) + if !bytes.Equal(metadataAfter, metadataBefore) { + t.Errorf("bd %s rewrote SQLite metadata.json:\nbefore:\n%s\nafter:\n%s", strings.Join(args, " "), metadataBefore, metadataAfter) + } + databaseAfter := sha256.Sum256(readBootstrapGuardFile(t, databasePath)) + if databaseAfter != databaseBefore { + t.Errorf("bd %s modified the existing SQLite database", strings.Join(args, " ")) + } + localVersionAfter, hasLocalVersion := readOptionalBootstrapGuardFile(t, filepath.Join(beadsDir, ".local_version")) + if hasLocalVersion != hadLocalVersion || !bytes.Equal(localVersionAfter, localVersionBefore) { + t.Errorf("bd %s created or modified SQLite workspace version tracking", strings.Join(args, " ")) + } + for _, name := range []string{"embeddeddolt", "dolt"} { + path := filepath.Join(beadsDir, name) + if _, statErr := os.Stat(path); !os.IsNotExist(statErr) { + t.Errorf("bd %s converted SQLite by creating Dolt state at %s (stat error: %v)", strings.Join(args, " "), path, statErr) + } + } + }) + } +} + +func bootstrapBackendGuardEnv(home, beadsDir string) []string { + env := make([]string, 0, len(os.Environ())+7) + for _, entry := range os.Environ() { + if strings.HasPrefix(entry, "BEADS_") || strings.HasPrefix(entry, "BD_") || strings.HasPrefix(entry, "HOME=") { + continue + } + env = append(env, entry) + } + return append(env, + "HOME="+home, + "BEADS_DIR="+beadsDir, + "BEADS_DOLT_AUTO_START=0", + "BEADS_NO_DAEMON=1", + "BEADS_TEST_IGNORE_REPO_CONFIG=1", + "BD_DISABLE_METRICS=1", + "BD_DISABLE_EVENT_FLUSH=1", + "BD_NON_INTERACTIVE=1", + ) +} + +func assertNoBootstrapStorageArtifacts(t *testing.T, beadsDir string) { + t.Helper() + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} { + path := filepath.Join(beadsDir, name) + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("rejected bootstrap created local state at %s (stat error: %v)", path, err) + } + } +} + +func readBootstrapGuardFile(t *testing.T, path string) []byte { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return data +} + +func readOptionalBootstrapGuardFile(t *testing.T, path string) ([]byte, bool) { + t.Helper() + data, err := os.ReadFile(path) + if os.IsNotExist(err) { + return nil, false + } + if err != nil { + t.Fatalf("read %s: %v", path, err) + } + return data, true +} diff --git a/cmd/bd/bootstrap_test.go b/cmd/bd/bootstrap_test.go index 92be0d074..f274caed2 100644 --- a/cmd/bd/bootstrap_test.go +++ b/cmd/bd/bootstrap_test.go @@ -919,7 +919,10 @@ func TestBootstrapRigSubdirUsesParentDBName(t *testing.T) { cfg, cfgErr := configfile.Load(synthesizedDir) if cfgErr != nil || cfg == nil { // This is the fix path: search parent directories for metadata.json - cfg = findParentConfig(synthesizedDir) + cfg, cfgErr = findParentConfig(synthesizedDir) + if cfgErr != nil { + t.Fatalf("findParentConfig: %v", cfgErr) + } } if cfg == nil { cfg = configfile.DefaultConfig() @@ -939,6 +942,37 @@ func TestBootstrapRigSubdirUsesParentDBName(t *testing.T) { } } +func TestFindParentConfigDoesNotSkipCorruptNearestAncestor(t *testing.T) { + root := t.TempDir() + higherBeadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(higherBeadsDir, 0o750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(higherBeadsDir, "metadata.json"), []byte(`{"dolt_database":"wrong_higher_database"}`), 0o600); err != nil { + t.Fatal(err) + } + + nearestBeadsDir := filepath.Join(root, "workspace", ".beads") + if err := os.MkdirAll(nearestBeadsDir, 0o750); err != nil { + t.Fatal(err) + } + corrupt := []byte("{\n") + metadataPath := filepath.Join(nearestBeadsDir, "metadata.json") + if err := os.WriteFile(metadataPath, corrupt, 0o600); err != nil { + t.Fatal(err) + } + + synthesizedDir := filepath.Join(root, "workspace", "rig", ".beads") + if cfg, err := findParentConfig(synthesizedDir); err == nil { + t.Fatalf("findParentConfig skipped corrupt nearest metadata and selected higher database %q", cfg.GetDoltDatabase()) + } else if !strings.Contains(err.Error(), filepath.Join("workspace", ".beads", "metadata.json")) { + t.Fatalf("findParentConfig error = %v, want nearest metadata path", err) + } + if after, err := os.ReadFile(metadataPath); err != nil || string(after) != string(corrupt) { + t.Fatalf("corrupt nearest metadata changed: got %q, err %v", after, err) + } +} + // TestDetectBootstrapAction_SharedServerEnvUsesSharedPath verifies that when // BEADS_DOLT_SHARED_SERVER=1 is set but cfg.DoltMode is the default (embedded), // detectBootstrapAction looks in the shared-server directory — not embeddeddolt/. @@ -1052,7 +1086,10 @@ func TestDetectBootstrapAction_WorktreeSynthesizedDirPrefersSyncOverDefaultShare synthesizedDir := filepath.Join(localBare, ".beads") cfg, cfgErr := configfile.Load(synthesizedDir) if cfgErr != nil || cfg == nil { - cfg = findParentConfig(synthesizedDir) + cfg, cfgErr = findParentConfig(synthesizedDir) + if cfgErr != nil { + t.Fatalf("findParentConfig: %v", cfgErr) + } } if cfg == nil { cfg = configfile.DefaultConfig() diff --git a/cmd/bd/doctor.go b/cmd/bd/doctor.go index 43bb0e5b3..9be970f4b 100644 --- a/cmd/bd/doctor.go +++ b/cmd/bd/doctor.go @@ -84,10 +84,17 @@ This command checks: - .beads/.gitignore up to date - Metadata.json version tracking (LastBdVersion field) +Storage Availability: + Full diagnostics, --perf, --deep, --server, --migration, and + --check=validate currently require Dolt server mode. Embedded Dolt + supports --check=artifacts, --check=conventions, and + --check=pollution. --check-health has a limited hook-health fallback. + Unsupported combinations return a notice without changing storage. + Performance Mode (--perf): Run performance diagnostics on your database: - Times key operations (bd ready, bd list, bd show, etc.) - - Collects system info (OS, arch, SQLite version, database stats) + - Collects system info (OS, arch, database stats) - Generates CPU profile for analysis - Outputs shareable report for bug reports @@ -123,18 +130,12 @@ Server Mode (--server): - Schema compatible: Can query beads tables? - Connection pool: Pool health metrics -Migration Validation Mode (--migration): - Run Dolt migration validation checks with machine-parseable output. - Use --migration=pre before migration to verify readiness: - - JSONL file exists and is valid (parseable, no corruption) - - All JSONL issues are present in SQLite (or explains discrepancies) - - No blocking issues prevent migration - Use --migration=post after migration to verify completion: - - Dolt database exists and is healthy - - All issues from JSONL are present in Dolt - - No data was lost during migration - - Dolt database has no locks or uncommitted changes - Combine with --json for machine-parseable output for automation. +Legacy Dolt Migration Validation Mode (--migration): + Retained for older SQLite-to-Dolt migration workflows and available only in + Dolt server mode. It is not the migration path for removed backends + (PostgreSQL, MySQL, SQLite); those fail closed with export/import guidance. + Combine + with --json for machine-parseable diagnostic output. Agent Mode (--agent): Output diagnostics designed for AI agent consumption. Instead of terse @@ -181,9 +182,9 @@ Examples: bd doctor --check=validate --fix # Auto-fix data-integrity issues bd doctor --deep # Full graph integrity validation bd doctor --server # Dolt server mode health checks - bd doctor --migration=pre # Validate readiness for Dolt migration - bd doctor --migration=post # Validate Dolt migration completed - bd doctor --migration=pre --json # Machine-parseable migration validation`, + bd doctor --migration=pre # Legacy Dolt-server migration diagnostic + bd doctor --migration=post # Legacy Dolt-server completion diagnostic + bd doctor --migration=pre --json # Machine-parseable legacy diagnostic`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { @@ -194,11 +195,6 @@ Examples: } }() - if usesProxiedServer() { - fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in proxied-server mode.") - return nil - } - var checkPath string if len(args) > 0 { checkPath = args[0] @@ -212,6 +208,14 @@ Examples: if err != nil { return HandleError("failed to resolve path: %v", err) } + if err := validateDoctorWorkspaceBackend(absPath); err != nil { + return HandleError("%v", err) + } + + if usesProxiedServer() { + fmt.Fprintln(os.Stderr, "Note: 'bd doctor' is not yet supported in proxied-server mode.") + return nil + } if doctorFix && isOrchestratorRoot(absPath) { return HandleErrorWithHint( @@ -340,7 +344,7 @@ func init() { doctorCmd.Flags().BoolVar(&doctorOrchestrator, "orchestrator", false, "Running in orchestrator multi-workspace mode (routes.jsonl is expected, higher duplicate tolerance)") doctorCmd.Flags().IntVar(&orchestratorDuplicatesThreshold, "orchestrator-duplicates-threshold", 1000, "Duplicate tolerance threshold for orchestrator mode (wisps are ephemeral)") doctorCmd.Flags().BoolVar(&doctorServer, "server", false, "Run Dolt server mode health checks (connectivity, version, schema)") - doctorCmd.Flags().StringVar(&doctorMigration, "migration", "", "Run Dolt migration validation: 'pre' (before migration) or 'post' (after migration)") + doctorCmd.Flags().StringVar(&doctorMigration, "migration", "", "Run legacy Dolt-server migration diagnostics: 'pre' or 'post'") doctorCmd.Flags().BoolVar(&doctorAgent, "agent", false, "Agent-facing diagnostic mode: rich context for AI agents (ZFC-compliant)") } @@ -348,6 +352,19 @@ func shouldSkipDoctorNetworkChecks() bool { return jsonOutput || !ui.IsTerminal() } +// validateDoctorWorkspaceBackend keeps doctor diagnostics read-only when metadata +// selects a removed or unknown implementation or cannot be parsed. Doctor contains +// direct diagnostic store paths and may run under shared-server mode, so corrupt +// metadata must be rejected before version tracking or any database check begins. +func validateDoctorWorkspaceBackend(path string) error { + beadsDir := doctor.ResolveBeadsDirForRepo(path) + cfg, err := configfile.Load(beadsDir) + if err != nil { + return fmt.Errorf("failed to load %s: %w; no storage database was opened or modified; fix or restore metadata.json and retry", configfile.ConfigPath(beadsDir), err) + } + return validateConfiguredBackend(cfg) +} + // printEmbeddedUnsupported reports that a doctor variant is not yet wired up // for embedded mode. Emits a structured payload to stderr when --json or // --agent is set so downstream tooling can detect the gap without parsing diff --git a/cmd/bd/doctor/deep.go b/cmd/bd/doctor/deep.go index 21f06fc07..a120fafc0 100644 --- a/cmd/bd/doctor/deep.go +++ b/cmd/bd/doctor/deep.go @@ -43,9 +43,8 @@ func RunDeepValidation(path string) DeepValidationResult { check := DoctorCheck{ Name: "Deep Validation", Status: StatusWarning, - Message: "SQLite backend detected", + Message: fmt.Sprintf("N/A (deep validation requires Dolt; configured backend is %q)", backend), Category: CategoryMaintenance, - Fix: "Run 'bd init' to set up Dolt backend", } result.AllChecks = append(result.AllChecks, check) return result diff --git a/cmd/bd/doctor/deep_test.go b/cmd/bd/doctor/deep_test.go index 1e7c36361..0cc06b6cc 100644 --- a/cmd/bd/doctor/deep_test.go +++ b/cmd/bd/doctor/deep_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/steveyegge/beads/internal/configfile" "github.com/steveyegge/beads/internal/types" ) @@ -45,6 +46,26 @@ func TestRunDeepValidation_EmptyBeadsDir(t *testing.T) { } } +func TestRunDeepValidationSQLiteIsNotAMigrationWarning(t *testing.T) { + tmpDir := t.TempDir() + beadsDir := filepath.Join(tmpDir, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + if err := (&configfile.Config{Backend: configfile.BackendSQLite, SQLitePath: "beads.db"}).Save(beadsDir); err != nil { + t.Fatalf("save SQLite config: %v", err) + } + + result := RunDeepValidation(tmpDir) + if len(result.AllChecks) != 1 { + t.Fatalf("SQLite deep-validation result = %#v, want one N/A check", result) + } + check := result.AllChecks[0] + if check.Status != StatusWarning || !strings.Contains(check.Message, "sqlite") || check.Fix != "" { + t.Fatalf("SQLite deep-validation check = %#v, want non-Dolt N/A without migration fix", check) + } +} + // TestCheckParentConsistency_OrphanedDeps verifies detection of orphaned parent-child deps func TestCheckParentConsistency_OrphanedDeps(t *testing.T) { store := newTestDoltStore(t, "bd") diff --git a/cmd/bd/doctor/dolt.go b/cmd/bd/doctor/dolt.go index 81c49111c..2290a5be9 100644 --- a/cmd/bd/doctor/dolt.go +++ b/cmd/bd/doctor/dolt.go @@ -101,9 +101,10 @@ func openDoltConn(beadsDir string) (*doltConn, error) { return &doltConn{db: db, cfg: cfg, port: port}, nil } -// GetBackend returns the configured backend type from configuration. -// It checks config.yaml first (storage-backend key), then falls back to metadata.json. -// Returns "dolt" (default) or "sqlite" (legacy). +// GetBackend returns the configured backend type from metadata.json. An absent +// or empty backend field reads as "dolt" (the default); removed-backend +// tombstones ("postgres", "mysql", "sqlite") are returned verbatim so callers +// can label them without opening anything. // hq-3446fc.17: Use dolt.GetBackendFromConfig for consistent backend detection. func GetBackend(beadsDir string) string { return dolt.GetBackendFromConfig(beadsDir) @@ -126,13 +127,13 @@ func runDoltHealthChecksInternal(path string) []DoctorCheck { if !IsDoltBackend(beadsDir) { return []DoctorCheck{ - {Name: "Dolt Connection", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryCore}, - {Name: "Dolt Schema", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryCore}, - {Name: "Dolt Issue Count", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryData}, - {Name: "Dolt Status", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryData}, - {Name: "Dolt Lock Health", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryRuntime}, - {Name: "Phantom Databases", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryData}, - {Name: "Shared Server", Status: StatusOK, Message: "N/A (SQLite backend)", Category: CategoryRuntime}, + {Name: "Dolt Connection", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryCore}, + {Name: "Dolt Schema", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryCore}, + {Name: "Dolt Issue Count", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryData}, + {Name: "Dolt Status", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryData}, + {Name: "Dolt Lock Health", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryRuntime}, + {Name: "Phantom Databases", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryData}, + {Name: "Shared Server", Status: StatusOK, Message: "N/A (non-Dolt backend)", Category: CategoryRuntime}, } } diff --git a/cmd/bd/doctor/dolt_e2e_test.go b/cmd/bd/doctor/dolt_e2e_test.go index 080323fd7..22d3f6831 100644 --- a/cmd/bd/doctor/dolt_e2e_test.go +++ b/cmd/bd/doctor/dolt_e2e_test.go @@ -274,7 +274,7 @@ func runBDDoctor(t *testing.T, bdPath, path string) (e2eDoctorResult, string, er return result, string(out), execErr } -// TestE2E_DoctorSQLiteBackend was removed: SQLite backend no longer exists. +// TestE2E_DoctorSQLiteBackend is covered by the backend-neutral doctor tests. // GetBackend() always returns "dolt" after the dolt-native cleanup (bd-yqpwy). // TestE2E_DoctorDoltBackendNoDB was removed: the embedded Dolt driver diff --git a/cmd/bd/doctor/legacy.go b/cmd/bd/doctor/legacy.go index dc473a290..91892fcba 100644 --- a/cmd/bd/doctor/legacy.go +++ b/cmd/bd/doctor/legacy.go @@ -508,7 +508,7 @@ func CheckFreshClone(repoPath string) DoctorCheck { return freshCloneServerUnreachableResult(dbName, host, port, result.Err) } default: - // SQLite (default): check configured .db file path. + // Non-Dolt (legacy sqlite-era metadata): check configured .db file path. var dbPath string if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil && cfg.Database != "" { dbPath = cfg.DatabasePath(beadsDir) diff --git a/cmd/bd/doctor/migration_validation.go b/cmd/bd/doctor/migration_validation.go index 13acdecc5..7e682d13c 100644 --- a/cmd/bd/doctor/migration_validation.go +++ b/cmd/bd/doctor/migration_validation.go @@ -148,7 +148,7 @@ func CheckMigrationReadiness(path string) (DoctorCheck, MigrationValidationResul Status: status, Message: message, Detail: strings.Join(result.Warnings, "\n"), - Fix: "Run 'bd migrate dolt' to start migration", + Fix: "Follow 'bd help init-safety' to reinitialize with Dolt, then import and verify this JSONL export", Category: CategoryMaintenance, }, result } @@ -195,7 +195,7 @@ func CheckMigrationCompletion(path string) (DoctorCheck, MigrationValidationResu Status: StatusError, Message: "Not using Dolt backend", Detail: fmt.Sprintf("Current backend: %s", result.Backend), - Fix: "Run 'bd migrate dolt' to migrate to Dolt", + Fix: "Follow 'bd help init-safety' to reinitialize with Dolt, then import and verify the issue export", Category: CategoryMaintenance, }, result } @@ -302,7 +302,7 @@ func CheckMigrationCompletion(path string) (DoctorCheck, MigrationValidationResu Status: StatusError, Message: fmt.Sprintf("Migration incomplete: %d error(s)", len(result.Errors)), Detail: strings.Join(result.Errors, "\n"), - Fix: "Re-run 'bd migrate dolt' or check for data issues", + Fix: "Check the export/import results; follow 'bd help init-safety' before reinitializing again", Category: CategoryMaintenance, }, result } diff --git a/cmd/bd/doctor/migration_validation_test.go b/cmd/bd/doctor/migration_validation_test.go index 001b93bb0..45ca66829 100644 --- a/cmd/bd/doctor/migration_validation_test.go +++ b/cmd/bd/doctor/migration_validation_test.go @@ -6,6 +6,7 @@ import ( "context" "os" "path/filepath" + "strings" "testing" ) @@ -135,13 +136,14 @@ func TestCheckMigrationReadinessResult_NoJSONL(t *testing.T) { if err := os.MkdirAll(beadsDir, 0755); err != nil { t.Fatalf("failed to create .beads: %v", err) } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"sqlite","sqlite_path":"issues.db"}`), 0644); err != nil { + t.Fatalf("failed to create SQLite metadata: %v", err) + } check, _ := CheckMigrationReadiness(tmpDir) - // With Dolt-only backend, GetBackend defaults to BackendDolt, - // so migration readiness returns OK ("Already using Dolt backend") - if check.Status != StatusOK { - t.Errorf("status = %q, want %q (Dolt-only backend returns OK)", check.Status, StatusOK) + if check.Status != StatusError { + t.Errorf("status = %q, want %q", check.Status, StatusError) } } @@ -156,6 +158,9 @@ func TestCheckMigrationReadinessResult_ValidJSONL(t *testing.T) { if err := os.MkdirAll(beadsDir, 0755); err != nil { t.Fatalf("failed to create .beads: %v", err) } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"sqlite","sqlite_path":"issues.db"}`), 0644); err != nil { + t.Fatalf("failed to create SQLite metadata: %v", err) + } // Create valid JSONL jsonl := `{"id":"bd-001","title":"Test 1"}` + "\n" + `{"id":"bd-002","title":"Test 2"}` @@ -165,12 +170,15 @@ func TestCheckMigrationReadinessResult_ValidJSONL(t *testing.T) { check, _ := CheckMigrationReadiness(tmpDir) - // With Dolt-only backend, GetBackend defaults to BackendDolt, - // so migration readiness returns OK ("Already using Dolt backend") - // without validating JSONL (no migration needed) if check.Status == StatusError { t.Errorf("status = %q, did not want error", check.Status) } + if !strings.Contains(check.Fix, "bd help init-safety") { + t.Errorf("fix must point to safe reinitialization guidance, got %q", check.Fix) + } + if strings.Contains(check.Fix, "bd migrate dolt") { + t.Errorf("fix must not recommend removed backend-conversion command, got %q", check.Fix) + } } func TestCheckMigrationCompletionResult_NoBeadsDir(t *testing.T) { @@ -206,6 +214,9 @@ func TestCheckMigrationCompletionResult_NotDoltBackend(t *testing.T) { if err := os.MkdirAll(beadsDir, 0755); err != nil { t.Fatalf("failed to create .beads: %v", err) } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"sqlite","sqlite_path":"issues.db"}`), 0644); err != nil { + t.Fatalf("failed to create SQLite metadata: %v", err) + } // Create JSONL (no Dolt backend present) jsonl := `{"id":"bd-001","title":"Test 1"}` @@ -226,6 +237,12 @@ func TestCheckMigrationCompletionResult_NotDoltBackend(t *testing.T) { if len(result.Errors) == 0 { t.Error("expected errors in result") } + if !strings.Contains(check.Fix, "bd help init-safety") { + t.Errorf("fix must point to safe reinitialization guidance, got %q", check.Fix) + } + if strings.Contains(check.Fix, "bd migrate dolt") { + t.Errorf("fix must not recommend removed backend-conversion command, got %q", check.Fix) + } } func TestMigrationValidationResult_JSONSerialization(t *testing.T) { diff --git a/cmd/bd/doctor/perf_dolt.go b/cmd/bd/doctor/perf_dolt.go index fd236e41f..686343478 100644 --- a/cmd/bd/doctor/perf_dolt.go +++ b/cmd/bd/doctor/perf_dolt.go @@ -49,7 +49,8 @@ func RunDoltPerformanceDiagnostics(path string, enableProfiling bool) (*DoltPerf // Verify this is a Dolt backend if !IsDoltBackend(beadsDir) { - return nil, fmt.Errorf("SQLite backend is no longer supported. Migrate to Dolt with 'bd migrate'") + backend, _ := getBackendAndBeadsDir(path) + return nil, fmt.Errorf("Dolt server performance diagnostics do not apply to the configured backend %q", backend) } metrics := &DoltPerfMetrics{ diff --git a/cmd/bd/doctor/perf_dolt_test.go b/cmd/bd/doctor/perf_dolt_test.go index 80ae52262..78fb2978d 100644 --- a/cmd/bd/doctor/perf_dolt_test.go +++ b/cmd/bd/doctor/perf_dolt_test.go @@ -40,3 +40,24 @@ func TestRunDoltPerformanceDiagnostics_RequiresServer(t *testing.T) { t.Errorf("expected server/database error, got: %v", err) } } + +func TestRunDoltPerformanceDiagnosticsDeclineNonDoltBackend(t *testing.T) { + tmpDir := t.TempDir() + beadsDir := filepath.Join(tmpDir, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + cfg := &configfile.Config{Backend: configfile.BackendSQLite, SQLitePath: "beads.db"} + if err := cfg.Save(beadsDir); err != nil { + t.Fatalf("save SQLite config: %v", err) + } + + _, err := RunDoltPerformanceDiagnostics(tmpDir, false) + if err == nil { + t.Fatal("expected Dolt-only diagnostics to decline a non-Dolt workspace") + } + message := err.Error() + if !strings.Contains(message, "Dolt") || !strings.Contains(message, `"sqlite"`) { + t.Fatalf("diagnostic error should explain the backend mismatch: %v", err) + } +} diff --git a/cmd/bd/doctor/server.go b/cmd/bd/doctor/server.go index 2a91ffa82..a007a81d4 100644 --- a/cmd/bd/doctor/server.go +++ b/cmd/bd/doctor/server.go @@ -61,9 +61,8 @@ func RunServerHealthChecks(path string) ServerHealthResult { result.Checks = append(result.Checks, DoctorCheck{ Name: "Server Config", Status: StatusWarning, - Message: fmt.Sprintf("Backend is '%s', not Dolt", cfg.GetBackend()), - Detail: "Server mode health checks are only relevant for Dolt backend", - Fix: "Set backend: dolt in metadata.json to use Dolt server mode", + Message: fmt.Sprintf("Server checks require Dolt; configured backend is %q", cfg.GetBackend()), + Detail: "Dolt server health checks do not apply to this backend", Category: CategoryFederation, }) result.OverallOK = false diff --git a/cmd/bd/doctor/server_backend_test.go b/cmd/bd/doctor/server_backend_test.go new file mode 100644 index 000000000..d75b3f448 --- /dev/null +++ b/cmd/bd/doctor/server_backend_test.go @@ -0,0 +1,33 @@ +package doctor + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/configfile" +) + +func TestRunServerHealthChecksSQLiteIsNotAMigrationWarning(t *testing.T) { + tmpDir := t.TempDir() + beadsDir := filepath.Join(tmpDir, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatal(err) + } + if err := (&configfile.Config{Backend: configfile.BackendSQLite, SQLitePath: "beads.db"}).Save(beadsDir); err != nil { + t.Fatalf("save SQLite config: %v", err) + } + + // The sqlite backend is a removed-backend tombstone: server checks report a + // clearly-attributed non-Dolt warning with no migration fix, and never edit + // the workspace. + result := RunServerHealthChecks(tmpDir) + if result.OverallOK || len(result.Checks) != 1 { + t.Fatalf("SQLite server-health result = %#v, want one non-Dolt warning", result) + } + check := result.Checks[0] + if check.Status != StatusWarning || !strings.Contains(check.Message, "sqlite") || check.Fix != "" { + t.Fatalf("SQLite server-health check = %#v, want non-Dolt warning without migration fix", check) + } +} diff --git a/cmd/bd/doctor_backend_guard_test.go b/cmd/bd/doctor_backend_guard_test.go new file mode 100644 index 000000000..3d2262151 --- /dev/null +++ b/cmd/bd/doctor_backend_guard_test.go @@ -0,0 +1,61 @@ +//go:build cgo + +package main + +import ( + "bytes" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestDoctorRejectsCorruptMetadataBeforeSharedServerChecks(t *testing.T) { + bd := buildBDUnderTest(t) + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + + metadata := []byte("{\n") + metadataPath := filepath.Join(beadsDir, "metadata.json") + if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil { + t.Fatalf("write corrupt metadata.json: %v", err) + } + + cmd := exec.Command(bd, "doctor", "--json") + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), + "BEADS_DOLT_SHARED_SERVER=1", + "BEADS_DOLT_SERVER_PORT=1", + "BEADS_DOLT_AUTO_START=0", + "BEADS_NO_DAEMON=1", + "BD_DISABLE_METRICS=1", + ) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("doctor unexpectedly ran shared-server checks with corrupt metadata:\n%s", out) + } + + message := strings.ToLower(string(out)) + for _, want := range []string{"metadata.json", "parsing config", "no storage database was opened or modified"} { + if !strings.Contains(message, want) { + t.Errorf("doctor corrupt-metadata error missing %q:\n%s", want, out) + } + } + + after, readErr := os.ReadFile(metadataPath) + if readErr != nil { + t.Fatalf("read metadata after refusal: %v", readErr) + } + if !bytes.Equal(after, metadata) { + t.Fatalf("doctor rewrote corrupt metadata:\nbefore: %q\nafter: %q", metadata, after) + } + for _, name := range []string{".local_version", "embeddeddolt", "dolt", "beads.db", "dolt-server.pid", "dolt-server.port"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("doctor created %s before rejecting corrupt metadata (stat error: %v)", name, statErr) + } + } +} diff --git a/cmd/bd/doctor_validate_test.go b/cmd/bd/doctor_validate_test.go index 5b6751006..5e3281cc4 100644 --- a/cmd/bd/doctor_validate_test.go +++ b/cmd/bd/doctor_validate_test.go @@ -144,7 +144,7 @@ func TestValidateCheck_DetectsOrphanedDeps(t *testing.T) { } func TestValidateCheck_GitConflicts_DoltClean(t *testing.T) { - // Since GetBackend() always returns "dolt" (SQLite removed in 87493ce9), + // When metadata is absent, GetBackend() defaults to "dolt", // the Git Conflicts check now queries dolt_conflicts (GH-2249). // Verify it reports OK for a clean Dolt database. tmpDir, store := setupValidateTestDB(t, "val") diff --git a/cmd/bd/dolt.go b/cmd/bd/dolt.go index 1551917c5..431f40e9f 100644 --- a/cmd/bd/dolt.go +++ b/cmd/bd/dolt.go @@ -106,6 +106,13 @@ Examples: bd dolt set data-dir /home/user/.beads-dolt/myproject`, Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { + beadsDir := selectedDoltBeadsDir() + if beadsDir == "" { + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + } + if _, err := loadDoltBackendConfig(beadsDir); err != nil { + return HandleError("%v", err) + } if !usesSQLServer() { return HandleError("'bd dolt set' is not supported in embedded mode (no Dolt server)") } @@ -129,6 +136,13 @@ This verifies that: Use this before switching to server mode to ensure the server is running.`, RunE: func(cmd *cobra.Command, args []string) error { + beadsDir := selectedDoltBeadsDir() + if beadsDir == "" { + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + } + if _, err := loadDoltBackendConfig(beadsDir); err != nil { + return HandleError("%v", err) + } if !usesSQLServer() { return HandleError("'bd dolt test' is not supported in embedded mode (no Dolt server)") } @@ -488,30 +502,6 @@ The remote must already exist (see 'bd dolt remote add').`, }, } -// errExplicitCommitUnsupported returns a typed *storage.ErrUnsupported when the -// open store has no Dolt commit graph (Postgres/MySQL/SQLite), and nil for Dolt. -// The SQL backends deliberately expose a no-op Commit so internal write paths can -// call store.Commit() opportunistically without erroring; an EXPLICIT `bd dolt -// commit` / `bd vc commit` must not ride that no-op and print a fake "Committed." -// with no commit graph behind it. Internal opportunistic auto-commit is skipped -// separately in PostRun for these backends, so gating only the explicit commands -// keeps that path untouched. -func errExplicitCommitUnsupported(st storage.DoltStorage, op string) error { - ncg, ok := storage.UnwrapStore(st).(storage.NonCommitGraphBackend) - if !ok || !ncg.CommitGraphUnsupported() { - return nil - } - backend := "non-dolt" - if beadsDir := selectedDoltBeadsDir(); beadsDir != "" { - if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil { - if b := cfg.GetBackend(); b != "" && b != configfile.BackendDolt { - backend = b - } - } - } - return &storage.ErrUnsupported{Op: op, Backend: backend} -} - var doltCommitCmd = &cobra.Command{ Use: "commit", Short: "Create a Dolt commit from pending changes", @@ -533,9 +523,6 @@ For more options (--stdin, custom messages), see: bd vc commit`, if st == nil { return HandleError("no store available") } - if err := errExplicitCommitUnsupported(st, "dolt commit"); err != nil { - return HandleError("%v", err) - } msg, _ := cmd.Flags().GetString("message") if msg == "" { msg = fmt.Sprintf("bd: dolt commit (auto-commit) by %s", getActor()) @@ -566,13 +553,16 @@ project path. PID and logs are stored in .beads/. The server auto-starts transparently when needed, so manual start is rarely required. Use this command for explicit control or diagnostics.`, RunE: func(cmd *cobra.Command, args []string) error { - if !usesSQLServer() { - return HandleError("'bd dolt start' is not supported in embedded mode (no Dolt server)") - } beadsDir := selectedDoltBeadsDir() if beadsDir == "" { return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } + if _, err := loadDoltBackendConfig(beadsDir); err != nil { + return HandleError("%v", err) + } + if !usesSQLServer() { + return HandleError("'bd dolt start' is not supported in embedded mode (no Dolt server)") + } serverDir := doltserver.ResolveServerDir(beadsDir) state, err := doltserver.Start(serverDir) @@ -609,13 +599,16 @@ var doltStopCmd = &cobra.Command{ This sends a graceful shutdown signal. The server will restart automatically on the next bd command unless auto-start is disabled.`, RunE: func(cmd *cobra.Command, args []string) error { - if !usesSQLServer() { - return HandleError("'bd dolt stop' is not supported in embedded mode (no Dolt server)") - } beadsDir := selectedDoltBeadsDir() if beadsDir == "" { return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } + if _, err := loadDoltBackendConfig(beadsDir); err != nil { + return HandleError("%v", err) + } + if !usesSQLServer() { + return HandleError("'bd dolt stop' is not supported in embedded mode (no Dolt server)") + } if usesProxiedServer() { rootDir, err := resolveProxiedServerRootPath(beadsDir) @@ -659,10 +652,20 @@ endpoint via SQL and reports reachability, server version, and database.`, if beadsDir == "" { return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } - // A non-Dolt backend (postgres/mysql/sqlite) has no Dolt engine at all; + cfg, cfgErr := configfile.Load(beadsDir) + if cfgErr != nil { + return HandleError("loading config: %v", cfgErr) + } + if cfg == nil { + cfg = configfile.DefaultConfig() + } + if err := validateConfiguredBackend(cfg); err != nil { + return HandleError("%v", err) + } + // A non-Dolt backend (SQLite or a removed-backend tombstone) has no Dolt engine; // report the backend rather than misdescribing an embedded Dolt server // (parity with `bd dolt show`, which already special-cases this). - if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil && cfg.GetBackend() != configfile.BackendDolt { + if cfg.GetBackend() != configfile.BackendDolt { fmt.Printf("Backend: %s (no Dolt engine)\n", cfg.GetBackend()) return nil } @@ -679,19 +682,10 @@ endpoint via SQL and reports reachability, server version, and database.`, // systemd manages the server lifecycle, be-0eyj) // // IsAutoStartDisabled reads the active (globally-bound) config and - // BEADS_DOLT_AUTO_START env, not the per-beadsDir cfg loaded just - // below. That coupling is intentional and consistent with every + // BEADS_DOLT_AUTO_START env, not the per-beadsDir cfg loaded above. + // That coupling is intentional and consistent with every // other call site of IsAutoStartDisabled in this package — both // resolve against the same active workspace at command time. - cfg, cfgErr := configfile.Load(beadsDir) - if cfgErr != nil { - // Don't silently swallow. A corrupted or missing metadata.json - // would otherwise mask the externally-managed routing for both - // the remote-host and auto-start-disabled-local cases, falling - // through to the PID-file path with a misleading "not running" - // — which is the exact failure mode this PR addresses. - fmt.Fprintf(os.Stderr, "Warning: cannot load .beads config (%v); falling back to PID-file status path\n", cfgErr) - } if cfg != nil && shouldUseExternalDoltStatus(cfg, doltserver.IsAutoStartDisabled(), doltserver.IsSharedServerMode()) { runExternalDoltStatus(beadsDir, cfg) return nil @@ -942,10 +936,15 @@ servers are preserved.`, SilenceUsage: true, SilenceErrors: true, RunE: func(cmd *cobra.Command, args []string) error { + beadsDir := selectedDoltBeadsDir() + if beadsDir != "" { + if _, err := loadDoltBackendConfig(beadsDir); err != nil { + return HandleError("%v", err) + } + } if !usesSQLServer() { return HandleError("'bd dolt killall' is not supported in embedded mode (no Dolt server)") } - beadsDir := selectedDoltBeadsDir() if beadsDir == "" { beadsDir = "." // best effort } @@ -1007,6 +1006,13 @@ Stale database prefixes: testdb_*, beads_test*, beads_pt*, beads_vr*, doctest_*, These waste server memory and can degrade performance under concurrent load. Use --dry-run to see what would be dropped without actually dropping.`, RunE: func(cmd *cobra.Command, args []string) error { + beadsDir := selectedDoltBeadsDir() + if beadsDir == "" { + return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) + } + if _, err := loadDoltBackendConfig(beadsDir); err != nil { + return HandleError("%v", err) + } if !usesSQLServer() { return HandleError("'bd dolt clean-databases' is not supported in embedded mode (no Dolt server)") } @@ -1450,6 +1456,9 @@ func showDoltConfig(testConnection bool) error { if cfg == nil { cfg = configfile.DefaultConfig() } + if err := validateConfiguredBackend(cfg); err != nil { + return HandleError("%v", err) + } backend := cfg.GetBackend() embedded := !usesSQLServer() @@ -1548,16 +1557,9 @@ func setDoltConfig(key, value string, updateConfig bool) error { return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } - cfg, err := configfile.Load(beadsDir) + cfg, err := loadDoltBackendConfig(beadsDir) if err != nil { - return HandleError("loading config: %v", err) - } - if cfg == nil { - cfg = configfile.DefaultConfig() - } - - if cfg.GetBackend() != configfile.BackendDolt { - return HandleError("not using Dolt backend") + return HandleError("%v", err) } var yamlKey string @@ -1709,16 +1711,9 @@ func testDoltConnection() error { return HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } - cfg, err := configfile.Load(beadsDir) + cfg, err := loadDoltBackendConfig(beadsDir) if err != nil { - return HandleError("loading config: %v", err) - } - if cfg == nil { - cfg = configfile.DefaultConfig() - } - - if cfg.GetBackend() != configfile.BackendDolt { - return HandleError("not using Dolt backend") + return HandleError("%v", err) } host := cfg.GetDoltServerHost() @@ -1878,12 +1873,9 @@ func openDoltServerConnection() (*sql.DB, func(), error) { return nil, nil, HandleErrorWithHint(activeWorkspaceNotFoundError(), diagHint()) } - cfg, err := configfile.Load(beadsDir) + cfg, err := loadDoltBackendConfig(beadsDir) if err != nil { - return nil, nil, HandleError("loading config: %v", err) - } - if cfg == nil { - cfg = configfile.DefaultConfig() + return nil, nil, HandleError("%v", err) } host := cfg.GetDoltServerHost() diff --git a/cmd/bd/init.go b/cmd/bd/init.go index 7f2e108de..6b4961095 100644 --- a/cmd/bd/init.go +++ b/cmd/bd/init.go @@ -3,20 +3,17 @@ package main import ( "bufio" "context" - "encoding/json" "errors" "fmt" "os" "os/exec" "path/filepath" "runtime" - "sort" "strconv" "strings" "time" "github.com/spf13/cobra" - "github.com/spf13/pflag" "github.com/steveyegge/beads/cmd/bd/doctor" "github.com/steveyegge/beads/cmd/bd/setup" "github.com/steveyegge/beads/internal/beads" @@ -28,11 +25,7 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dbproxy/proxy" "github.com/steveyegge/beads/internal/storage/dolt" - beadsmysql "github.com/steveyegge/beads/internal/storage/mysql" - "github.com/steveyegge/beads/internal/storage/pgdialect" - "github.com/steveyegge/beads/internal/storage/postgres" "github.com/steveyegge/beads/internal/storage/schema" - beadssqlite "github.com/steveyegge/beads/internal/storage/sqlite" "github.com/steveyegge/beads/internal/templates/agents" "github.com/steveyegge/beads/internal/ui" "github.com/steveyegge/beads/internal/utils" @@ -48,9 +41,8 @@ var initCmd = &cobra.Command{ Long: `Initialize bd in the current directory by creating a .beads/ directory and its storage (a Dolt database by default). Optionally specify a custom issue prefix. -Dolt is the default backend and the only one with version control (history, -branching, sync). Select an alternative with --backend=; -see docs/architecture/storage-backends.md for the trade-offs and setup. +Dolt is the default and only supported storage backend, with full version +control (history, branching, sync). Use --database to specify an existing server database name, overriding the default prefix-based naming. This is useful when an external tool (e.g. an orchestrator) @@ -105,12 +97,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): serverUser, _ := cmd.Flags().GetString("server-user") database, _ := cmd.Flags().GetString("database") destroyToken, _ := cmd.Flags().GetString("destroy-token") - // Postgres backend flags (backend="postgres") - pgURL, _ := cmd.Flags().GetString("pg-url") - pgSchema, _ := cmd.Flags().GetString("pg-schema") - mysqlURL, _ := cmd.Flags().GetString("mysql-url") - mysqlDatabase, _ := cmd.Flags().GetString("mysql-database") - sqlitePath, _ := cmd.Flags().GetString("sqlite-path") // --force is a deprecated alias for --reinit-local. They share // semantics for the local data-safety guard; both refuse remote @@ -249,49 +235,21 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): externalConfig = &cfg } - // Backend selection: dolt (default) + the pluggable SQL-family backends - // (postgres, mysql, sqlite). SQLite was removed under the one-backend - // assumption (#3151) and re-added as a pluggable leaf backend. - isPostgres := backendFlag == configfile.BackendPostgres - isMySQL := backendFlag == configfile.BackendMySQL - isSQLite := backendFlag == configfile.BackendSQLite - if backendFlag != "" && backendFlag != configfile.BackendDolt && !isPostgres && !isMySQL && !isSQLite { - return fmt.Errorf("unknown backend %q: supported backends are \"dolt\" (default), \"postgres\", \"mysql\", and \"sqlite\"", backendFlag) - } - if isPostgres || isMySQL || isSQLite { - // A non-Dolt SQL backend is a plain local workspace: only a small set of - // init-local flags apply. Reject any other init-local flag by ALLOWLIST — a - // denylist silently ignores Dolt-only flags added later, the exact footgun - // this block exists to prevent. Inherited/global flags (--json, --dir, …) - // are not init-local and are left untouched. - pgAllowedFlags := map[string]bool{ - "backend": true, - "pg-url": true, "pg-schema": true, - "mysql-url": true, "mysql-database": true, - "sqlite-path": true, - "prefix": true, "quiet": true, - "skip-hooks": true, "skip-agents": true, - "reinit-local": true, "force": true, "init-if-missing": true, - "non-interactive": true, + // Backend selection: Dolt is the only supported backend. + if !configfile.IsSupportedBackend(backendFlag) { + switch backendFlag { + case configfile.BackendPostgres, configfile.BackendMySQL: + return fmt.Errorf("storage backend %q is no longer supported: %s; the supported backend is \"dolt\" (default)", backendFlag, configfile.RemovedBackendRationale) + case configfile.BackendSQLite: + return fmt.Errorf("storage backend %q is no longer supported: %s; the supported backend is \"dolt\" (default)", backendFlag, configfile.RemovedSQLiteRationale) } - var rejected []string - cmd.Flags().Visit(func(f *pflag.Flag) { - // Only police init's own flags; inherited/global flags (--json, …) - // are not this command's concern. cmd.Flags() is the authoritative - // parsed set that carries the Changed state. - if cmd.InheritedFlags().Lookup(f.Name) != nil { - return - } - if !pgAllowedFlags[f.Name] { - rejected = append(rejected, "--"+f.Name) - } - }) - if len(rejected) > 0 { - sort.Strings(rejected) - return fmt.Errorf("bd init --backend=%s does not support %s (a non-Dolt SQL backend is a plain local workspace: no Dolt server, sync, remote, or wizard)", backendFlag, strings.Join(rejected, ", ")) + return fmt.Errorf("unknown backend %q: the supported backend is \"dolt\" (default)", backendFlag) + } + for _, legacyFlag := range removedBackendInitFlags { + if cmd.Flags().Changed(legacyFlag.name) { + return fmt.Errorf("--%s belonged to %s: %s; use --backend=dolt (the default)", legacyFlag.name, legacyFlag.origin, legacyFlag.rationale) } } - // Validate --database format early, before any side effects. if database != "" { if err := dolt.ValidateDatabaseName(database); err != nil { @@ -321,8 +279,7 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): return fmt.Errorf("--team requires interactive prompts and cannot be used with --non-interactive") } - // Non-Dolt backends (postgres/mysql/sqlite) were dispatched and returned - // earlier; this is the Dolt init path. + // Dolt is the only supported backend. backend := configfile.BackendDolt // Also treat BEADS_DOLT_SERVER_MODE=1 env var as --server. @@ -815,41 +772,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): ctx := rootCtx - // Postgres proof-wedge: finalize a plain local workspace backed by Postgres. - // Everything below provisions Dolt (embedded/server DB dir, migrations, remote - // gate, sync, remotes) — none of which Postgres has an analog for — so the PG - // path provisions the schema + seeds + metadata.json here and returns. The - // shared setup above (.beads/, .gitignore, git init) already ran. - if isPostgres { - return runInitPostgres(ctx, initPostgresInput{ - beadsDir: beadsDir, - prefix: prefix, - pgURL: pgURL, - pgSchema: pgSchema, - quiet: quiet, - jsonOutput: jsonOutput, - }) - } - if isMySQL { - return runInitMySQL(ctx, initMySQLInput{ - beadsDir: beadsDir, - prefix: prefix, - mysqlURL: mysqlURL, - mysqlDatabase: mysqlDatabase, - quiet: quiet, - jsonOutput: jsonOutput, - }) - } - if isSQLite { - return runInitSQLite(ctx, initSQLiteInput{ - beadsDir: beadsDir, - prefix: prefix, - sqlitePath: sqlitePath, - quiet: quiet, - jsonOutput: jsonOutput, - }) - } - // Create Dolt storage backend storagePath := doltserver.ResolveDoltDir(beadsDir) // Respect existing config's database name to avoid creating phantom catalog @@ -1829,293 +1751,6 @@ Non-interactive mode (--non-interactive or BD_NON_INTERACTIVE=1): }, } -// initPostgresInput carries the resolved inputs the Postgres init arm needs from -// the shared prologue of the init command. -type initPostgresInput struct { - beadsDir string - prefix string - pgURL string - pgSchema string - quiet bool - jsonOutput bool -} - -// runInitPostgres finalizes a Postgres-backed workspace. It is the Postgres analog -// of the Dolt store-open + config-seed + metadata block (init.go), minus every -// version-control / server / sync step Postgres has no analog for: it provisions the -// schema (DDL + config-default seeds, idempotent), seeds the issue prefix and project -// identity, and writes metadata.json with the password-stripped DSN. The password is -// supplied at open time via BEADS_PG_PASSWORD and never lands on disk. -func runInitPostgres(ctx context.Context, in initPostgresInput) error { - dsn := in.pgURL - if dsn == "" { - dsn = os.Getenv("BEADS_POSTGRES_URL") - } - if dsn == "" { - return fmt.Errorf("bd init --backend=postgres requires --pg-url= (or BEADS_POSTGRES_URL); a password may be included for init but is never persisted — set BEADS_PG_PASSWORD for later commands") - } - schema := in.pgSchema - if schema == "" { - return fmt.Errorf("bd init --backend=postgres requires --pg-schema= (the per-workspace schema for search_path isolation)") - } - - // Redact BEFORE provisioning: a connection string whose password we cannot safely - // strip fails the whole init before any schema is created, and the password is - // guaranteed never to reach metadata.json (RedactPassword verifies with pgx that - // no password survives, failing closed). - persistDSN, err := pgdialect.RedactPassword(dsn) - if err != nil { - return fmt.Errorf("cannot safely persist the Postgres connection: %w", err) - } - - store, err := postgres.Provision(ctx, dsn, schema) - if err != nil { - return fmt.Errorf("failed to initialize Postgres workspace: %w", err) - } - defer func() { _ = store.Close() }() - - // Load any existing metadata.json up front so we can adopt its project identity. - cfg, _ := configfile.Load(in.beadsDir) - if cfg == nil { - cfg = configfile.DefaultConfig() - } - - // Seed the issue prefix, only if unset — a shared schema may already carry one. - // Matches the Dolt init path (dots normalized to underscores for valid IDs). - if in.prefix != "" { - if existing, _ := store.GetConfig(ctx, "issue_prefix"); existing == "" { - issuePrefix := strings.ReplaceAll(in.prefix, ".", "_") - if err := store.SetConfig(ctx, "issue_prefix", issuePrefix); err != nil { - return fmt.Errorf("failed to set issue prefix: %w", err) - } - } - } - - // Project identity: the DB is authoritative when it already carries one; otherwise - // adopt the metadata.json id (a re-init or committed clone) or mint a fresh UUID. - // Write it to BOTH the DB and metadata.json so the two can never diverge (GH#2372) — - // the Dolt path keeps them in lockstep the same way. - projectID, _ := store.GetMetadata(ctx, "_project_id") - if projectID == "" { - if cfg.ProjectID != "" { - projectID = cfg.ProjectID - } else { - projectID = configfile.GenerateProjectID() - } - if err := store.SetMetadata(ctx, "_project_id", projectID); err != nil { - return fmt.Errorf("failed to write project ID: %w", err) - } - } - - // Persist metadata.json: backend + password-free DSN + schema + the DB's identity. - cfg.Backend = configfile.BackendPostgres - cfg.PostgresDSN = persistDSN - cfg.PostgresSchema = schema - cfg.ProjectID = projectID - if err := cfg.Save(in.beadsDir); err != nil { - return fmt.Errorf("failed to write metadata.json: %w", err) - } - - switch { - case in.jsonOutput: - out := map[string]any{ - "status": "initialized", - "backend": configfile.BackendPostgres, - "schema": schema, - "prefix": in.prefix, - } - b, _ := json.MarshalIndent(out, "", " ") - fmt.Println(string(b)) - case !in.quiet: - fmt.Printf("%s bd initialized with the Postgres backend\n", ui.RenderPass("✓")) - fmt.Printf(" Schema: %s\n", schema) - if in.prefix != "" { - fmt.Printf(" Prefix: %s\n", in.prefix) - } - fmt.Println(" History: not tracked (Postgres backend has no version control; use Dolt for history)") - } - return nil -} - -// initMySQLInput carries the resolved inputs the MySQL init arm needs. -type initMySQLInput struct { - beadsDir string - prefix string - mysqlURL string - mysqlDatabase string - quiet bool - jsonOutput bool -} - -// runInitMySQL finalizes a MySQL-backed workspace: it creates the per-workspace -// database, applies the schema (config seeds on first provision), seeds the issue -// prefix and project identity, and writes metadata.json with the password-stripped -// DSN. The password is supplied at open time via BEADS_MYSQL_PASSWORD and never lands -// on disk. MySQL isolates by database where Postgres isolates by schema. -func runInitMySQL(ctx context.Context, in initMySQLInput) error { - dsn := in.mysqlURL - if dsn == "" { - dsn = os.Getenv("BEADS_MYSQL_URL") - } - if dsn == "" { - return fmt.Errorf("bd init --backend=mysql requires --mysql-url= (or BEADS_MYSQL_URL), e.g. user:pass@tcp(host:3306)/ ; a password may be included for init but is never persisted — set BEADS_MYSQL_PASSWORD for later commands") - } - database := in.mysqlDatabase - if database == "" { - return fmt.Errorf("bd init --backend=mysql requires --mysql-database= (the per-workspace database)") - } - - // Redact BEFORE provisioning so a DSN we cannot safely persist fails before any - // side effect, and the password is guaranteed never to reach metadata.json. - persistDSN, err := beadsmysql.RedactPassword(dsn) - if err != nil { - return fmt.Errorf("cannot safely persist the MySQL connection: %w", err) - } - - store, err := beadsmysql.Provision(ctx, dsn, database) - if err != nil { - return fmt.Errorf("failed to initialize MySQL workspace: %w", err) - } - defer func() { _ = store.Close() }() - - cfg, _ := configfile.Load(in.beadsDir) - if cfg == nil { - cfg = configfile.DefaultConfig() - } - - if in.prefix != "" { - if existing, _ := store.GetConfig(ctx, "issue_prefix"); existing == "" { - issuePrefix := strings.ReplaceAll(in.prefix, ".", "_") - if err := store.SetConfig(ctx, "issue_prefix", issuePrefix); err != nil { - return fmt.Errorf("failed to set issue prefix: %w", err) - } - } - } - - projectID, _ := store.GetMetadata(ctx, "_project_id") - if projectID == "" { - if cfg.ProjectID != "" { - projectID = cfg.ProjectID - } else { - projectID = configfile.GenerateProjectID() - } - if err := store.SetMetadata(ctx, "_project_id", projectID); err != nil { - return fmt.Errorf("failed to write project ID: %w", err) - } - } - - cfg.Backend = configfile.BackendMySQL - cfg.MySQLDSN = persistDSN - cfg.MySQLDatabase = database - cfg.ProjectID = projectID - if err := cfg.Save(in.beadsDir); err != nil { - return fmt.Errorf("failed to write metadata.json: %w", err) - } - - switch { - case in.jsonOutput: - out := map[string]any{ - "status": "initialized", - "backend": configfile.BackendMySQL, - "database": database, - "prefix": in.prefix, - } - b, _ := json.MarshalIndent(out, "", " ") - fmt.Println(string(b)) - case !in.quiet: - fmt.Printf("%s bd initialized with the MySQL backend\n", ui.RenderPass("✓")) - fmt.Printf(" Database: %s\n", database) - if in.prefix != "" { - fmt.Printf(" Prefix: %s\n", in.prefix) - } - fmt.Println(" History: not tracked (MySQL backend has no version control; use Dolt for history)") - } - return nil -} - -// initSQLiteInput carries the resolved inputs the SQLite init arm needs. -type initSQLiteInput struct { - beadsDir string - prefix string - sqlitePath string - quiet bool - jsonOutput bool -} - -// runInitSQLite finalizes a SQLite-backed workspace: it provisions the database file -// (default beads.db inside the beads dir), seeds the issue prefix and project identity, -// and writes metadata.json. SQLite is file-based and embedded (pure-Go), so there is no -// server, DSN, or password. -func runInitSQLite(ctx context.Context, in initSQLiteInput) error { - relPath := in.sqlitePath - if relPath == "" { - relPath = "beads.db" - } - dbPath := relPath - if !filepath.IsAbs(dbPath) { - dbPath = filepath.Join(in.beadsDir, dbPath) - } - - store, err := beadssqlite.Provision(ctx, dbPath) - if err != nil { - return fmt.Errorf("failed to initialize SQLite workspace: %w", err) - } - defer func() { _ = store.Close() }() - - cfg, _ := configfile.Load(in.beadsDir) - if cfg == nil { - cfg = configfile.DefaultConfig() - } - - if in.prefix != "" { - if existing, _ := store.GetConfig(ctx, "issue_prefix"); existing == "" { - issuePrefix := strings.ReplaceAll(in.prefix, ".", "_") - if err := store.SetConfig(ctx, "issue_prefix", issuePrefix); err != nil { - return fmt.Errorf("failed to set issue prefix: %w", err) - } - } - } - - projectID, _ := store.GetMetadata(ctx, "_project_id") - if projectID == "" { - if cfg.ProjectID != "" { - projectID = cfg.ProjectID - } else { - projectID = configfile.GenerateProjectID() - } - if err := store.SetMetadata(ctx, "_project_id", projectID); err != nil { - return fmt.Errorf("failed to write project ID: %w", err) - } - } - - cfg.Backend = configfile.BackendSQLite - cfg.SQLitePath = relPath - cfg.ProjectID = projectID - if err := cfg.Save(in.beadsDir); err != nil { - return fmt.Errorf("failed to write metadata.json: %w", err) - } - - switch { - case in.jsonOutput: - out := map[string]any{ - "status": "initialized", - "backend": configfile.BackendSQLite, - "path": relPath, - "prefix": in.prefix, - } - b, _ := json.MarshalIndent(out, "", " ") - fmt.Println(string(b)) - case !in.quiet: - fmt.Printf("%s bd initialized with the SQLite backend\n", ui.RenderPass("✓")) - fmt.Printf(" Database: %s\n", relPath) - if in.prefix != "" { - fmt.Printf(" Prefix: %s\n", in.prefix) - } - fmt.Println(" History: not tracked (SQLite backend has no version control; use Dolt for history)") - } - return nil -} - func init() { initCmd.Flags().StringP("prefix", "p", "", "Issue prefix (default: current directory name)") initCmd.Flags().BoolP("quiet", "q", false, "Suppress output (quiet mode)") @@ -2140,13 +1775,16 @@ func init() { initCmd.Flags().Bool("non-interactive", false, "Skip all interactive prompts (auto-detected in CI or non-TTY environments)") initCmd.Flags().String("role", "", "Set beads role without prompting: \"maintainer\" or \"contributor\"") - // Backend selection: dolt (default) plus the SQL-family backends (postgres/mysql/sqlite). - initCmd.Flags().String("backend", "", "Storage backend: dolt (default), postgres, mysql, or sqlite. See docs/architecture/storage-backends.md.") - initCmd.Flags().String("pg-url", "", "Postgres connection URL (with --backend=postgres). A password may be included for init but is never persisted; set BEADS_PG_PASSWORD for later commands. Falls back to BEADS_POSTGRES_URL.") - initCmd.Flags().String("pg-schema", "", "Postgres schema for this workspace's tables (with --backend=postgres; provides search_path isolation)") - initCmd.Flags().String("mysql-url", "", "MySQL server DSN (with --backend=mysql), e.g. user:pass@tcp(host:3306)/ . A password may be included for init but is never persisted; set BEADS_MYSQL_PASSWORD for later commands. Falls back to BEADS_MYSQL_URL.") - initCmd.Flags().String("mysql-database", "", "MySQL database for this workspace (with --backend=mysql; MySQL's isolation unit)") - initCmd.Flags().String("sqlite-path", "", "SQLite database file (with --backend=sqlite; relative to the beads dir, default beads.db)") + // Backend selection: Dolt is the default and only supported backend. + initCmd.Flags().String("backend", "", "Storage backend: dolt (default). Removed backends (postgres, mysql, sqlite) print migration guidance.") + // Keep the short-lived removed-backend flags as hidden parser tombstones. A + // legacy invocation can then reach the backend rollback guidance instead of + // failing early with an opaque "unknown flag" error. The current backend rejects + // these flags explicitly above; they are never consumed as connection data. + for _, legacyFlag := range removedBackendInitFlags { + initCmd.Flags().String(legacyFlag.name, "", legacyFlag.usage) + _ = initCmd.Flags().MarkHidden(legacyFlag.name) + } // Dolt server connection flags initCmd.Flags().Bool("server", false, "Use external dolt sql-server instead of embedded engine") @@ -2179,6 +1817,19 @@ func init() { rootCmd.AddCommand(initCmd) } +var removedBackendInitFlags = []struct { + name string + usage string + origin string + rationale string +}{ + {name: "pg-url", usage: "Legacy PostgreSQL connection URL (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale}, + {name: "pg-schema", usage: "Legacy PostgreSQL schema (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale}, + {name: "mysql-url", usage: "Legacy MySQL connection URL (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale}, + {name: "mysql-database", usage: "Legacy MySQL database (removed backend compatibility only)", origin: "the removed PostgreSQL/MySQL initialization paths", rationale: configfile.RemovedBackendRationale}, + {name: "sqlite-path", usage: "Legacy SQLite database file (removed backend compatibility only)", origin: "the removed SQLite initialization path", rationale: configfile.RemovedSQLiteRationale}, +} + // migrateOldDatabases detects and migrates old database files to beads.db func migrateOldDatabases(targetPath string, quiet bool) error { targetDir := filepath.Dir(targetPath) @@ -2267,50 +1918,6 @@ func alreadyInitialized(format string, args ...any) error { // A returned error that matches errWorkspaceAlreadyInitialized means a database // already exists (the benign, idempotent-skip case); any other error is // operational and must not be treated as success. -// checkExistingSQLBackend returns an "already initialized" guard error when cfg -// selects a non-Dolt SQL backend (Postgres/MySQL/SQLite), each of which is marked -// by metadata.json alone with no local DB directory to inspect. It returns nil for -// the Dolt backend so the caller runs the directory/server checks instead. Split -// out of checkExistingBeadsDataAt so the added SQL-backend branches don't inflate -// that function's complexity. -func checkExistingSQLBackend(cfg *configfile.Config) error { - switch cfg.GetBackend() { - case configfile.BackendPostgres: - return alreadyInitialized(` -%s This workspace is already initialized with the Postgres backend (schema %q). - -To use it: - Just run bd commands normally (e.g., %s) - -To re-initialize (Postgres provisioning is idempotent): - bd init --backend=postgres --reinit-local ... - -Aborting.`, ui.RenderWarn("⚠"), cfg.GetPostgresSchema(), ui.RenderAccent("bd list")) - case configfile.BackendMySQL: - return alreadyInitialized(` -%s This workspace is already initialized with the MySQL backend (database %q). - -To use it: - Just run bd commands normally (e.g., %s) - -To re-initialize (MySQL provisioning is idempotent): - bd init --backend=mysql --reinit-local ... - -Aborting.`, ui.RenderWarn("⚠"), cfg.GetMySQLDatabase(), ui.RenderAccent("bd list")) - case configfile.BackendSQLite: - return alreadyInitialized(` -%s This workspace is already initialized with the SQLite backend (%q). - -To use it: - Just run bd commands normally (e.g., %s) - -To re-initialize (SQLite provisioning is idempotent): - bd init --backend=sqlite --reinit-local ... - -Aborting.`, ui.RenderWarn("⚠"), cfg.GetSQLitePath(), ui.RenderAccent("bd list")) - } - return nil -} func checkExistingBeadsDataAt(beadsDir string, prefix string) error { // Check if .beads directory exists @@ -2319,20 +1926,24 @@ func checkExistingBeadsDataAt(beadsDir string, prefix string) error { } // metadata.json is authoritative for the configured backend, so resolve it once - // and dispatch. A non-Dolt SQL backend (Postgres/MySQL/SQLite) is marked by - // metadata alone — there is no local DB directory to inspect — so a plain + // and dispatch. Removed-backend tombstones are marked by metadata + // alone — there is no local Dolt directory to inspect — so a plain // `bd init` (which defaults to Dolt) must not silently repoint a live SQL // workspace to a fresh embedded Dolt DB and orphan its issues. --reinit-local - // /--force bypass this (handled by the caller). A config that fails to load falls - // through to the redirect/database-file checks below. + // /--force bypass this (handled by the caller). Invalid metadata must fail closed: + // without an explicit reinitialization request, init may not overwrite the only + // marker for an external or otherwise nonlocal database. cfg, cfgErr := configfile.Load(beadsDir) - if cfgErr == nil && cfg != nil { - if guardErr := checkExistingSQLBackend(cfg); guardErr != nil { + if cfgErr != nil { + return fmt.Errorf("failed to load %s: %w; refusing to reinitialize automatically (restore the metadata or use --reinit-local after safeguarding existing data)", configfile.ConfigPath(beadsDir), cfgErr) + } + if cfg != nil { + if guardErr := validateConfiguredBackend(cfg); guardErr != nil { return guardErr } } - if cfgErr == nil && cfg != nil && cfg.GetBackend() == configfile.BackendDolt { + if cfg != nil && cfg.GetBackend() == configfile.BackendDolt { if cfg.IsDoltProxiedServerMode() { proxiedRoot, rootErr := resolveProxiedServerRootPath(beadsDir) if rootErr != nil { diff --git a/cmd/bd/init_embedded_test.go b/cmd/bd/init_embedded_test.go index 409237153..b5eed7d4e 100644 --- a/cmd/bd/init_embedded_test.go +++ b/cmd/bd/init_embedded_test.go @@ -1377,24 +1377,18 @@ func TestEmbeddedInit(t *testing.T) { }) t.Run("sql_backend_flags", func(t *testing.T) { - // SQLite is a supported pluggable backend now: init succeeds and records it. - _, beadsDir, _ := bdInit(t, bd, "--prefix", "sqlt", "--backend", "sqlite") - cfg, err := configfile.Load(beadsDir) - if err != nil { - t.Fatalf("failed to load metadata.json: %v", err) - } - if cfg.Backend != configfile.BackendSQLite { - t.Errorf("backend: got %q, want %q", cfg.Backend, configfile.BackendSQLite) + // The SQLite backend was rolled back with the other alternative + // backends: init fails closed with its own rationale. + sqliteOut := bdInitFail(t, bd, "--backend", "sqlite") + if !strings.Contains(sqliteOut, "no longer supported") || !strings.Contains(sqliteOut, "single engine") { + t.Errorf("sqlite should report the backend rollback: %s", sqliteOut) } - // Postgres is recognized, not an unknown backend: it fails only because the - // required connection config is absent (bdEnv strips any ambient DSN). - pgOut := bdInitFail(t, bd, "--backend", "postgres") - if strings.Contains(pgOut, "unknown backend") { - t.Errorf("postgres should be recognized, got unknown-backend error: %s", pgOut) - } - if !strings.Contains(pgOut, "--pg-url") { - t.Errorf("postgres init should request --pg-url, got: %s", pgOut) + for _, backend := range []string{"postgres", "mysql"} { + out := bdInitFail(t, bd, "--backend", backend) + if !strings.Contains(out, "no longer supported") { + t.Errorf("%s should report the backend rollback: %s", backend, out) + } } // A genuinely unsupported backend is still rejected. diff --git a/cmd/bd/init_test.go b/cmd/bd/init_test.go index c152c9a13..b56467100 100644 --- a/cmd/bd/init_test.go +++ b/cmd/bd/init_test.go @@ -2369,10 +2369,9 @@ func initBackendTestEnv(beadsDir string) []string { func TestInitBackendFlag(t *testing.T) { bd := buildBDForInitTests(t) - // SQLite is a supported pluggable backend now (it was removed under the - // one-backend assumption in #3151 and re-added as a leaf backend): init - // succeeds and metadata.json records backend=sqlite. - t.Run("sqlite_initializes_and_persists_backend", func(t *testing.T) { + // The SQLite backend was rolled back with the other alternative backends: + // init fails closed with migration guidance and writes no workspace state. + t.Run("sqlite_is_no_longer_supported", func(t *testing.T) { tmpDir := t.TempDir() beadsDir := filepath.Join(tmpDir, ".beads") @@ -2380,45 +2379,41 @@ func TestInitBackendFlag(t *testing.T) { cmd.Dir = tmpDir cmd.Env = initBackendTestEnv(beadsDir) out, err := cmd.CombinedOutput() - if err != nil { - t.Fatalf("bd init --backend=sqlite should succeed: %v\n%s", err, out) - } - - cfg, err := configfile.Load(beadsDir) - if err != nil { - t.Fatalf("Failed to load metadata.json: %v", err) - } - if cfg == nil { - t.Fatal("metadata.json not found after --backend=sqlite init") - } - if cfg.Backend != configfile.BackendSQLite { - t.Errorf("Expected backend %q, got %q", configfile.BackendSQLite, cfg.Backend) - } - }) - - // Postgres is a recognized backend now: it must not be rejected as unknown, - // and it fails only because the required connection config is absent. - t.Run("postgres_is_recognized_and_requires_config", func(t *testing.T) { - tmpDir := t.TempDir() - beadsDir := filepath.Join(tmpDir, ".beads") - - cmd := exec.Command(bd, "init", "--backend", "postgres", "--quiet") - cmd.Dir = tmpDir - cmd.Env = initBackendTestEnv(beadsDir) - out, err := cmd.CombinedOutput() if err == nil { - t.Fatal("Expected non-zero exit for --backend=postgres without connection config") + t.Fatalf("Expected non-zero exit for --backend=sqlite:\n%s", out) } - outStr := string(out) - if strings.Contains(outStr, "unknown backend") { - t.Errorf("postgres must be a recognized backend, not reported unknown: %s", outStr) + if !strings.Contains(outStr, "no longer supported") || !strings.Contains(outStr, "single engine") { + t.Errorf("Expected rollback guidance for sqlite, got: %s", outStr) } - if !strings.Contains(outStr, "--pg-url") { - t.Errorf("Expected missing --pg-url guidance for postgres, got: %s", outStr) + if _, statErr := os.Stat(beadsDir); !os.IsNotExist(statErr) { + t.Fatalf("rejected sqlite init created workspace state (stat error: %v)", statErr) } }) + for _, backend := range []string{"postgres", "mysql"} { + t.Run(backend+"_is_no_longer_supported", func(t *testing.T) { + tmpDir := t.TempDir() + beadsDir := filepath.Join(tmpDir, ".beads") + + cmd := exec.Command(bd, "init", "--backend", backend, "--quiet") + cmd.Dir = tmpDir + cmd.Env = initBackendTestEnv(beadsDir) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("Expected non-zero exit for --backend=%s", backend) + } + + outStr := string(out) + if !strings.Contains(outStr, "no longer supported") { + t.Errorf("Expected rollback guidance for %s, got: %s", backend, outStr) + } + if !strings.Contains(outStr, `"dolt"`) { + t.Errorf("Expected supported backend guidance for %s, got: %s", backend, outStr) + } + }) + } + // A genuinely unsupported backend value is still rejected up front. t.Run("unknown_backend_errors", func(t *testing.T) { tmpDir := t.TempDir() diff --git a/cmd/bd/main.go b/cmd/bd/main.go index 3929f8e51..a1939a8f7 100644 --- a/cmd/bd/main.go +++ b/cmd/bd/main.go @@ -33,11 +33,7 @@ import ( "github.com/steveyegge/beads/internal/routing" "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dolt" - mysqlstore "github.com/steveyegge/beads/internal/storage/mysql" - "github.com/steveyegge/beads/internal/storage/pgdialect" - pgstore "github.com/steveyegge/beads/internal/storage/postgres" "github.com/steveyegge/beads/internal/storage/schema" - sqlitestore "github.com/steveyegge/beads/internal/storage/sqlite" "github.com/steveyegge/beads/internal/storage/uow" "github.com/steveyegge/beads/internal/telemetry" "github.com/steveyegge/beads/internal/ui" @@ -992,9 +988,13 @@ var rootCmd = &cobra.Command{ if dbPath == "" { if bd := beads.FindBeadsDir(); bd != "" { - if cfg, _ := configfile.Load(bd); cfg != nil && (cfg.IsDoltProxiedServerMode() || cfg.GetBackend() == configfile.BackendPostgres || cfg.GetBackend() == configfile.BackendMySQL || cfg.GetBackend() == configfile.BackendSQLite) { - // A non-Dolt SQL (or proxied-server) workspace has no local Dolt - // database file; the .beads dir with metadata.json IS the workspace. + cfg, cfgErr := configfile.Load(bd) + if cfgErr != nil || cfg != nil && (cfg.IsDoltProxiedServerMode() || !configfile.IsSupportedBackend(cfg.Backend)) { + // Proxied-server and removed-backend workspaces may have no + // local Dolt database file. Invalid or unknown metadata likewise must + // reach config validation instead of becoming a generic "no database" + // result. metadata.json identifies the workspace so store selection can + // route or reject it explicitly. dbPath = bd } } @@ -1076,6 +1076,18 @@ var rootCmd = &cobra.Command{ return HandleError("%v", err) } + // Resolve the backend before version tracking, migration, server startup, or + // any store construction. PostgreSQL/MySQL values are retained as metadata + // tombstones so an existing workspace fails closed instead of falling through + // to a new, empty Dolt database. + cfg, cfgErr := configfile.Load(beadsDir) + if cfgErr != nil { + return HandleError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr) + } + if backendErr := validateConfiguredBackend(cfg); backendErr != nil { + return HandleError("%v", backendErr) + } + // Set actor for audit trail actor = getActorWithGit() // Attach actor to the command span now that we have it. @@ -1134,10 +1146,6 @@ var rootCmd = &cobra.Command{ // result set and exit 0 (false-empty), which readers misinterpret as // "no work". Absent metadata.json (cfg == nil, cfgErr == nil) keeps // the fresh-repo embedded default below. - cfg, cfgErr := configfile.Load(beadsDir) - if cfgErr != nil { - return HandleError("failed to load beads config from %s: %v (refusing to fall back to the embedded store; fix or restore metadata.json and retry)", beadsDir, cfgErr) - } if cfg != nil { warnSharedServerEmbeddedMismatch(cfg) doltCfg.ProxiedServer = cfg.IsDoltProxiedServerMode() @@ -1179,9 +1187,7 @@ var rootCmd = &cobra.Command{ // command must not run (or fail) embedded opens even when the env var is set. // Dolt-only: the gateway credential command mints a Dolt server // username. IsSharedServerMode() forces ServerMode true with no backend - // guard, so without this check a shared-server config in config.yaml - // would run (and fail closed) the command for postgres/mysql/sqlite - // workspaces, which never present a server username. + // guard, so non-Dolt metadata must not try to resolve a server username. if doltCfg.ServerMode && cfg.GetBackend() == configfile.BackendDolt { if _, credErr := dolt.ApplyGatewayCredential(rootCtx, cfg, doltCfg); credErr != nil { return HandleError("resolving dolt credential command: %v", credErr) @@ -1275,19 +1281,7 @@ var rootCmd = &cobra.Command{ // Removing them WILL cause unrecoverable data corruption and data loss. // Dolt manages these files itself; external interference is never safe. - if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres { - // Postgres backend: open via the SQL-family bundle, bypassing the - // Dolt open path (the doltCfg above is built but unused here). - store, err = pgstore.NewFromConfig(rootCtx, beadsDir) - } else if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL { - // MySQL backend: same SQL-family bundle, isolation by database. - store, err = mysqlstore.NewFromConfig(rootCtx, beadsDir) - } else if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite { - // SQLite backend: pure-Go file-based SQL-family bundle. - store, err = sqlitestore.NewFromConfig(rootCtx, beadsDir) - } else { - store, err = newDoltStore(rootCtx, doltCfg) - } + store, err = newDoltStore(rootCtx, doltCfg) // Track final read-only state for staleness checks (GH#1089) storeIsReadOnly = doltCfg.ReadOnly @@ -1394,72 +1388,60 @@ var rootCmd = &cobra.Command{ uowProvider = nil } } else { - // Slice 5c: a NonCommitGraphBackend (Postgres, SQLite, ...) has no Dolt - // commit graph, so skip the Dolt-only maintenance tail. UnwrapStore reaches - // the concrete store past the HookFiringStore decorator; a store WITHOUT the - // marker (every Dolt variant) leaves skipMaintenance false and runs the tail - // unchanged. store.Close below stays unconditional. - skipMaintenance := false - if ncg, ok := storage.UnwrapStore(store).(storage.NonCommitGraphBackend); ok && ncg.CommitGraphUnsupported() { - skipMaintenance = true + // Dolt auto-commit: after a successful write command (and after final flush), + // create a Dolt commit so changes don't remain only in the working set. + if commandDidWrite.Load() && !commandDidExplicitDoltCommit { + if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil { + return HandleError("dolt auto-commit failed: %v", err) + } } - if !skipMaintenance { - // Dolt auto-commit: after a successful write command (and after final flush), - // create a Dolt commit so changes don't remain only in the working set. - if commandDidWrite.Load() && !commandDidExplicitDoltCommit { - if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: cmd.Name()}); err != nil { - return HandleError("dolt auto-commit failed: %v", err) - } - } - - // Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the - // tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands. - if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 { - // Only applies when dolt auto-commit is enabled and backend is versioned (Dolt). - if mode, err := getDoltAutoCommitMode(); err != nil { - return HandleError("dolt tip auto-commit failed: %v", err) - } else if mode == doltAutoCommitOn { - // Apply tip metadata writes now (deferred in recordTipShown for Dolt). - for tipID := range commandTipIDsShown { - key := fmt.Sprintf("tip_%s_last_shown", tipID) - value := time.Now().Format(time.RFC3339) - if err := store.SetLocalMetadata(rootCtx, key, value); err != nil { - return HandleError("dolt tip auto-commit failed: %v", err) - } - } - - ids := make([]string, 0, len(commandTipIDsShown)) - for tipID := range commandTipIDsShown { - ids = append(ids, tipID) - } - msg := formatDoltAutoCommitMessage("tip", getActor(), ids) - if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { + // Tip metadata auto-commit: if a tip was shown, create a separate Dolt commit for the + // tip_*_last_shown metadata updates. This may happen even for otherwise read-only commands. + if commandDidWriteTipMetadata && len(commandTipIDsShown) > 0 { + // Only applies when dolt auto-commit is enabled and backend is versioned (Dolt). + if mode, err := getDoltAutoCommitMode(); err != nil { + return HandleError("dolt tip auto-commit failed: %v", err) + } else if mode == doltAutoCommitOn { + // Apply tip metadata writes now (deferred in recordTipShown for Dolt). + for tipID := range commandTipIDsShown { + key := fmt.Sprintf("tip_%s_last_shown", tipID) + value := time.Now().Format(time.RFC3339) + if err := store.SetLocalMetadata(rootCtx, key, value); err != nil { return HandleError("dolt tip auto-commit failed: %v", err) } } - } - // Auto-backup: sync a Dolt-native backup if enabled and due - maybeAutoBackup(rootCtx) - - // Auto-export: write git-tracked JSONL for portability if enabled and due. - // Read-only commands must not perform post-run maintenance writes or emit - // sync guidance after machine-readable output. - if shouldRunPostCommandAutoExport(cmd) { - if err := maybeAutoExport(rootCtx, commandAllowsEmptyAutoExport(cmd)); err != nil { - return HandleError("%v", err) + ids := make([]string, 0, len(commandTipIDsShown)) + for tipID := range commandTipIDsShown { + ids = append(ids, tipID) + } + msg := formatDoltAutoCommitMessage("tip", getActor(), ids) + if err := maybeAutoCommit(rootCtx, doltAutoCommitParams{Command: "tip", MessageOverride: msg}); err != nil { + return HandleError("dolt tip auto-commit failed: %v", err) } } + } - // Auto-push: push to Dolt remote if enabled and due. - // Skip for read-only commands to avoid unnecessary network operations - // and metadata writes on commands like bd list/show/ready (GH#2191). - if !isReadOnlyCommand(cmd.Name()) { - maybeAutoPush(rootCtx) + // Auto-backup: sync a Dolt-native backup if enabled and due + maybeAutoBackup(rootCtx) + + // Auto-export: write git-tracked JSONL for portability if enabled and due. + // Read-only commands must not perform post-run maintenance writes or emit + // sync guidance after machine-readable output. + if shouldRunPostCommandAutoExport(cmd) { + if err := maybeAutoExport(rootCtx, commandAllowsEmptyAutoExport(cmd)); err != nil { + return HandleError("%v", err) } } + // Auto-push: push to Dolt remote if enabled and due. + // Skip for read-only commands to avoid unnecessary network operations + // and metadata writes on commands like bd list/show/ready (GH#2191). + if !isReadOnlyCommand(cmd.Name()) { + maybeAutoPush(rootCtx) + } + // Signal that store is closing (prevents background flush from accessing closed store) storeMutex.Lock() storeActive = false @@ -1572,7 +1554,7 @@ func checkBlockedEnvVars() error { for _, name := range blockedEnvVars { if os.Getenv(name) != "" { return fmt.Errorf("%s env var is not supported and has been removed to prevent data fragmentation.\n"+ - "The storage backend is set in .beads/metadata.json. To change it, use: bd migrate dolt", name) + "Unset %s; storage selection comes from .beads/metadata.json. To choose a different supported backend, follow 'bd help init-safety'; do not edit metadata.json by hand", name, name) } } return nil @@ -1747,15 +1729,9 @@ func envTruthyValue(v string) bool { return true } -// dsnFlags are the flags whose value is a connection string that may embed a -// password (bd init --backend=postgres/mysql). Their values get the full -// parser-backed DSN scrub; other args only get the unambiguous userinfo scrub. -var dsnFlags = map[string]bool{"--pg-url": true, "--mysql-url": true} - // secretFlagNames are long flag names whose entire value is an opaque credential -// that must never reach the bd.args telemetry span. Unlike dsnFlags (a DSN that is -// parsed so its structure survives), a secret flag's value is redacted wholesale. -// Only federation add-peer's --password currently qualifies. Its shorthand (-p) is +// that must never reach the bd.args telemetry span. The flag's value is redacted +// wholesale. Only federation add-peer's --password currently qualifies. Its shorthand (-p) is // resolved per command via secretFlagTokens so the same letter bound to // --priority/--prefix/--parallel on other commands is never redacted. var secretFlagNames = map[string]bool{"password": true} @@ -1784,40 +1760,38 @@ func secretFlagTokens(cmd *cobra.Command) map[string]bool { } // scrubArgsForTelemetry joins argv for the bd.args span attribute with any -// credential-bearing values redacted. --pg-url/--mysql-url may carry a password -// for init, and federation add-peer --password/-p carries a SQL password; -// RedactPassword protects metadata.json, but the raw argv would otherwise leak the -// secret into the telemetry root span and trace logs. -// -// A DSN flag's value is scrubbed through the parser-backed pgdialect logic so every -// password form pgx accepts is caught — URL userinfo, URL `?password=`/`?sslpassword=` -// query params, and libpq `password=`/`sslpassword=` keyword/value tokens — in both -// the `--pg-url=` and `--pg-url ` spellings. A secretFlags token's value is -// an opaque credential and is redacted wholesale across the `--password `, +// credential-bearing values redacted. A secretFlags token's value is redacted +// wholesale across the `--password `, // `--password=`, `-p `, `-p=`, and `-p` spellings pflag accepts. Every -// other arg still gets the narrow user:PASS@host userinfo scrub as defense in depth, -// without the broad keyword scan that would over-redact ordinary text. +// other arg gets a conservative DSN/userinfo scrub as defense in depth so a +// positional connection string cannot leak a password. func scrubArgsForTelemetry(argv []string, secretFlags map[string]bool) string { parts := make([]string, len(argv)) + redactNext := false for i, a := range argv { - if name, val, ok := strings.Cut(a, "="); ok { - if dsnFlags[name] { - // --pg-url= — scrub only the value, keep the flag name. - parts[i] = name + "=" + scrubDSNValue(val) - continue - } + if redactNext { + parts[i] = "xxxxx" + redactNext = false + continue + } + if name, value, ok := strings.Cut(a, "="); ok { if secretFlags[name] { // --password= / -p= — redact the whole value. parts[i] = name + "=xxxxx" continue } + if strings.HasPrefix(name, "-") { + scrubbed := scrubUserinfoPassword(scrubPotentialDSNPasswords(value)) + if scrubbed != value { + // Preserve an arbitrary flag name while parsing its equals-value as + // a possible DSN. Passing the whole token to url.Parse would treat + // the flag prefix as the URL scheme and miss query credentials. + parts[i] = name + "=" + scrubbed + continue + } + } } if i > 0 { - if dsnFlags[argv[i-1]] { - // following a bare --pg-url token. - parts[i] = scrubDSNValue(a) - continue - } if secretFlags[argv[i-1]] { // following a bare --password / -p token. parts[i] = "xxxxx" @@ -1829,7 +1803,14 @@ func scrubArgsForTelemetry(argv []string, secretFlags map[string]bool) string { parts[i] = short + "xxxxx" continue } - parts[i] = scrubUserinfoPassword(a) + if secretShorthandTakesSeparateValue(a, secretFlags) { + // -qp — a boolean shorthand cluster ending in the + // value-taking secret shorthand, with its value in the next token. + parts[i] = a + redactNext = true + continue + } + parts[i] = scrubUserinfoPassword(scrubPotentialDSNPasswords(a)) } return strings.Join(parts, " ") } @@ -1868,12 +1849,23 @@ func secretShorthandPrefix(a string, secretFlags map[string]bool) (string, bool) return "", false } -// scrubDSNValue redacts every password form from a connection-string value. The -// pgdialect pass covers pgx's URL (userinfo + query) and libpq keyword/value shapes; -// the trailing userinfo pass covers the MySQL user:PASS@tcp(...) DSN, which is not a -// scheme URL and so is invisible to the pgdialect extractor. -func scrubDSNValue(val string) string { - return scrubUserinfoPassword(pgdialect.ScrubDSNString(val, val)) +// secretShorthandTakesSeparateValue recognizes a boolean-shorthand cluster that +// ends in a registered secret shorthand with no attached value. For example, +// pflag parses "-qp secret" as -q followed by -p=secret. +func secretShorthandTakesSeparateValue(a string, secretFlags map[string]bool) bool { + if len(a) < 3 || a[0] != '-' || a[1] == '-' { + return false + } + for i := 1; i < len(a); i++ { + c := a[i] + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { + return false + } + if secretFlags["-"+string(c)] { + return i == len(a)-1 + } + } + return false } // scrubUserinfoPassword redacts the password in a URL/DSN userinfo section diff --git a/cmd/bd/main_test.go b/cmd/bd/main_test.go index 6563ed78c..187cc130f 100644 --- a/cmd/bd/main_test.go +++ b/cmd/bd/main_test.go @@ -142,6 +142,12 @@ func TestBlockedEnvVars(t *testing.T) { if err != nil && !strings.Contains(err.Error(), tt.envVar) { t.Errorf("expected error to mention %s, got: %v", tt.envVar, err) } + if err != nil && !strings.Contains(err.Error(), "bd help init-safety") { + t.Errorf("expected error to point to safe reinitialization guidance, got: %v", err) + } + if err != nil && strings.Contains(err.Error(), "bd migrate dolt") { + t.Errorf("error must not recommend the removed backend-conversion command: %v", err) + } }) } diff --git a/cmd/bd/sql.go b/cmd/bd/sql.go index 97a199123..eb3220a69 100644 --- a/cmd/bd/sql.go +++ b/cmd/bd/sql.go @@ -15,7 +15,7 @@ var sqlCmd = &cobra.Command{ Use: "sql ", GroupID: "maint", Short: "Execute raw SQL against the beads database", - Long: `Execute a raw SQL query against the underlying database (SQLite or Dolt). + Long: `Execute a raw SQL query against the underlying database (Dolt). Useful for debugging, maintenance, and working around bugs in higher-level commands. diff --git a/cmd/bd/store_factory.go b/cmd/bd/store_factory.go index 6fdac6657..1c61f3e79 100644 --- a/cmd/bd/store_factory.go +++ b/cmd/bd/store_factory.go @@ -15,9 +15,6 @@ import ( "github.com/steveyegge/beads/internal/storage/dbproxy/util" "github.com/steveyegge/beads/internal/storage/dolt" "github.com/steveyegge/beads/internal/storage/embeddeddolt" - beadsmysql "github.com/steveyegge/beads/internal/storage/mysql" - "github.com/steveyegge/beads/internal/storage/postgres" - beadssqlite "github.com/steveyegge/beads/internal/storage/sqlite" ) func usesSQLServer() bool { @@ -110,14 +107,8 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltS // metadata.json (cfg == nil, err == nil) keeps the embedded default. return nil, fmt.Errorf("load %s: %w (refusing to fall back to the embedded store)", configfile.ConfigPath(beadsDir), err) } - if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres { - return postgres.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL { - return beadsmysql.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite { - return beadssqlite.NewFromConfig(ctx, beadsDir) + if err := validateConfiguredBackend(cfg); err != nil { + return nil, err } if cfg != nil && cfg.IsDoltProxiedServerMode() { // TODO: this needs to be uow provider @@ -199,17 +190,8 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D // "database not found" the embedded open would produce. return nil, fmt.Errorf("load %s: %w (refusing to fall back to the embedded store)", configfile.ConfigPath(beadsDir), err) } - if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres { - // Postgres has no read-only open mode in the wedge; a normal open is fine - // (reads don't mutate, and search_path is per-workspace). - return postgres.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL { - // MySQL likewise has no separate read-only open in the wedge; reads don't mutate. - return beadsmysql.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite { - return beadssqlite.NewFromConfig(ctx, beadsDir) + if err := validateConfiguredBackend(cfg); err != nil { + return nil, err } if cfg != nil && cfg.IsDoltProxiedServerMode() { // TODO: this needs to be uow provider diff --git a/cmd/bd/store_factory_nocgo.go b/cmd/bd/store_factory_nocgo.go index 892eb0f0f..4839651a4 100644 --- a/cmd/bd/store_factory_nocgo.go +++ b/cmd/bd/store_factory_nocgo.go @@ -10,9 +10,6 @@ import ( "github.com/steveyegge/beads/internal/storage" "github.com/steveyegge/beads/internal/storage/dbproxy/util" "github.com/steveyegge/beads/internal/storage/dolt" - beadsmysql "github.com/steveyegge/beads/internal/storage/mysql" - "github.com/steveyegge/beads/internal/storage/postgres" - beadssqlite "github.com/steveyegge/beads/internal/storage/sqlite" ) func usesSQLServer() bool { @@ -57,17 +54,8 @@ func newDoltStoreFromConfig(ctx context.Context, beadsDir string) (storage.DoltS // message below. return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err) } - if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres { - // Postgres needs no CGO (pure-Go pgx), so it works in the nocgo build too. - return postgres.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL { - // MySQL (go-sql-driver) needs no CGO either. - return beadsmysql.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite { - // SQLite (modernc.org/sqlite) is pure-Go; no CGO. - return beadssqlite.NewFromConfig(ctx, beadsDir) + if err := validateConfiguredBackend(cfg); err != nil { + return nil, err } if cfg != nil && cfg.IsDoltProxiedServerMode() { // TODO: this needs to be uow provider @@ -90,14 +78,8 @@ func newReadOnlyStoreFromConfig(ctx context.Context, beadsDir string) (storage.D if err != nil { return nil, fmt.Errorf("load %s: %w", configfile.ConfigPath(beadsDir), err) } - if cfg != nil && cfg.GetBackend() == configfile.BackendPostgres { - return postgres.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendMySQL { - return beadsmysql.NewFromConfig(ctx, beadsDir) - } - if cfg != nil && cfg.GetBackend() == configfile.BackendSQLite { - return beadssqlite.NewFromConfig(ctx, beadsDir) + if err := validateConfiguredBackend(cfg); err != nil { + return nil, err } if cfg != nil && cfg.IsDoltProxiedServerMode() { // TODO: this needs to be uow provider diff --git a/cmd/bd/store_selection_removed_backend_test.go b/cmd/bd/store_selection_removed_backend_test.go new file mode 100644 index 000000000..5c1ec2b13 --- /dev/null +++ b/cmd/bd/store_selection_removed_backend_test.go @@ -0,0 +1,420 @@ +package main + +import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads/internal/configfile" +) + +func TestCommandStartupRejectsRemovedBackendsBeforeLocalWrites(t *testing.T) { + bd := buildBDForInitTests(t) + for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} { + t.Run(backend, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o755); err != nil { + t.Fatalf("create beads dir: %v", err) + } + if err := (&configfile.Config{Backend: backend}).Save(beadsDir); err != nil { + t.Fatalf("save config: %v", err) + } + + cmd := exec.Command(bd, "list", "--json") + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("removed backend %s unexpectedly opened", backend) + } + message := strings.ToLower(string(out)) + for _, want := range removedBackendWantSubstrings(backend) { + if !strings.Contains(message, want) { + t.Errorf("startup error for %s missing %q: %s", backend, want, message) + } + } + + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} { + path := filepath.Join(beadsDir, name) + if _, statErr := os.Stat(path); !os.IsNotExist(statErr) { + t.Fatalf("removed backend %s created local state at %s (stat error: %v)", backend, path, statErr) + } + } + }) + } +} + +func TestCommandStartupRejectsUnknownBackendBeforeLocalWrites(t *testing.T) { + bd := buildBDForInitTests(t) + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + if err := (&configfile.Config{Backend: "mystery"}).Save(beadsDir); err != nil { + t.Fatalf("save unknown-backend metadata: %v", err) + } + + cmd := exec.Command(bd, "list", "--json") + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("unknown backend unexpectedly opened:\n%s", out) + } + message := string(out) + if strings.Contains(message, "no beads database found") { + t.Fatalf("unknown backend stopped at generic discovery instead of metadata guidance:\n%s", out) + } + for _, want := range []string{"not recognized", "opened or modified", "dolt"} { + if !strings.Contains(message, want) { + t.Errorf("unknown-backend error missing %q:\n%s", want, out) + } + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("unknown backend created %s (stat error: %v)", name, statErr) + } + } +} + +func TestInitGuardRejectsCorruptMetadataBeforeWorkspaceWrites(t *testing.T) { + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + metadata := []byte("{\n") + if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil { + t.Fatalf("write corrupt metadata.json: %v", err) + } + + err := checkExistingBeadsDataAt(beadsDir, "guard") + if err == nil || !strings.Contains(err.Error(), "metadata.json") { + t.Fatalf("init guard error = %v, want corrupt metadata refusal", err) + } + after, readErr := os.ReadFile(metadataPath) + if readErr != nil { + t.Fatalf("read metadata after refusal: %v", readErr) + } + if string(after) != string(metadata) { + t.Fatalf("init guard rewrote corrupt metadata: before %q, after %q", metadata, after) + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("init guard created %s (stat error: %v)", name, statErr) + } + } +} + +func TestDoctorRejectsUnknownBackendBeforeDoltChecks(t *testing.T) { + bd := buildBDForInitTests(t) + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + cfg := &configfile.Config{ + Backend: "mystery", + DoltMode: configfile.DoltModeServer, + DoltServerHost: "127.0.0.1", + DoltServerPort: 1, + } + if err := cfg.Save(beadsDir); err != nil { + t.Fatalf("save unknown-backend metadata: %v", err) + } + + cmd := exec.Command(bd, "doctor", "--server", "--json") + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), "BEADS_DOLT_AUTO_START=0", "BD_DISABLE_METRICS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("doctor unexpectedly ran Dolt checks for unknown backend:\n%s", out) + } + for _, want := range []string{"not recognized", "no storage database was opened or modified", "dolt"} { + if !strings.Contains(string(out), want) { + t.Errorf("doctor unknown-backend error missing %q:\n%s", want, out) + } + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", "dolt-server.pid", "dolt-server.port"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("doctor created %s for unknown backend (stat error: %v)", name, statErr) + } + } +} + +func TestLegacyInitFlagsReachRemovedBackendGuidance(t *testing.T) { + bd := buildBDForInitTests(t) + tests := []struct { + backend string + args []string + wants []string + }{ + { + backend: configfile.BackendPostgres, + args: []string{ + "init", "--backend=postgres", + "--pg-url=postgres://beads@127.0.0.1:5432/beads", + "--pg-schema=legacy_workspace", + }, + wants: []string{"no longer supported", "general-purpose server databases", "simple and resource-light", "dolt"}, + }, + { + backend: configfile.BackendMySQL, + args: []string{ + "init", "--backend=mysql", + "--mysql-url=beads@tcp(127.0.0.1:3306)/", + "--mysql-database=legacy_workspace", + }, + wants: []string{"no longer supported", "general-purpose server databases", "simple and resource-light", "dolt"}, + }, + { + backend: configfile.BackendSQLite, + args: []string{ + "init", "--backend=sqlite", + "--sqlite-path=beads.db", + }, + wants: []string{"no longer supported", "single engine", "dolt"}, + }, + } + + for _, tt := range tests { + t.Run(tt.backend, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + cmd := exec.Command(bd, tt.args...) + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("legacy %s init unexpectedly succeeded: %s", tt.backend, out) + } + + message := string(out) + if strings.Contains(message, "unknown flag") { + t.Errorf("legacy %s init stopped at argument parsing instead of rollback guidance: %s", tt.backend, message) + } + for _, want := range tt.wants { + if !strings.Contains(message, want) { + t.Errorf("legacy %s init error missing %q: %s", tt.backend, want, message) + } + } + if _, statErr := os.Stat(beadsDir); !os.IsNotExist(statErr) { + t.Fatalf("rejected legacy %s init created workspace state (stat error: %v)", tt.backend, statErr) + } + }) + } +} + +func TestDoltAdministrativeCommandsRejectRemovedBackends(t *testing.T) { + bd := buildBDForInitTests(t) + commands := []struct { + name string + args []string + }{ + {name: "show", args: []string{"dolt", "show"}}, + {name: "status", args: []string{"dolt", "status"}}, + {name: "set", args: []string{"dolt", "set", "host", "127.0.0.1"}}, + {name: "test", args: []string{"dolt", "test"}}, + {name: "start", args: []string{"dolt", "start"}}, + {name: "stop", args: []string{"dolt", "stop"}}, + {name: "killall", args: []string{"dolt", "killall"}}, + {name: "clean-databases", args: []string{"dolt", "clean-databases", "--dry-run"}}, + } + + for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} { + t.Run(backend, func(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o755); err != nil { + t.Fatalf("create beads dir: %v", err) + } + if err := (&configfile.Config{Backend: backend}).Save(beadsDir); err != nil { + t.Fatalf("save config: %v", err) + } + + for _, command := range commands { + t.Run(command.name, func(t *testing.T) { + cmd := exec.Command(bd, command.args...) + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), "BD_DISABLE_METRICS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("%q unexpectedly succeeded for removed backend %s: %s", strings.Join(command.args, " "), backend, out) + } + + message := strings.ToLower(string(out)) + for _, want := range removedBackendWantSubstrings(backend) { + if !strings.Contains(message, want) { + t.Errorf("%q error for %s missing %q: %s", strings.Join(command.args, " "), backend, want, message) + } + } + + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version"} { + path := filepath.Join(beadsDir, name) + if _, statErr := os.Stat(path); !os.IsNotExist(statErr) { + t.Fatalf("%q created local state for removed backend %s at %s (stat error: %v)", strings.Join(command.args, " "), backend, path, statErr) + } + } + }) + } + }) + } +} + +func TestDoltReadOnlyCommandsRejectUnknownBackend(t *testing.T) { + bd := buildBDForInitTests(t) + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + if err := (&configfile.Config{Backend: "mystery", DoltMode: configfile.DoltModeServer, DoltServerPort: 1}).Save(beadsDir); err != nil { + t.Fatalf("save unknown-backend metadata: %v", err) + } + + for _, args := range [][]string{{"dolt", "show"}, {"dolt", "status"}, {"dolt", "killall"}} { + cmd := exec.Command(bd, args...) + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), "BEADS_DOLT_AUTO_START=0", "BD_DISABLE_METRICS=1") + out, err := cmd.CombinedOutput() + if err == nil { + t.Errorf("bd %s unexpectedly treated unknown metadata as Dolt:\n%s", strings.Join(args, " "), out) + continue + } + if !strings.Contains(string(out), "not recognized") || !strings.Contains(string(out), "opened or modified") { + t.Errorf("bd %s error lacks fail-closed guidance:\n%s", strings.Join(args, " "), out) + } + } +} + +func TestDoltKillallRejectsCorruptMetadataBeforeServerCleanup(t *testing.T) { + bd := buildBDForInitTests(t) + root := t.TempDir() + beadsDir := filepath.Join(root, ".beads") + if err := os.MkdirAll(beadsDir, 0o700); err != nil { + t.Fatalf("create .beads: %v", err) + } + metadata := []byte("{\n") + metadataPath := filepath.Join(beadsDir, configfile.ConfigFileName) + if err := os.WriteFile(metadataPath, metadata, 0o600); err != nil { + t.Fatalf("write corrupt metadata: %v", err) + } + + cmd := exec.Command(bd, "dolt", "killall") + cmd.Dir = root + cmd.Env = append(removedBackendTestEnv(beadsDir), + "BEADS_DOLT_SHARED_SERVER=1", + "BEADS_DOLT_AUTO_START=0", + "BEADS_SHARED_SERVER_DIR="+filepath.Join(root, "shared-server"), + "BD_DISABLE_METRICS=1", + ) + out, err := cmd.CombinedOutput() + if err == nil { + t.Fatalf("bd dolt killall unexpectedly ignored corrupt metadata:\n%s", out) + } + message := strings.ToLower(string(out)) + for _, want := range []string{"loading config", "parsing config"} { + if !strings.Contains(message, want) { + t.Errorf("bd dolt killall corrupt-metadata error missing %q:\n%s", want, out) + } + } + after, readErr := os.ReadFile(metadataPath) + if readErr != nil { + t.Fatalf("read metadata after refusal: %v", readErr) + } + if string(after) != string(metadata) { + t.Fatalf("bd dolt killall rewrote corrupt metadata: before %q, after %q", metadata, after) + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db", ".local_version", "dolt-server.pid", "dolt-server.port"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("bd dolt killall created %s before rejecting corrupt metadata (stat error: %v)", name, statErr) + } + } +} + +func removedBackendTestEnv(beadsDir string) []string { + var env []string + for _, entry := range os.Environ() { + if strings.HasPrefix(entry, "BEADS_") || strings.HasPrefix(entry, "BD_") { + continue + } + env = append(env, entry) + } + return append(env, "BEADS_DIR="+beadsDir) +} + +func TestStoreFactoriesRemovedBackendsFailLoud(t *testing.T) { + for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} { + t.Run(backend, func(t *testing.T) { + beadsDir := t.TempDir() + cfg := &configfile.Config{Backend: backend} + if err := cfg.Save(beadsDir); err != nil { + t.Fatalf("save config: %v", err) + } + + factories := map[string]func(context.Context, string) (interface{ Close() error }, error){ + "read-write": func(ctx context.Context, dir string) (interface{ Close() error }, error) { + return newDoltStoreFromConfig(ctx, dir) + }, + "read-only": func(ctx context.Context, dir string) (interface{ Close() error }, error) { + return newReadOnlyStoreFromConfig(ctx, dir) + }, + } + + for name, open := range factories { + t.Run(name, func(t *testing.T) { + store, err := open(t.Context(), beadsDir) + if err == nil { + if store != nil { + _ = store.Close() + } + t.Fatalf("expected removed-backend error for %s", backend) + } + if !strings.Contains(err.Error(), "no longer supported") { + t.Fatalf("error should explain that %s is no longer supported: %v", backend, err) + } + guidance := strings.ToLower(err.Error()) + if !strings.Contains(guidance, "export") || !strings.Contains(guidance, "dolt") { + t.Fatalf("error should provide safe migration guidance: %v", err) + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db"} { + path := filepath.Join(beadsDir, name) + if _, statErr := os.Stat(path); !os.IsNotExist(statErr) { + t.Fatalf("removed backend %s created local storage at %s (stat error: %v)", backend, path, statErr) + } + } + }) + } + }) + } +} + +func TestRequireDoltBackend(t *testing.T) { + for _, cfg := range []*configfile.Config{nil, {}, {Backend: configfile.BackendDolt}} { + if err := requireDoltBackend(cfg); err != nil { + t.Fatalf("Dolt config %#v rejected: %v", cfg, err) + } + } + + for _, backend := range []string{configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite} { + err := requireDoltBackend(&configfile.Config{Backend: backend}) + if err == nil || !strings.Contains(err.Error(), "no longer supported") || !strings.Contains(err.Error(), "export") { + t.Fatalf("removed backend %q guard error = %v, want rollback and migration guidance", backend, err) + } + } +} + +// removedBackendWantSubstrings returns the guidance substrings every removed-backend +// rejection must carry, including the backend-specific rationale marker. +func removedBackendWantSubstrings(backend string) []string { + wants := []string{"no longer supported", "was not opened", "export", "dolt"} + if backend == configfile.BackendSQLite { + return append(wants, "single engine") + } + return append(wants, "general-purpose server databases", "simple and resource-light") +} diff --git a/cmd/bd/telemetry_redact.go b/cmd/bd/telemetry_redact.go new file mode 100644 index 000000000..0be0b2d1e --- /dev/null +++ b/cmd/bd/telemetry_redact.go @@ -0,0 +1,129 @@ +package main + +import ( + "net/url" + "regexp" + "sort" + "strings" +) + +// These expressions recognize password-bearing libpq keyword/value tokens. The +// scrubber is intentionally backend-neutral: command-line telemetry may receive a +// connection string even when bd does not implement that connection's backend. +const dsnWhitespace = `\t\n\f\r \v` + +var dsnPasswordValue = regexp.MustCompile(`(?i)(?:^|[` + dsnWhitespace + `])(?:password|sslpassword)[` + dsnWhitespace + `]*=[` + dsnWhitespace + `]*(?:'((?:[^'\\]|\\.)*)'|((?:[^` + dsnWhitespace + `\\]|\\.)+))`) + +// A libpq keyword/value connection string begins with a recognized connection +// parameter. Requiring the first key to be recognized avoids treating ordinary +// prose such as "transport=rail password=..." as a DSN while still covering valid +// minimal forms such as "password=..." and service-file forms. +var dsnLeadingKeyword = regexp.MustCompile(`(?i)^[` + dsnWhitespace + `]*(?:application_name|channel_binding|client_encoding|connect_timeout|dbname|fallback_application_name|gssencmode|gsslib|host|hostaddr|keepalives|keepalives_count|keepalives_idle|keepalives_interval|krbsrvname|load_balance_hosts|options|passfile|password|port|replication|requirepeer|service|servicefile|sslcert|sslcrl|sslcrldir|sslkey|sslmode|sslpassword|sslrootcert|sslsni|ssl_max_protocol_version|ssl_min_protocol_version|target_session_attrs|tcp_user_timeout|user)[` + dsnWhitespace + `]*=`) + +func scrubStructuredDSNPasswords(dsn, text string) string { + secrets := structuredDSNPasswords(dsn) + sort.Slice(secrets, func(i, j int) bool { return len(secrets[i]) > len(secrets[j]) }) + for _, secret := range secrets { + text = strings.ReplaceAll(text, secret, "xxxxx") + } + return text +} + +func scrubPotentialDSNPasswords(value string) string { + if strings.Contains(value, "://") { + return scrubStructuredDSNPasswords(value, value) + } + if dsnLeadingKeyword.MatchString(value) { + return scrubStructuredDSNPasswords(value, value) + } + return value +} + +func structuredDSNPasswords(dsn string) []string { + seen := make(map[string]bool) + var values []string + add := func(value string) { + if value == "" || seen[value] { + return + } + seen[value] = true + values = append(values, value) + } + + if parsed, err := url.Parse(dsn); err == nil && parsed.Scheme != "" { + if parsed.User != nil { + if password, ok := parsed.User.Password(); ok { + add(password) + add(rawURLUserinfoPassword(dsn)) + } + } + } + // Extract query credentials independently of url.Parse. A malformed escape in + // the path, userinfo, or fragment makes url.Parse reject the entire URL even + // when the password query pair itself is valid. Telemetry redaction must fail + // closed in that case. + addRawURLQueryPasswords(dsn, add) + + for _, match := range dsnPasswordValue.FindAllStringSubmatch(dsn, -1) { + add(match[1]) + add(match[2]) + } + return values +} + +func addRawURLQueryPasswords(dsn string, add func(string)) { + queryStart := strings.IndexByte(dsn, '?') + if queryStart < 0 { + return + } + query := dsn[queryStart+1:] + if fragment := strings.IndexByte(query, '#'); fragment >= 0 { + query = query[:fragment] + } + for _, pair := range strings.Split(query, "&") { + key, value, ok := strings.Cut(pair, "=") + if !ok { + continue + } + decodedKey, err := url.QueryUnescape(key) + if err != nil { + decodedKey = key + } + if !isDSNPasswordKey(key) && !isDSNPasswordKey(decodedKey) { + continue + } + add(value) + if decoded, err := url.QueryUnescape(value); err == nil { + add(decoded) + } + } +} + +func isDSNPasswordKey(key string) bool { + switch strings.ToLower(key) { + case "password", "sslpassword": + return true + default: + return false + } +} + +func rawURLUserinfoPassword(dsn string) string { + scheme := strings.Index(dsn, "://") + if scheme < 0 { + return "" + } + authority := dsn[scheme+len("://"):] + if end := strings.IndexAny(authority, "/?#"); end >= 0 { + authority = authority[:end] + } + at := strings.LastIndex(authority, "@") + if at < 0 { + return "" + } + _, password, ok := strings.Cut(authority[:at], ":") + if !ok { + return "" + } + return password +} diff --git a/cmd/bd/telemetry_scrub_test.go b/cmd/bd/telemetry_scrub_test.go index 740746cb0..dfce9f013 100644 --- a/cmd/bd/telemetry_scrub_test.go +++ b/cmd/bd/telemetry_scrub_test.go @@ -7,12 +7,10 @@ import ( "github.com/spf13/cobra" ) -// TestScrubArgsForTelemetry locks the invariant that no password embedded in a -// --pg-url/--mysql-url value survives into the bd.args telemetry span, across every -// DSN password form pgx/go-sql-driver accept and both the --flag=value and -// --flag value spellings. The pre-fix scrubber handled only URL userinfo, so -// query-param and libpq keyword/value passwords (the confirmed red-team vectors) -// leaked verbatim. +// TestScrubArgsForTelemetry locks the invariant that a positional connection +// string cannot leak an embedded password into the bd.args telemetry span. This +// defense is backend-neutral and remains useful even when bd does not implement +// the connection string's database backend. func TestScrubArgsForTelemetry(t *testing.T) { const secret = "s3cr3t-pw" cases := []struct { @@ -21,34 +19,44 @@ func TestScrubArgsForTelemetry(t *testing.T) { keep []string // non-secret structure that must survive redaction }{ { - name: "pg url userinfo =form", - argv: []string{"init", "--backend=postgres", "--pg-url=postgres://bts:" + secret + "@127.0.0.1:5432/db"}, - keep: []string{"--pg-url=postgres://bts:", "127.0.0.1:5432/db", "--backend=postgres"}, + name: "url userinfo", + argv: []string{"command", "postgres://bts:" + secret + "@127.0.0.1:5432/db"}, + keep: []string{"postgres://bts:", "127.0.0.1:5432/db"}, }, { - name: "pg url query param space form", - argv: []string{"init", "--pg-url", "postgres://bts@127.0.0.1:5432/db?password=" + secret}, + name: "url query param", + argv: []string{"command", "postgres://bts@127.0.0.1:5432/db?password=" + secret}, keep: []string{"127.0.0.1:5432/db", "password="}, }, { - name: "pg url sslpassword =form", - argv: []string{"init", "--pg-url=postgres://bts@h:5432/db?sslpassword=" + secret + "&sslmode=require"}, + name: "url sslpassword", + argv: []string{"command", "postgres://bts@h:5432/db?sslpassword=" + secret + "&sslmode=require"}, keep: []string{"sslmode=require"}, }, { - name: "pg libpq keyword/value =form single token", - argv: []string{"init", "--pg-url=host=127.0.0.1 user=bts password=" + secret + " dbname=db"}, + name: "keyword value connection string", + argv: []string{"command", "host=127.0.0.1 user=bts password=" + secret + " dbname=db"}, keep: []string{"host=127.0.0.1", "user=bts", "dbname=db"}, }, { - name: "mysql userinfo space form", - argv: []string{"init", "--mysql-url", "bts:" + secret + "@tcp(127.0.0.1:3306)/db"}, - keep: []string{"tcp(127.0.0.1:3306)/db", "bts:"}, + name: "keyword value connection string with whitespace around equals", + argv: []string{"command", "host = 127.0.0.1 password=" + secret}, + keep: []string{"host = 127.0.0.1", "password="}, }, { - name: "mysql userinfo =form", - argv: []string{"init", "--mysql-url=bts:" + secret + "@tcp(127.0.0.1:3306)/db"}, - keep: []string{"--mysql-url=bts:", "tcp(127.0.0.1:3306)/db"}, + name: "password-only keyword connection string", + argv: []string{"command", "password=" + secret}, + keep: []string{"password="}, + }, + { + name: "service keyword connection string", + argv: []string{"command", "service=production password=" + secret}, + keep: []string{"service=production", "password="}, + }, + { + name: "scheme-less userinfo", + argv: []string{"command", "bts:" + secret + "@tcp(127.0.0.1:3306)/db"}, + keep: []string{"tcp(127.0.0.1:3306)/db", "bts:"}, }, } for _, tc := range cases { @@ -78,11 +86,24 @@ func TestScrubArgsForTelemetryLeavesOrdinaryArgs(t *testing.T) { if out := scrubArgsForTelemetry(argv, nil); out != "create --title document the password= knob" { t.Fatalf("over-redacted ordinary args: got %q", out) } + argv = []string{"create", "--title", "transport=rail password=foo"} + if out := scrubArgsForTelemetry(argv, nil); out != "create --title transport=rail password=foo" { + t.Fatalf("over-redacted non-DSN key/value text: got %q", out) + } argv = []string{"weird", "postgres://u:leak@h:5432/db"} if out := scrubArgsForTelemetry(argv, nil); strings.Contains(out, "leak") { t.Fatalf("userinfo password not scrubbed as defense in depth: %q", out) } + + for _, arg := range []string{ + "postgres://u@h:5432/db?password=leak", + "host=h user=u password=leak dbname=db", + } { + if out := scrubArgsForTelemetry([]string{"weird", arg}, nil); strings.Contains(out, "leak") { + t.Fatalf("positional DSN password not scrubbed as defense in depth: %q", out) + } + } } // TestSecretFlagTokensResolvesByCommand proves -p is treated as secret only on the @@ -190,6 +211,14 @@ func TestScrubArgsForTelemetryRedactsShorthandCluster(t *testing.T) { name: "boolean shorthand -v then -p cluster", argv: []string{"federation", "add-peer", "partner", "h:3306/db", "-vp" + secret}, }, + { + name: "boolean shorthand -q then separate -p value", + argv: []string{"federation", "add-peer", "partner", "h:3306/db", "-qp", secret}, + }, + { + name: "boolean shorthand -v then separate -p value", + argv: []string{"federation", "add-peer", "partner", "h:3306/db", "-vp", secret}, + }, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { @@ -220,3 +249,194 @@ func TestScrubArgsForTelemetryKeepsOverloadedShortFlag(t *testing.T) { t.Fatalf("over-redacted non-secret -p=prefix: got %q", out) } } + +// TestTelemetryRedactionURLInFlagEqualsValue covers URL values embedded in a +// --flag=value argv element. The flag prefix must not prevent URL query parsing. +func TestTelemetryRedactionURLInFlagEqualsValue(t *testing.T) { + const secret = "query-secret" + arg := "--remote=postgres://bts@db.example/beads?password=" + secret + out := scrubArgsForTelemetry([]string{"init", arg}, nil) + if strings.Contains(out, secret) { + t.Fatalf("PASSWORD LEAK: URL query password in --flag=value survived telemetry scrub: %q", out) + } +} + +// TestTelemetryRedactionMalformedURLQuery fails closed when a URL-shaped DSN has +// an invalid percent escape. net/url rejects the whole URL in that case, but the +// query password must still never reach the bd.args telemetry span. +func TestTelemetryRedactionMalformedURLQuery(t *testing.T) { + const secret = "query-secret" + arg := "postgres://bts@db.example/beads%zz?password=" + secret + "&sslmode=require" + out := scrubArgsForTelemetry([]string{"command", arg}, nil) + if strings.Contains(out, secret) { + t.Fatalf("PASSWORD LEAK: malformed URL query password survived telemetry scrub: %q", out) + } + if !strings.Contains(out, "password=xxxxx") || !strings.Contains(out, "sslmode=require") { + t.Fatalf("malformed URL query structure was not preserved after redaction: %q", out) + } +} + +// TestScrubArgsForTelemetryAdversarialDSNVectors ports the adversarial regression +// vectors from the deleted internal/storage/pgdialect redaction tests +// (redact_error_test.go, redact_matrix_test.go). Each vector was a real leak or a +// scrubber-bypass near miss in an earlier redactor, so they are pinned here against +// the argv scrubber — the telemetry sink is backend-neutral and keeps receiving +// these DSN shapes even though the backends that motivated them are gone. +// +// Historical failure modes locked in, per case: +// - percent-encoded userinfo/query passwords must vanish in BOTH the raw +// (SUPER%2ASECRET) and decoded (SUPER*SECRET) forms; +// - percent-encoded query KEYS (pass%77ord, sslpass%77ord, %70assword) decode to +// password keys and bypassed key matching done on the raw key only; +// - password=SUPER\ SECRET: pgx accepts the backslash-escaped space as part of a +// single value, but a \S+-shaped value regex stopped at the space and shipped +// with the tail " SECRET" left in cleartext; +// - a single-quoted libpq password containing spaces is one value, not several; +// - pgx treats \v as inter-token whitespace, but Go's regexp \s class does not +// include \v, so a (^|\s)-anchored password regex never matched after \v and the +// password leaked entirely; +// - when one collected secret is a prefix of another (userinfo "foo", query +// "fooACTUAL"), replacing the short secret first turned "fooACTUAL" into +// "xxxxxACTUAL" and the tail survived; replacement must be length-descending. +func TestScrubArgsForTelemetryAdversarialDSNVectors(t *testing.T) { + const secret = "SUPERSECRET" + cases := []struct { + name string + dsn string + leaks []string // every cleartext form that must NOT survive redaction + keep []string // non-secret structure that must survive redaction + }{ + { + name: "url userinfo percent-encoded password", + dsn: "postgres://u:SUPER%2ASECRET@h:5432/db", + leaks: []string{"SUPER%2ASECRET", "SUPER*SECRET"}, + keep: []string{"postgres://u:", "h:5432/db"}, + }, + { + name: "url userinfo percent-encoded special chars", + dsn: "postgres://bts:p%40ss%3Aw%2Frd-" + secret + "@127.0.0.1:5432/db", + leaks: []string{"p%40ss%3Aw%2Frd-" + secret, "p@ss:w/rd-" + secret}, + keep: []string{"postgres://bts:", "127.0.0.1:5432/db"}, + }, + { + name: "url query param percent-encoded value", + dsn: "postgres://u@h:5432/db?password=SUPER%2ASECRET", + leaks: []string{"SUPER%2ASECRET", "SUPER*SECRET"}, + keep: []string{"password=", "h:5432/db"}, + }, + { + name: "url query param percent-encoded key (pass%77ord)", + dsn: "postgres://u@h:5432/db?pass%77ord=" + secret, + leaks: []string{secret}, + keep: []string{"pass%77ord=", "h:5432/db"}, + }, + { + name: "url query sslpassword percent-encoded key (sslpass%77ord)", + dsn: "postgres://u@h:5432/db?sslpass%77ord=" + secret + "&sslmode=require", + leaks: []string{secret}, + keep: []string{"sslpass%77ord=", "sslmode=require"}, + }, + { + name: "url query param fully percent-encoded key (%70assword)", + dsn: "postgres://u@h:5432/db?%70assword=" + secret, + leaks: []string{secret}, + keep: []string{"%70assword=", "h:5432/db"}, + }, + { + name: "url query password with sslmode preserved", + dsn: "postgres://bts@127.0.0.1:5432/db?password=" + secret + "&sslmode=disable", + leaks: []string{secret}, + keep: []string{"sslmode=disable", "127.0.0.1:5432/db"}, + }, + { + name: "url userinfo password with sslmode and application_name preserved", + dsn: "postgres://bts:" + secret + "@127.0.0.1:5432/db?sslmode=require&application_name=beads", + leaks: []string{secret}, + keep: []string{"sslmode=require", "application_name=beads", "127.0.0.1:5432/db"}, + }, + { + name: "url userinfo password but no user", + dsn: "postgres://:" + secret + "@h:5432/db", + leaks: []string{secret}, + keep: []string{"h:5432/db"}, + }, + { + name: "keyword value password with backslash-escaped whitespace", + dsn: `host=h user=u password=SUPER\ SECRET dbname=db`, + // "SECRET" pins the historical shipped bug: the tail after the escaped + // space must not survive in cleartext. + leaks: []string{"SECRET", `SUPER\`}, + keep: []string{"host=h", "user=u", "dbname=db"}, + }, + { + name: "keyword value single-quoted password containing spaces", + dsn: "host=h user=u password='se cret " + secret + "' dbname=db", + leaks: []string{"se cret", secret}, + keep: []string{"host=h", "user=u", "dbname=db"}, + }, + { + name: "keyword value single-quoted password", + dsn: "host=h user=u password='" + secret + "' dbname=db", + leaks: []string{secret}, + keep: []string{"host=h", "user=u", "dbname=db"}, + }, + { + name: "keyword value vertical-tab separator", + dsn: "host=h user=u\vpassword=" + secret + " dbname=db", + leaks: []string{secret}, + keep: []string{"host=h", "dbname=db"}, + }, + { + name: "keyword value sslpassword with sslmode preserved", + dsn: "host=h user=u sslpassword=" + secret + " sslmode=require dbname=db", + leaks: []string{secret}, + keep: []string{"host=h", "sslmode=require", "dbname=db"}, + }, + { + name: "keyword value password but no user", + dsn: "host=h port=5432 password=" + secret + " dbname=db", + leaks: []string{secret}, + keep: []string{"host=h", "port=5432", "dbname=db"}, + }, + { + name: "overlapping secrets where one is a prefix of another", + dsn: "postgres://u:foo@h:5432/db?password=fooACTUAL", + leaks: []string{"ACTUAL", ":foo@"}, + keep: []string{"postgres://u:", "h:5432/db"}, + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + out := scrubArgsForTelemetry([]string{"command", tc.dsn}, nil) + for _, leak := range tc.leaks { + if strings.Contains(out, leak) { + t.Errorf("PASSWORD LEAK: %q survived telemetry scrub of %q: %q", leak, tc.dsn, out) + } + } + if !strings.Contains(out, "xxxxx") { + t.Errorf("expected redaction marker xxxxx in %q", out) + } + for _, k := range tc.keep { + if !strings.Contains(out, k) { + t.Errorf("expected %q to survive redaction in %q", k, out) + } + } + }) + } +} + +// TestScrubArgsForTelemetryPasswordlessDSNUnchanged ports the deleted matrix +// round-trip invariant: a DSN carrying no password must pass through the scrubber +// byte-for-byte unchanged, in both URL and libpq keyword/value form. Over-redaction +// here would destroy the non-secret operational signal the span exists to carry. +func TestScrubArgsForTelemetryPasswordlessDSNUnchanged(t *testing.T) { + for _, dsn := range []string{ + "postgres://bts@127.0.0.1:5432/db?application_name=beads&sslmode=require", + "host=127.0.0.1 port=5432 user=bts dbname=db sslmode=require", + } { + want := "command " + dsn + if out := scrubArgsForTelemetry([]string{"command", dsn}, nil); out != want { + t.Errorf("passwordless DSN altered by scrubber:\n in = %q\n out = %q", want, out) + } + } +} diff --git a/cmd/bd/vc.go b/cmd/bd/vc.go index daba45191..499752c44 100644 --- a/cmd/bd/vc.go +++ b/cmd/bd/vc.go @@ -176,10 +176,6 @@ Examples: return HandleErrorRespectJSON("commit message is required (use -m, --message, or --stdin)") } - if err := errExplicitCommitUnsupported(store, "vc commit"); err != nil { - return HandleErrorRespectJSON("%v", err) - } - commandDidExplicitDoltCommit = true if err := store.Commit(ctx, vcCommitMessage); err != nil { if isDoltNothingToCommit(err) { diff --git a/cmd/bd/version_tracking.go b/cmd/bd/version_tracking.go index acba00814..1ef580632 100644 --- a/cmd/bd/version_tracking.go +++ b/cmd/bd/version_tracking.go @@ -163,6 +163,10 @@ func autoMigrateOnVersionBump(beadsDir string) { if cfg == nil { cfg = configfile.DefaultConfig() } + if cfg.GetBackend() != configfile.BackendDolt { + debug.Logf("auto-migrate: skipping Dolt migration for backend %q", cfg.GetBackend()) + return + } if cfg.IsDoltProxiedServerMode() { debug.Logf("auto-migrate: skipping embedded migration, proxied-server handled after UOW provider init") diff --git a/cmd/bd/version_tracking_test.go b/cmd/bd/version_tracking_test.go index 01678adef..fa46d271b 100644 --- a/cmd/bd/version_tracking_test.go +++ b/cmd/bd/version_tracking_test.go @@ -434,5 +434,5 @@ func TestAutoMigrateOnVersionBump_NoDatabase(t *testing.T) { // TestAutoMigrateOnVersionBump_RefusesDowngrade, and TestAutoMigrateOnVersionBump_TracksMaxVersion // were removed because they depended on the SQLite storage backend (sqlite.New) for round-trip // persistence testing through autoMigrateOnVersionBump -> dolt.NewFromConfig. -// Since SQLite support has been removed, auto-migration is only exercised with Dolt backends. +// Automatic schema migration is exercised here through the Dolt backend. // Dolt-based migration testing is covered by TestInitDoltMetadata in init_test.go. diff --git a/default.nix b/default.nix index bb503ed7c..a440d1a7e 100644 --- a/default.nix +++ b/default.nix @@ -19,7 +19,7 @@ buildGoModule { # proxyVendor avoids vendor/modules.txt consistency checks when the vendored # tree lags go.mod/go.sum. proxyVendor = true; - vendorHash = "sha256-Ij4xnWQLre/uE48TGMJRSGrunLqfXQ8MVBA+NCKlhLE="; + vendorHash = "sha256-j+KnR2/0AxVkSfwO/C6/Zo2FjIC7iQs8RlZlrBt/8wc="; # Match go.mod to the selected Nix Go toolchain. buildGoModule also builds # vendored dependencies in the Nix sandbox, where toolchain downloads are not diff --git a/engdocs/PERFORMANCE_TESTING.md b/engdocs/PERFORMANCE_TESTING.md index a2aa3395f..741fdb8e3 100644 --- a/engdocs/PERFORMANCE_TESTING.md +++ b/engdocs/PERFORMANCE_TESTING.md @@ -82,7 +82,7 @@ Benchmarks automatically generate CPU profiles: make bench # View profile in browser (flamegraph) -cd internal/storage/sqlite +cd internal/storage/dolt go tool pprof -http=:8080 bench-cpu-*.prof ``` diff --git a/engdocs/TESTING.md b/engdocs/TESTING.md index 2f6244cfe..84b67e417 100644 --- a/engdocs/TESTING.md +++ b/engdocs/TESTING.md @@ -198,7 +198,7 @@ Most tests are <0.01s and very fast. ``` cmd/bd/ - Main CLI tests (82 test files, most of the suite) internal/beads/ - Core beads library tests -internal/storage/ - Storage backend tests (SQLite, memory) +internal/storage/ - Storage backend tests (Dolt embedded/server, conformance) internal/rpc/ - RPC protocol tests internal/*/ - Various internal package tests ``` diff --git a/examples/library-usage/README.md b/examples/library-usage/README.md index 9eac33788..6ff70550e 100644 --- a/examples/library-usage/README.md +++ b/examples/library-usage/README.md @@ -35,9 +35,9 @@ import ( func main() { ctx := context.Background() - // Find and open database - dbPath := beads.FindDatabasePath() - store, err := beads.Open(ctx, dbPath) + // Find the workspace and open its configured Dolt implementation + beadsDir := beads.FindBeadsDir() + store, err := beads.OpenBestAvailable(ctx, beadsDir) if err != nil { log.Fatal(err) } @@ -145,8 +145,8 @@ type VCStorage struct { beads beads.Storage } -func NewVCStorage(ctx context.Context, dbPath string) (*VCStorage, error) { - store, err := beads.Open(ctx, dbPath) +func NewVCStorage(ctx context.Context, beadsDir string) (*VCStorage, error) { + store, err := beads.OpenBestAvailable(ctx, beadsDir) if err != nil { return nil, err } diff --git a/examples/library-usage/go.mod b/examples/library-usage/go.mod index 4a6e39830..ee773ee30 100644 --- a/examples/library-usage/go.mod +++ b/examples/library-usage/go.mod @@ -5,13 +5,174 @@ go 1.26.2 require github.com/steveyegge/beads v0.0.0 require ( + cel.dev/expr v0.25.1 // indirect + cloud.google.com/go v0.120.0 // indirect + cloud.google.com/go/auth v0.16.2 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect + cloud.google.com/go/compute/metadata v0.9.0 // indirect + cloud.google.com/go/iam v1.5.2 // indirect + cloud.google.com/go/monitoring v1.24.2 // indirect + cloud.google.com/go/storage v1.50.0 // indirect + filippo.io/edwards25519 v1.2.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 // indirect + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 // indirect + github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect + github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirect + github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 // indirect + github.com/HdrHistogram/hdrhistogram-go v1.1.2 // indirect + github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db // indirect + github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible // indirect + github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 // indirect + github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40 // indirect + github.com/apache/thrift v0.23.0 // indirect + github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect + github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect + github.com/aws/aws-sdk-go-v2/config v1.29.8 // indirect + github.com/aws/aws-sdk-go-v2/credentials v1.17.61 // indirect + github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30 // indirect + github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.64 // indirect + github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect + github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect + github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect + github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 // indirect + github.com/aws/aws-sdk-go-v2/service/dynamodb v1.41.0 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.10.15 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 // indirect + github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 // indirect + github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 // indirect + github.com/aws/aws-sdk-go-v2/service/sso v1.25.0 // indirect + github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.0 // indirect + github.com/aws/aws-sdk-go-v2/service/sts v1.33.16 // indirect + github.com/aws/smithy-go v1.24.2 // indirect + github.com/bcicen/jstream v1.0.1 // indirect + github.com/cenkalti/backoff/v4 v4.3.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/clipperhouse/uax29/v2 v2.7.0 // indirect + github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 // indirect + github.com/cockroachdb/apd/v3 v3.2.3 // indirect + github.com/denisbrodbeck/machineid v1.0.1 // indirect + github.com/dolthub/aws-sdk-go-ini-parser v0.0.0-20250305001723-2821c37f6c12 // indirect + github.com/dolthub/dolt/go v0.40.5-0.20260715172757-a6690826d767 // indirect + github.com/dolthub/driver/v2 v2.2.0 // indirect + github.com/dolthub/eventsapi_schema v0.0.0-20260310172945-37a9265ade69 // indirect + github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2 // indirect + github.com/dolthub/fslock v0.0.5 // indirect + github.com/dolthub/go-icu-regex v0.0.0-20260610153742-72563bc7ca83 // indirect + github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3 // indirect + github.com/dolthub/gozstd v0.0.0-20240423170813-23a2903bca63 // indirect + github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037 // indirect + github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71 // indirect + github.com/dolthub/vitess v0.0.0-20260624214226-81d034e0fde8 // indirect github.com/dustin/go-humanize v1.0.1 // indirect + github.com/edsrzf/mmap-go v1.2.0 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.37.0 // indirect + github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect + github.com/esote/minmaxheap v1.0.0 // indirect + github.com/fatih/color v1.16.0 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/flynn-archive/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect + github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-sql-driver/mysql v1.10.0 // indirect + github.com/go-viper/mapstructure/v2 v2.4.0 // indirect + github.com/goccy/go-json v0.10.5 // indirect + github.com/gocraft/dbr/v2 v2.7.6 // indirect + github.com/gofrs/flock v0.8.1 // indirect + github.com/golang-jwt/jwt/v5 v5.3.0 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/google/btree v1.1.2 // indirect + github.com/google/go-github/v57 v57.0.0 // indirect + github.com/google/go-querystring v1.1.0 // indirect + github.com/google/s2a-go v0.1.9 // indirect + github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/google/uuid v1.6.0 // indirect - github.com/mattn/go-isatty v0.0.20 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.6 // indirect + github.com/googleapis/gax-go/v2 v2.14.2 // indirect + github.com/hashicorp/golang-lru v1.0.2 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/juju/gnuflag v1.0.0 // indirect + github.com/kch42/buzhash v0.0.0-20160816060738-9bdec3dec7c6 // indirect + github.com/klauspost/compress v1.18.5 // indirect + github.com/klauspost/cpuid/v2 v2.2.6 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect + github.com/lestrrat-go/strftime v1.2.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.22 // indirect + github.com/mattn/go-runewidth v0.0.23 // indirect + github.com/mohae/uvarint v0.0.0-20160208145430-c3f9e62bf2b0 // indirect github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/oracle/oci-go-sdk/v65 v65.55.0 // indirect + github.com/pelletier/go-toml/v2 v2.2.4 // indirect + github.com/pierrec/lz4/v4 v4.1.21 // indirect + github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pkg/profile v1.5.0 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/prometheus/procfs v0.16.1 // indirect github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rivo/uniseg v0.4.7 // indirect + github.com/sagikazarmark/locafero v0.11.0 // indirect + github.com/sergi/go-diff v1.4.0 // indirect + github.com/sirupsen/logrus v1.9.4 // indirect + github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 // indirect + github.com/sony/gobreaker v0.5.0 // indirect + github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect + github.com/spf13/afero v1.15.0 // indirect + github.com/spf13/cast v1.10.0 // indirect + github.com/spf13/pflag v1.0.10 // indirect + github.com/spf13/viper v1.21.0 // indirect + github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/tealeg/xlsx v1.0.5 // indirect + github.com/tidwall/gjson v1.18.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.1 // indirect + github.com/tidwall/sjson v1.2.5 // indirect + github.com/vbauerster/mpb/v8 v8.7.2 // indirect + github.com/xitongsys/parquet-go v1.6.2 // indirect + github.com/xitongsys/parquet-go-source v0.0.0-20240122235623-d6294584ab18 // indirect + github.com/xtaci/smux v1.5.56 // indirect + github.com/zeebo/xxh3 v1.0.2 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.42.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 // indirect + go.opentelemetry.io/otel v1.44.0 // indirect + go.opentelemetry.io/otel/metric v1.44.0 // indirect + go.opentelemetry.io/otel/sdk v1.44.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.44.0 // indirect + go.opentelemetry.io/otel/trace v1.44.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.0 // indirect + go.yaml.in/yaml/v3 v3.0.4 // indirect + golang.org/x/crypto v0.52.0 // indirect golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect - golang.org/x/sys v0.41.0 // indirect + golang.org/x/net v0.55.0 // indirect + golang.org/x/oauth2 v0.36.0 // indirect + golang.org/x/sync v0.20.0 // indirect + golang.org/x/sys v0.45.0 // indirect + golang.org/x/term v0.43.0 // indirect + golang.org/x/text v0.37.0 // indirect + golang.org/x/time v0.12.0 // indirect + golang.org/x/tools v0.45.0 // indirect + golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect + google.golang.org/api v0.241.0 // indirect + google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect + google.golang.org/grpc v1.81.1 // indirect + google.golang.org/protobuf v1.36.11 // indirect + gopkg.in/go-jose/go-jose.v2 v2.6.3 // indirect + gopkg.in/src-d/go-errors.v1 v1.0.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect modernc.org/libc v1.66.3 // indirect modernc.org/mathutil v1.7.1 // indirect modernc.org/memory v1.11.0 // indirect diff --git a/examples/library-usage/go.sum b/examples/library-usage/go.sum index 2eee93ee4..fa5773f8e 100644 --- a/examples/library-usage/go.sum +++ b/examples/library-usage/go.sum @@ -1,27 +1,1425 @@ +cel.dev/expr v0.25.1 h1:1KrZg61W6TWSxuNZ37Xy49ps13NUovb66QLprthtwi4= +cel.dev/expr v0.25.1/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU= +cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU= +cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY= +cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc= +cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0= +cloud.google.com/go v0.50.0/go.mod h1:r9sluTvynVuxRIOHXQEHMFffphuXHOMZMycpNR5e6To= +cloud.google.com/go v0.52.0/go.mod h1:pXajvRH/6o3+F9jDHZWQ5PbGhn+o8w9qiu/CffaVdO4= +cloud.google.com/go v0.53.0/go.mod h1:fp/UouUEsRkN6ryDKNW/Upv/JBKnv6WDthjR6+vze6M= +cloud.google.com/go v0.54.0/go.mod h1:1rq2OEkV3YMf6n/9ZvGWI3GWw0VoqH/1x2nd8Is/bPc= +cloud.google.com/go v0.56.0/go.mod h1:jr7tqZxxKOVYizybht9+26Z/gUq7tiRzu+ACVAMbKVk= +cloud.google.com/go v0.57.0/go.mod h1:oXiQ6Rzq3RAkkY7N6t3TcE6jE+CIBBbA36lwQ1JyzZs= +cloud.google.com/go v0.62.0/go.mod h1:jmCYTdRCQuc1PHIIJ/maLInMho30T/Y0M4hTdTShOYc= +cloud.google.com/go v0.65.0/go.mod h1:O5N8zS7uWy9vkA9vayVHs65eM1ubvY4h553ofrNHObY= +cloud.google.com/go v0.66.0/go.mod h1:dgqGAjKCDxyhGTtC9dAREQGUJpkceNm1yt590Qno0Ko= +cloud.google.com/go v0.72.0/go.mod h1:M+5Vjvlc2wnp6tjzE102Dw08nGShTscUx2nZMufOKPI= +cloud.google.com/go v0.74.0/go.mod h1:VV1xSbzvo+9QJOxLDaJfTjx5e+MePCpCWwvftOeQmWk= +cloud.google.com/go v0.78.0/go.mod h1:QjdrLG0uq+YwhjoVOLsS1t7TW8fs36kLs4XO5R5ECHg= +cloud.google.com/go v0.79.0/go.mod h1:3bzgcEeQlzbuEAYu4mrWhKqWjmpprinYgKJLgKHnbb8= +cloud.google.com/go v0.81.0/go.mod h1:mk/AM35KwGk/Nm2YSeZbxXdrNK3KZOYHmLkOqC2V6E0= +cloud.google.com/go v0.82.0/go.mod h1:vlKccHJGuFBFufnAnuB08dfEH9Y3H7dzDzRECFdC2TA= +cloud.google.com/go v0.83.0/go.mod h1:Z7MJUsANfY0pYPdw0lbnivPx4/vhy/e2FEkSkF7vAVY= +cloud.google.com/go v0.84.0/go.mod h1:RazrYuxIK6Kb7YrzzhPoLmCVzl7Sup4NrbKPg8KHSUM= +cloud.google.com/go v0.87.0/go.mod h1:TpDYlFy7vuLzZMMZ+B6iRiELaY7z/gJPaqbMx6mlWcY= +cloud.google.com/go v0.90.0/go.mod h1:kRX0mNRHe0e2rC6oNakvwQqzyDmg57xJ+SZU1eT2aDQ= +cloud.google.com/go v0.93.3/go.mod h1:8utlLll2EF5XMAV15woO4lSbWQlk8rer9aLOfLh7+YI= +cloud.google.com/go v0.94.1/go.mod h1:qAlAugsXlC+JWO+Bke5vCtc9ONxjQT3drlTTnAplMW4= +cloud.google.com/go v0.97.0/go.mod h1:GF7l59pYBVlXQIBLx3a761cZ41F9bBH3JUlihCt2Udc= +cloud.google.com/go v0.99.0/go.mod h1:w0Xx2nLzqWJPuozYQX+hFfCSI8WioryfRDzkoI/Y2ZA= +cloud.google.com/go v0.100.1/go.mod h1:fs4QogzfH5n2pBXBP9vRiU+eCny7lD2vmFZy79Iuw1U= +cloud.google.com/go v0.100.2/go.mod h1:4Xra9TjzAeYHrl5+oeLlzbM2k3mjVhZh4UqTZ//w99A= +cloud.google.com/go v0.120.0 h1:wc6bgG9DHyKqF5/vQvX1CiZrtHnxJjBlKUyF9nP6meA= +cloud.google.com/go v0.120.0/go.mod h1:/beW32s8/pGRuj4IILWQNd4uuebeT4dkOhKmkfit64Q= +cloud.google.com/go/auth v0.16.2 h1:QvBAGFPLrDeoiNjyfVunhQ10HKNYuOwZ5noee0M5df4= +cloud.google.com/go/auth v0.16.2/go.mod h1:sRBas2Y1fB1vZTdurouM0AzuYQBMZinrUYL8EufhtEA= +cloud.google.com/go/auth/oauth2adapt v0.2.8 h1:keo8NaayQZ6wimpNSmW5OPc283g65QNIiLpZnkHRbnc= +cloud.google.com/go/auth/oauth2adapt v0.2.8/go.mod h1:XQ9y31RkqZCcwJWNSx2Xvric3RrU88hAYYbjDWYDL+c= +cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o= +cloud.google.com/go/bigquery v1.3.0/go.mod h1:PjpwJnslEMmckchkHFfq+HTD2DmtT67aNFKH1/VBDHE= +cloud.google.com/go/bigquery v1.4.0/go.mod h1:S8dzgnTigyfTmLBfrtrhyYhwRxG72rYxvftPBK2Dvzc= +cloud.google.com/go/bigquery v1.5.0/go.mod h1:snEHRnqQbz117VIFhE8bmtwIDY80NLUZUMb4Nv6dBIg= +cloud.google.com/go/bigquery v1.7.0/go.mod h1://okPTzCYNXSlb24MZs83e2Do+h+VXtc4gLoIoXIAPc= +cloud.google.com/go/bigquery v1.8.0/go.mod h1:J5hqkt3O0uAFnINi6JXValWIb1v0goeZM77hZzJN/fQ= +cloud.google.com/go/compute v0.1.0/go.mod h1:GAesmwr110a34z04OlxYkATPBEfVhkymfTBXtfbBFow= +cloud.google.com/go/compute v1.2.0/go.mod h1:xlogom/6gr8RJGBe7nT2eGsQYAFUbbv8dbC29qE3Xmw= +cloud.google.com/go/compute v1.3.0/go.mod h1:cCZiE1NHEtai4wiufUhW8I8S1JKkAnhnQJWM7YD99wM= +cloud.google.com/go/compute v1.5.0/go.mod h1:9SMHyhJlzhlkJqrPAc839t2BZFTSk6Jdj6mkzQJeu0M= +cloud.google.com/go/compute/metadata v0.9.0 h1:pDUj4QMoPejqq20dK0Pg2N4yG9zIkYGdBtwLoEkH9Zs= +cloud.google.com/go/compute/metadata v0.9.0/go.mod h1:E0bWwX5wTnLPedCKqk3pJmVgCBSM6qQI1yTBdEb3C10= +cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE= +cloud.google.com/go/datastore v1.1.0/go.mod h1:umbIZjpQpHh4hmRpGhH4tLFup+FVzqBi1b3c64qFpCk= +cloud.google.com/go/firestore v1.6.1/go.mod h1:asNXNOzBdyVQmEU+ggO8UPodTkEVFW5Qx+rwHnAz+EY= +cloud.google.com/go/iam v0.1.0/go.mod h1:vcUNEa0pEm0qRVpmWepWaFMIAI8/hjB9mO8rNCJtF6c= +cloud.google.com/go/iam v0.1.1/go.mod h1:CKqrcnI/suGpybEHxZ7BMehL0oA4LpdyJdUlTl9jVMw= +cloud.google.com/go/iam v0.3.0/go.mod h1:XzJPvDayI+9zsASAFO68Hk07u3z+f+JrT2xXNdp4bnY= +cloud.google.com/go/iam v1.5.2 h1:qgFRAGEmd8z6dJ/qyEchAuL9jpswyODjA2lS+w234g8= +cloud.google.com/go/iam v1.5.2/go.mod h1:SE1vg0N81zQqLzQEwxL2WI6yhetBdbNQuTvIKCSkUHE= +cloud.google.com/go/kms v1.1.0/go.mod h1:WdbppnCDMDpOvoYBMn1+gNmOeEoZYqAv+HeuKARGCXI= +cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxsnnOA= +cloud.google.com/go/monitoring v1.1.0/go.mod h1:L81pzz7HKn14QCMaCs6NTQkdBnE87TElyanS95vIcl4= +cloud.google.com/go/monitoring v1.4.0/go.mod h1:y6xnxfwI3hTFWOdkOaD7nfJVlwuC3/mS/5kvtT131p4= +cloud.google.com/go/monitoring v1.24.2 h1:5OTsoJ1dXYIiMiuL+sYscLc9BumrL3CarVLL7dd7lHM= +cloud.google.com/go/monitoring v1.24.2/go.mod h1:x7yzPWcgDRnPEv3sI+jJGBkwl5qINf+6qY4eq0I9B4U= +cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I= +cloud.google.com/go/pubsub v1.1.0/go.mod h1:EwwdRX2sKPjnvnqCa270oGRyludottCI76h+R3AArQw= +cloud.google.com/go/pubsub v1.2.0/go.mod h1:jhfEVHT8odbXTkndysNHCcx0awwzvfOlguIAii9o8iA= +cloud.google.com/go/pubsub v1.3.1/go.mod h1:i+ucay31+CNRpDW4Lu78I4xXG+O1r/MAHgjpRVR+TSU= +cloud.google.com/go/pubsub v1.19.0/go.mod h1:/O9kmSe9bb9KRnIAWkzmqhPjHo6LtzGOBYd/kr06XSs= +cloud.google.com/go/secretmanager v1.3.0/go.mod h1:+oLTkouyiYiabAQNugCeTS3PAArGiMJuBqvJnJsyH+U= +cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw= +cloud.google.com/go/storage v1.5.0/go.mod h1:tpKbwo567HUNpVclU5sGELwQWBDZ8gh0ZeosJ0Rtdos= +cloud.google.com/go/storage v1.6.0/go.mod h1:N7U0C8pVQ/+NIKOBQyamJIeKQKkZ+mxpohlUTyfDhBk= +cloud.google.com/go/storage v1.8.0/go.mod h1:Wv1Oy7z6Yz3DshWRJFhqM/UCfaWIRTdp0RXyy7KQOVs= +cloud.google.com/go/storage v1.10.0/go.mod h1:FLPqc6j+Ki4BU591ie1oL6qBQGu2Bl/tZ9ullr3+Kg0= +cloud.google.com/go/storage v1.12.0/go.mod h1:fFLk2dp2oAhDz8QFKwqrjdJvxSp/W2g7nillojlL5Ho= +cloud.google.com/go/storage v1.21.0/go.mod h1:XmRlxkgPjlBONznT2dDUU/5XlpU2OjMnKuqnZI01LAA= +cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= +cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= +cloud.google.com/go/trace v1.0.0/go.mod h1:4iErSByzxkyHWzzlAj63/Gmjz0NH1ASqhJguHpGcr6A= +cloud.google.com/go/trace v1.2.0/go.mod h1:Wc8y/uYyOhPy12KEnXG9XGrvfMz5F5SrYecQlbW1rwM= +contrib.go.opencensus.io/exporter/aws v0.0.0-20200617204711-c478e41e60e9/go.mod h1:uu1P0UCM/6RbsMrgPa98ll8ZcHM858i/AD06a9aLRCA= +contrib.go.opencensus.io/exporter/stackdriver v0.13.10/go.mod h1:I5htMbyta491eUxufwwZPQdcKvvgzMB4O9ni41YnIM8= +contrib.go.opencensus.io/integrations/ocsql v0.1.7/go.mod h1:8DsSdjz3F+APR+0z0WkU1aRorQCFfRxvqjUUPMbF3fE= +dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= +filippo.io/edwards25519 v1.2.0 h1:crnVqOiS4jqYleHd9vaKZ+HKtHfllngJIiOpNpoJsjo= +filippo.io/edwards25519 v1.2.0/go.mod h1:xzAOLCNug/yB62zG1bQ8uziwrIqIuxhctzJT18Q77mc= +gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zumjgTw83q2ge/PI+yyw8= +github.com/Azure/azure-amqp-common-go/v3 v3.2.1/go.mod h1:O6X1iYHP7s2x7NjUKsXVhkwWrQhxrd+d8/3rRadj4CI= +github.com/Azure/azure-amqp-common-go/v3 v3.2.2/go.mod h1:O6X1iYHP7s2x7NjUKsXVhkwWrQhxrd+d8/3rRadj4CI= +github.com/Azure/azure-pipeline-go v0.2.3/go.mod h1:x841ezTBIMG6O3lAcl8ATHnsOPVl2bqk7S3ta6S6u4k= +github.com/Azure/azure-sdk-for-go v51.1.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go v59.3.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= +github.com/Azure/azure-sdk-for-go/sdk/azcore v0.19.0/go.mod h1:h6H6c8enJmmocHUbLiiGY6sx7f9i+X3m1CHdd5c6Rdw= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.0.0/go.mod h1:uGG2W01BaETf0Ozp+QxxKJdMBNRWPdstHG0Fmdwn1/U= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.0/go.mod h1:bjGvMhVMb+EEm3VRNQawDMUyMMjo+S5ewNjflkep/0Q= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0 h1:fou+2+WFTib47nS+nz/ozhEBnvU96bKHy6LjRsY4E28= +github.com/Azure/azure-sdk-for-go/sdk/azcore v1.21.0/go.mod h1:t76Ruy8AHvUAC8GfMWJMa0ElSbuIcO03NLpynfbgsPA= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v0.11.0/go.mod h1:HcM1YX14R7CJcghJGOYCgdezslRSVzqwLf/q+4Y2r/0= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.0.0/go.mod h1:+6sju8gk8FRmSajX3Oz4G5Gm7P+mbqE9FVaXXFYTkCM= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0/go.mod h1:OQeznEEkTZ9OrhHJoDD8ZDq51FHgXjqtP9z6bEwBq9U= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1 h1:Hk5QBxZQC1jb2Fwj6mpzme37xbCDdNTxU7O9eb5+LB4= +github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.13.1/go.mod h1:IYus9qsFobWIc2YVwe/WPjcnyCkPKtnHAqUYeebc8z0= +github.com/Azure/azure-sdk-for-go/sdk/internal v0.7.0/go.mod h1:yqy467j36fJxcRV2TzfVZ1pCb5vxm4BtZPUdYWe/Xo8= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.0.0/go.mod h1:eWRD7oawr1Mu1sLCawqVc0CUiF43ia3qQMxLscsKQ9w= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0/go.mod h1:okt5dMMTOFjX/aovMlrjvvXoPMBVSPzk9185BT0+eZM= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 h1:9iefClla7iYpfYWdzPCRDozdmndjTm8DXdpCzPajMgA= +github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2/go.mod h1:XtLgD3ZD34DAaVIIAyG3objl5DynM3CQ/vMcbBNJZGI= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/internal v1.0.0/go.mod h1:ceIuwmxDWptoW3eCqSXlnPsZFKh4X+R38dWPv7GS9Vs= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0/go.mod h1:s1tW/At+xHqjNFvWU4G0c0Qv33KOhvbGNj0RCTQDV8s= +github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.2.0/go.mod h1:c+Lifp3EDEamAkPVzMooRNOK6CZjNSdEnf1A7jsI9u4= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.1.0/go.mod h1:7QJP7dr2wznCMeqIrhMgWGf7XpAQnVrJqDm9nvV3Cu4= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 h1:jWQK1GI+LeGGUKBADtcH2rRqPxYB1Ljwms5gFA2LqrM= +github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew= +github.com/Azure/azure-service-bus-go v0.11.5/go.mod h1:MI6ge2CuQWBVq+ly456MY7XqNLJip5LO1iSFodbNLbU= +github.com/Azure/azure-storage-blob-go v0.14.0/go.mod h1:SMqIBi+SuiQH32bvyjngEewEeXoPfKMgWlBDaYf6fck= +github.com/Azure/go-amqp v0.16.0/go.mod h1:9YJ3RhxRT1gquYnzpZO1vcYMMpAdJT+QEg6fwmw9Zlg= +github.com/Azure/go-amqp v0.16.4/go.mod h1:9YJ3RhxRT1gquYnzpZO1vcYMMpAdJT+QEg6fwmw9Zlg= +github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= +github.com/Azure/go-autorest/autorest v0.11.18/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= +github.com/Azure/go-autorest/autorest v0.11.19/go.mod h1:dSiJPy22c3u0OtOKDNttNgqpNFY/GeWa7GH/Pz56QRA= +github.com/Azure/go-autorest/autorest v0.11.22/go.mod h1:BAWYUWGPEtKPzjVkp0Q6an0MJcJDsoh5Z1BFAEFs4Xs= +github.com/Azure/go-autorest/autorest/adal v0.9.5/go.mod h1:B7KF7jKIeC9Mct5spmyCB/A8CG/sEz1vwIRGv/bbw7A= +github.com/Azure/go-autorest/autorest/adal v0.9.13/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= +github.com/Azure/go-autorest/autorest/adal v0.9.14/go.mod h1:W/MM4U6nLxnIskrw4UwWzlHfGjwUS50aOsc/I3yuU8M= +github.com/Azure/go-autorest/autorest/adal v0.9.17/go.mod h1:XVVeme+LZwABT8K5Lc3hA4nAe8LDBVle26gTrguhhPQ= +github.com/Azure/go-autorest/autorest/azure/auth v0.5.9/go.mod h1:hg3/1yw0Bq87O3KvvnJoAh34/0zbP7SFizX/qN5JvjU= +github.com/Azure/go-autorest/autorest/azure/cli v0.4.2/go.mod h1:7qkJkT+j6b+hIpzMOwPChJhTqS8VbsqqgULzMNRugoM= +github.com/Azure/go-autorest/autorest/date v0.3.0/go.mod h1:BI0uouVdmngYNUzGWeSYnokU+TrmwEsOqdt8Y6sso74= +github.com/Azure/go-autorest/autorest/mocks v0.4.1/go.mod h1:LTp+uSrOhSkaKrUy935gNZuuIPPVsHlr9DSOxSayd+k= +github.com/Azure/go-autorest/autorest/to v0.4.0/go.mod h1:fE8iZBn7LQR7zH/9XU2NcPR4o9jEImooCeWJcYV/zLE= +github.com/Azure/go-autorest/autorest/validation v0.3.1/go.mod h1:yhLgjC0Wda5DYXl6JAsWyUe4KVNffhoDhG0zVzUMo3E= +github.com/Azure/go-autorest/logger v0.2.1/go.mod h1:T9E3cAhj2VqvPOtCYAvby9aBXkZmbF5NWuPV8+WeEW8= +github.com/Azure/go-autorest/tracing v0.6.0/go.mod h1:+vhtPC754Xsa23ID7GlGsrdKBpUA79WCAKPPZVC2DeU= +github.com/AzureAD/microsoft-authentication-library-for-go v0.4.0/go.mod h1:Vt9sXTKwMyGcOxSmLDMnGPgqsUg7m8pe215qMLrDXw4= +github.com/AzureAD/microsoft-authentication-library-for-go v1.0.0/go.mod h1:kgDmCTgBzIEPFElEF+FK0SdjAor06dRq2Go927dnQ6o= +github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs= +github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo= +github.com/GoogleCloudPlatform/cloudsql-proxy v1.29.0/go.mod h1:spvB9eLJH9dutlbPSRmHvSXXHOwGRyeXh1jVdquA2G8= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0 h1:DHa2U07rk8syqvCge0QIGMCE1WxGj9njT44GH7zNJLQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.31.0/go.mod h1:P4WPRUkOhJC13W//jWpyfJNDAIpvRbAUIYLX/4jtlE0= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0 h1:5IT7xOdq17MtcdtL/vtl6mGfzhaq4m4vpollPRmlsBQ= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.50.0/go.mod h1:ZV4VOm0/eHR06JLrXWe09068dHpr3TRpY9Uo7T+anuA= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0 h1:ig/FpDD2JofP/NExKQUbn7uOSZzJAQqogfqluZK4ed4= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.50.0/go.mod h1:otE2jQekW/PqXk1Awf5lmfokJx4uwuqcj1ab5SpGeW0= +github.com/HdrHistogram/hdrhistogram-go v1.1.2 h1:5IcZpTvzydCQeHzK4Ef/D5rrSqwxob0t8PQPMybUNFM= +github.com/HdrHistogram/hdrhistogram-go v1.1.2/go.mod h1:yDgFjdqOqDEKOvasDdhWNXYg9BVp4O+o5f6V/ehm6Oo= +github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs= +github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db h1:CjPUSXOiYptLbTdr1RceuZgSFDQ7U15ITERUGrUORx8= +github.com/abiosoft/readline v0.0.0-20180607040430-155bce2042db/go.mod h1:rB3B4rKii8V21ydCbIzH5hZiCQE7f5E9SzUb/ZZx530= +github.com/ajstarks/svgo v0.0.0-20180226025133-644b8db467af/go.mod h1:K08gAheRH3/J6wwsYMMT4xOr94bZjxIelGM0+d/wbFw= +github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible h1:8psS8a+wKfiLt1iVDX79F7Y6wUM49Lcha2FMXt4UM8g= +github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible/go.mod h1:T/Aws4fEfogEE9v+HPhhw+CntffsBHJ8nXQCwKr0/g8= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ= +github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/apache/arrow/go/arrow v0.0.0-20200730104253-651201b0f516/go.mod h1:QNYViu/X0HXDHw7m3KXzWSVXIbfUvJqBFe6Gj8/pYA0= +github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40 h1:q4dksr6ICHXqG5hm0ZW5IHyeEJXoIJSOZeBLmWPNeIQ= +github.com/apache/arrow/go/arrow v0.0.0-20211112161151-bc219186db40/go.mod h1:Q7yQnSMnLvcXlZ8RV+jwz/6y1rQTqbX6C82SndT52Zs= +github.com/apache/thrift v0.0.0-20181112125854-24918abba929/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.14.2/go.mod h1:cp2SuWMxlEZw2r+iP2GNCdIi4C1qmUzdZFSVb+bacwQ= +github.com/apache/thrift v0.23.0 h1:wKR6YnefQSEnxpEfmgTPuJibNG4bF0p2TK34tHLWi3s= +github.com/apache/thrift v0.23.0/go.mod h1:zPt6WxgvTOM6hF92y8C+MkEM5LMxZuk4JcQOiU4Esvs= +github.com/aws/aws-sdk-go v1.15.27/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0= +github.com/aws/aws-sdk-go v1.30.19/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= +github.com/aws/aws-sdk-go v1.37.0/go.mod h1:hcU610XS61/+aQV88ixoOzUoG7v3b31pl2zKMmprdro= +github.com/aws/aws-sdk-go v1.43.31/go.mod h1:y4AeaBuwd2Lk+GepC1E9v0qOiTws0MIWAX4oIKwKHZo= +github.com/aws/aws-sdk-go-v2 v1.16.2/go.mod h1:ytwTPBG6fXTZLxxeeCCWj2/EMYp/xDUgX+OET6TLNNU= +github.com/aws/aws-sdk-go-v2 v1.23.0/go.mod h1:i1XDttT4rnf6vxc9AuskLc6s7XBee8rlLilKlc03uAA= +github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY= +github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.4.1/go.mod h1:n8Bs1ElDD2wJ9kCRTczA83gYbBmjSwZp3umc6zF4EeM= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.5.1/go.mod h1:t8PYl/6LzdAqsU4/9tz28V/kU+asFePvpOMkdul0gEQ= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o= +github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI= +github.com/aws/aws-sdk-go-v2/config v1.15.3/go.mod h1:9YL3v07Xc/ohTsxFXzan9ZpFpdTOFl4X65BAKYaz8jg= +github.com/aws/aws-sdk-go-v2/config v1.25.3/go.mod h1:tAByZy03nH5jcq0vZmkcVoo6tRzRHEwSFx3QW4NmDw8= +github.com/aws/aws-sdk-go-v2/config v1.29.8 h1:RpwAfYcV2lr/yRc4lWhUM9JRPQqKgKWmou3LV7UfWP4= +github.com/aws/aws-sdk-go-v2/config v1.29.8/go.mod h1:t+G7Fq1OcO8cXTPPXzxQSnj/5Xzdc9jAAD3Xrn9/Mgo= +github.com/aws/aws-sdk-go-v2/credentials v1.11.2/go.mod h1:j8YsY9TXTm31k4eFhspiQicfXPLZ0gYXA50i4gxPE8g= +github.com/aws/aws-sdk-go-v2/credentials v1.16.2/go.mod h1:sDdvGhXrSVT5yzBDR7qXz+rhbpiMpUYfF3vJ01QSdrc= +github.com/aws/aws-sdk-go-v2/credentials v1.17.61 h1:Hd/uX6Wo2iUW1JWII+rmyCD7MMhOe7ALwQXN6sKDd1o= +github.com/aws/aws-sdk-go-v2/credentials v1.17.61/go.mod h1:L7vaLkwHY1qgW0gG1zG0z/X0sQ5tpIY5iI13+j3qI80= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.12.3/go.mod h1:uk1vhHHERfSVCUnqSqz8O48LBYDSC+k6brng09jcMOk= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.14.4/go.mod h1:t4i+yGHMCcUNIX1x7YVYa6bH/Do7civ5I6cG/6PMfyA= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30 h1:x793wxmUWVDhshP8WW2mlnXuFrO4cOd3HLBroh1paFw= +github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30/go.mod h1:Jpne2tDnYiFascUEs2AWHJL9Yp7A5ZVy3TNyxaAjD6M= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.11.3/go.mod h1:0dHuD2HZZSiwfJSy1FO5bX1hQ1TxVV1QXXjpn3XUE44= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.14.0/go.mod h1:UcgIwJ9KHquYxs6Q5skC9qXjhYMK+JASDYcXQ4X7JZE= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.64 h1:RTko0AQ0i1vWXDM97DkuW6zskgOxFxm4RqC0kmBJFkE= +github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.64/go.mod h1:ty968MpOa5CoQ/ALWNB8Gmfoehof2nRHDR/DZDPfimE= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.9/go.mod h1:AnVH5pvai0pAF4lXRq0bmhbes1u9R8wTE+g+183bZNM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.2.3/go.mod h1:7sGSz1JCKHWWBHq98m6sMtWQikmYPpxjqOydDemiVoM= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4= +github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.3/go.mod h1:ssOhaLpRlh88H3UmEcsBoVKq309quMvm3Ds8e9d4eJM= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.5.3/go.mod h1:ify42Rb7nKeDDPkFjKn7q1bPscVPu/+gmHH8d2c+anU= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A= +github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21/go.mod h1:p+hz+PRAYlY3zcpJhPwXlLC4C+kqn70WIHwnzAfs6ps= +github.com/aws/aws-sdk-go-v2/internal/ini v1.3.10/go.mod h1:8DcYQcz0+ZJaSxANlHIsbbi6S+zMwjwdDqwW3r9AzaE= +github.com/aws/aws-sdk-go-v2/internal/ini v1.7.1/go.mod h1:6fQQgfuGmw8Al/3M2IgIllycxV7ZW7WCdVSqfBeUiCY= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo= +github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.2.3/go.mod h1:5yzAuE9i2RkVAttBl8yxZgQr5OCq4D5yDnG7j9x2L0U= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22 h1:rWyie/PxDRIdhNf4DzRk0lvjVOqFJuNnO8WwaIRVxzQ= +github.com/aws/aws-sdk-go-v2/internal/v4a v1.4.22/go.mod h1:zd/JsJ4P7oGfUhXn1VyLqaRZwPmZwg44Jf2dS84Dm3Y= +github.com/aws/aws-sdk-go-v2/service/dynamodb v1.41.0 h1:kSMAk72LZ5eIdY/W+tVV6VdokciajcDdVClEBVNWNP0= +github.com/aws/aws-sdk-go-v2/service/dynamodb v1.41.0/go.mod h1:yYaWRnVSPyAmexW5t7G3TcuYoalYfT+xQwzWsvtUQ7M= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.9.1/go.mod h1:GeUru+8VzrTXV/83XyMJ80KpH8xO89VPoUileyNQ+tc= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.10.1/go.mod h1:l9ymW25HOqymeU2m1gbUQ3rUIsTwKs8gYHXkqDQUhiI= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7 h1:5EniKhLZe4xzL7a+fU3C2tfUN4nWIqlLesfrjkuPFTY= +github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.7/go.mod h1:x0nZssQ3qZSnIcePWLvcoFisRXJzcTVvYpAAdYX8+GI= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.1.3/go.mod h1:Seb8KNmD6kVTjwRjVEgOT5hPin6sq+v4C2ycJQDwuH8= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.2.3/go.mod h1:R+/S1O4TYpcktbVwddeOYg+uwUfLhADP2S/x4QwsCTM= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13 h1:JRaIgADQS/U6uXDqlPiefP32yXTda7Kqfx+LgspooZM= +github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.9.13/go.mod h1:CEuVn5WqOMilYl+tbccq8+N2ieCy0gVn3OtRb0vBNNM= +github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.10.15 h1:M1R1rud7HzDrfCdlBQ7NjnRsDNEhXO/vGhuD189Ggmk= +github.com/aws/aws-sdk-go-v2/service/internal/endpoint-discovery v1.10.15/go.mod h1:uvFKBSq9yMPV4LGAi7N4awn4tLY+hKE35f8THes2mzQ= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.3/go.mod h1:wlY6SVjuwvh3TVRpTqdy4I1JpBFLX4UGeKZdWntaocw= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.10.3/go.mod h1:Owv1I59vaghv1Ax8zz8ELY8DN7/Y0rGS+WWAmjgi950= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21 h1:c31//R3xgIJMSC8S6hEVq+38DcvUlgFY0FM6mSI5oto= +github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.13.21/go.mod h1:r6+pf23ouCB718FUxaqzZdbpYFyDtehyZcmP5KL9FkA= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.13.3/go.mod h1:Bm/v2IaN6rZ+Op7zX+bOUMdL4fsrYZiD0dsjLhNKwZc= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.16.3/go.mod h1:KZgs2ny8HsxRIRbDwgvJcHHBZPOzQr/+NtGwnP+w2ec= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21 h1:ZlvrNcHSFFWURB8avufQq9gFsheUgjVD9536obIknfM= +github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.21/go.mod h1:cv3TNhVrssKR0O/xxLJVRfd2oazSnZnkUeTf6ctUwfQ= +github.com/aws/aws-sdk-go-v2/service/kms v1.16.3/go.mod h1:QuiHPBqlOFCi4LqdSskYYAWpQlx3PKmohy+rE2F+o5g= +github.com/aws/aws-sdk-go-v2/service/s3 v1.26.3/go.mod h1:g1qvDuRsJY+XghsV6zg00Z4KJ7DtFFCx8fJD2a491Ak= +github.com/aws/aws-sdk-go-v2/service/s3 v1.43.0/go.mod h1:NXRKkiRF+erX2hnybnVU660cYT5/KChRD4iUgJ97cI8= +github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3 h1:HwxWTbTrIHm5qY+CAEur0s/figc3qwvLWsNkF4RPToo= +github.com/aws/aws-sdk-go-v2/service/s3 v1.97.3/go.mod h1:uoA43SdFwacedBfSgfFSjjCvYe8aYBS7EnU5GZ/YKMM= +github.com/aws/aws-sdk-go-v2/service/secretsmanager v1.15.4/go.mod h1:PJc8s+lxyU8rrre0/4a0pn2wgwiDvOEzoOjcJUBr67o= +github.com/aws/aws-sdk-go-v2/service/sns v1.17.4/go.mod h1:kElt+uCcXxcqFyc+bQqZPFD9DME/eC6oHBXvFzQ9Bcw= +github.com/aws/aws-sdk-go-v2/service/sqs v1.18.3/go.mod h1:skmQo0UPvsjsuYYSYMVmrPc1HWCbHUJyrCEp+ZaLzqM= +github.com/aws/aws-sdk-go-v2/service/ssm v1.24.1/go.mod h1:NR/xoKjdbRJ+qx0pMR4mI+N/H1I1ynHwXnO6FowXJc0= +github.com/aws/aws-sdk-go-v2/service/sso v1.11.3/go.mod h1:7UQ/e69kU7LDPtY40OyoHYgRmgfGM4mgsLYtcObdveU= +github.com/aws/aws-sdk-go-v2/service/sso v1.17.2/go.mod h1:/pE21vno3q1h4bbhUOEi+6Zu/aT26UK2WKkDXd+TssQ= +github.com/aws/aws-sdk-go-v2/service/sso v1.25.0 h1:2U9sF8nKy7UgyEeLiZTRg6ShBS22z8UnYpV6aRFL0is= +github.com/aws/aws-sdk-go-v2/service/sso v1.25.0/go.mod h1:qs4a9T5EMLl/Cajiw2TcbNt2UNo/Hqlyp+GiuG4CFDI= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.20.0/go.mod h1:dWqm5G767qwKPuayKfzm4rjzFmVjiBFbOJrpSPnAMDs= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.0 h1:wjAdc85cXdQR5uLx5FwWvGIHm4OPJhTyzUHU8craXtE= +github.com/aws/aws-sdk-go-v2/service/ssooidc v1.29.0/go.mod h1:MlYRNmYu/fGPoxBQVvBYr9nyr948aY/WLUvwBMBJubs= +github.com/aws/aws-sdk-go-v2/service/sts v1.16.3/go.mod h1:bfBj0iVmsUyUg4weDB4NxktD9rDGeKSVWnjTnwbx9b8= +github.com/aws/aws-sdk-go-v2/service/sts v1.25.3/go.mod h1:4EqRHDCKP78hq3zOnmFXu5k0j4bXbRFfCh/zQ6KnEfQ= +github.com/aws/aws-sdk-go-v2/service/sts v1.33.16 h1:BHEK2Q/7CMRMCb3nySi/w8UbIcPhKvYP5s1xf8/izn0= +github.com/aws/aws-sdk-go-v2/service/sts v1.33.16/go.mod h1:cQnB8CUnxbMU82JvlqjKR2HBOm3fe9pWorWBza6MBJ4= +github.com/aws/smithy-go v1.11.2/go.mod h1:3xHYmszWVx2c0kIwQeEVf9uSm4fYZt67FBJnwub1bgM= +github.com/aws/smithy-go v1.17.0/go.mod h1:NukqUGpCZIILqqiV0NIjeFh24kd/FAa4beRb6nbIUPE= +github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng= +github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc= +github.com/bcicen/jstream v1.0.1 h1:BXY7Cu4rdmc0rhyTVyT3UkxAiX3bnLpKLas9btbH5ck= +github.com/bcicen/jstream v1.0.1/go.mod h1:9ielPxqFry7Y4Tg3j4BfjPocfJ3TbsRtXOAYXYmRuAQ= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/bobg/gcsobj v0.1.2/go.mod h1:vS49EQ1A1Ib8FgrL58C8xXYZyOCR2TgzAdopy6/ipa8= +github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8= +github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= +github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= +github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= +github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/clipperhouse/uax29/v2 v2.7.0 h1:+gs4oBZ2gPfVrKPthwbMzWZDaAFPGYK72F0NJv2v7Vk= +github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20200629203442-efcf912fb354/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2 h1:aBangftG7EVZoUb69Os8IaYg++6uMOdKK83QtkkvJik= +github.com/cncf/xds/go v0.0.0-20260202195803-dba9d589def2/go.mod h1:qwXFYgsP6T7XnJtbKlf1HP8AjxZZyzxMmc+Lq5GjlU4= +github.com/cockroachdb/apd v1.1.0/go.mod h1:8Sl8LxpKi29FqWXR16WEFZRNSz3SoPzUzeMeY4+DwBQ= +github.com/cockroachdb/apd/v3 v3.2.3 h1:4Zx+I3R35bFXMnltzmjP79i2cravE4jTRL6ps9Aux80= +github.com/cockroachdb/apd/v3 v3.2.3/go.mod h1:klXJcjp+FffLTHlhIG69tezTDvdP065naDsHzKhYSqc= +github.com/colinmarc/hdfs/v2 v2.1.1/go.mod h1:M3x+k8UKKmxtFu++uAZ0OtDU8jR3jnaZIAc6yK4Ue0c= +github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd v0.0.0-20190719114852-fd7a80b32e1f/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/denisbrodbeck/machineid v1.0.1 h1:geKr9qtkB876mXguW2X6TU4ZynleN6ezuMSRhl4D7AQ= +github.com/denisbrodbeck/machineid v1.0.1/go.mod h1:dJUwb7PTidGDeYyUBmXZ2GphQBbjJCrnectwCyxcUSI= +github.com/denisenkom/go-mssqldb v0.12.0/go.mod h1:iiK0YP1ZeepvmBQk/QpLEhhTNJgfzrpArPY/aFvc9yU= +github.com/devigned/tab v0.1.1/go.mod h1:XG9mPq0dFghrYvoBF3xdRrJzSTX1b7IQrvaL9mzjeJY= +github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= +github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= +github.com/dnaeon/go-vcr v1.1.0/go.mod h1:M7tiix8f0r6mKKJ3Yq/kqU1OYf3MnfmBWVbPx/yU9ko= +github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ= +github.com/dolthub/aws-sdk-go-ini-parser v0.0.0-20250305001723-2821c37f6c12 h1:IdqX7J8vi/Kn3T3Ee0VzqnLqwFmgA2hr8WZETPcQjfM= +github.com/dolthub/aws-sdk-go-ini-parser v0.0.0-20250305001723-2821c37f6c12/go.mod h1:rN7X8BHwkjPcfMQQ2QTAq/xM3leUSGLfb+1Js7Y6TVo= +github.com/dolthub/dolt/go v0.40.5-0.20260715172757-a6690826d767 h1:RSO4YZ5xuZ2EnHv813q2q+QpEqDW1ugjRepPXyDvb7s= +github.com/dolthub/dolt/go v0.40.5-0.20260715172757-a6690826d767/go.mod h1:DXkKITEIpR85Ta86AyjAXYeTULr/tRylidxxy95eraI= +github.com/dolthub/driver/v2 v2.2.0 h1:Qm9BhvvKNmeTDF6kZdDkdLe62CF1W6GrCA3ZDRx/tlk= +github.com/dolthub/driver/v2 v2.2.0/go.mod h1:Ngki9vM88/sqin1RKfUt/9Ex8DmoePtHgY7d4+YoolU= +github.com/dolthub/eventsapi_schema v0.0.0-20260310172945-37a9265ade69 h1:JShhbqMw26nKx3pqqu/cFxOpzBkN+4elVhzuUfgDw2k= +github.com/dolthub/eventsapi_schema v0.0.0-20260310172945-37a9265ade69/go.mod h1:SSLraQS/jGLYFgff3vuZ+JbVUct6vyEeMzjLBqWqoyM= +github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2 h1:u3PMzfF8RkKd3lB9pZ2bfn0qEG+1Gms9599cr0REMww= +github.com/dolthub/flatbuffers/v23 v23.3.3-dh.2/go.mod h1:mIEZOHnFx4ZMQeawhw9rhsj+0zwQj7adVsnBX7t+eKY= +github.com/dolthub/fslock v0.0.5 h1:QoXhBhgY1oumHE26qyE7tgmXUT8qjJwxsIzo54O/B/k= +github.com/dolthub/fslock v0.0.5/go.mod h1:sdofYYqE0D79zNZyB4/kmlnsQOVap1C2yByjGKSirEM= +github.com/dolthub/go-icu-regex v0.0.0-20260610153742-72563bc7ca83 h1:FEMjCGEroDnY/BXyAffVZxUpXhP2GpoUJyyq5KaLn8c= +github.com/dolthub/go-icu-regex v0.0.0-20260610153742-72563bc7ca83/go.mod h1:F3cnm+vMRK1HaU6+rNqQrOCyR03HHhR1GWG2gnPOqaE= +github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3 h1:HdPnbDFCkxyEU1zDHVPcHq8aWFkar3fIz9I9Wz5cC0E= +github.com/dolthub/go-mysql-server v0.20.1-0.20260713210757-6d01d00bbbf3/go.mod h1:AnD2jKQZCf09sM2JhV/cTEtsoEhPNg6pVWjRCBox4Zw= +github.com/dolthub/gozstd v0.0.0-20240423170813-23a2903bca63 h1:OAsXLAPL4du6tfbBgK0xXHZkOlos63RdKYS3Sgw/dfI= +github.com/dolthub/gozstd v0.0.0-20240423170813-23a2903bca63/go.mod h1:lV7lUeuDhH5thVGDCKXbatwKy2KW80L4rMT46n+Y2/Q= +github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037 h1:oIW9HwuWrhxv+4HZxA+QQSKHLqWFyXZ2FmNjUYwkdiM= +github.com/dolthub/ishell v0.0.0-20260414231531-5f031e3e9037/go.mod h1:ehexgi1mPxRTk0Mok/pADALuHbvATulTh6gzr7NzZto= +github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71 h1:bMGS25NWAGTEtT5tOBsCuCrlYnLRKpbJVJkDbrTRhwQ= +github.com/dolthub/jsonpath v0.0.2-0.20240227200619-19675ab05c71/go.mod h1:2/2zjLQ/JOOSbbSboojeg+cAwcRV0fDLzIiWch/lhqI= +github.com/dolthub/vitess v0.0.0-20260624214226-81d034e0fde8 h1:zmKLyRCTiNZnizO++sNXP1QW2bxLE2Y+WJAdu/hcu6s= +github.com/dolthub/vitess v0.0.0-20260624214226-81d034e0fde8/go.mod h1:5SVEJgAhw5nnQUFnGgKI1Svqes1Mw+zKUsalyxmOuG0= +github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk= github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/edsrzf/mmap-go v1.2.0 h1:hXLYlkbaPzt1SaQk+anYwKSRNhufIDCchSPkUD6dD84= +github.com/edsrzf/mmap-go v1.2.0/go.mod h1:19H/e8pUPLicwkyNgOykDXkJ9F0MHE+Z52B8EIth78Q= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.7/go.mod h1:cwu0lG7PUMfa9snN8LXBig5ynNVH9qI8YYLbd1fK2po= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.9.9-0.20210512163311-63b5d3c536b0/go.mod h1:hliV/p42l8fGbc6Y9bQ70uLwIvmJyVE5k4iMKlh8wCQ= +github.com/envoyproxy/go-control-plane v0.9.10-0.20210907150352-cf90f659a021/go.mod h1:AFq3mo9L8Lqqiid3OhADV3RfLJnjiw63cSpi+fDTRC0= +github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNfdSbEPe9Yyl09/B6wBrQ= +github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= +github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= +github.com/esote/minmaxheap v1.0.0 h1:rgA7StnXXpZG6qlM0S7pUmEv1KpWe32rYT4x8J8ntaA= +github.com/esote/minmaxheap v1.0.0/go.mod h1:Ln8+i7fS1k3PLgZI2JAo0iA1as95QnIYiGCrqSJ5FZk= +github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= +github.com/fatih/color v1.16.0 h1:zmkK9Ngbjj+K0yRhTVONQh1p/HknKYSlNT+vZCzyokM= +github.com/fatih/color v1.16.0/go.mod h1:fL2Sau1YI5c0pdGEVCbKQbLXB6edEj1ZgiY4NijnWvE= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/flynn-archive/go-shlex v0.0.0-20150515145356-3f9db97f8568 h1:BMXYYRWTLOJKlh+lOBt6nUQgXAfB7oVIQt5cNreqSLI= +github.com/flynn-archive/go-shlex v0.0.0-20150515145356-3f9db97f8568/go.mod h1:rZfgFAXFS/z/lEd6LJmf9HVZ1LkgYiHx5pHhV5DR16M= +github.com/fogleman/gg v1.2.1-0.20190220221249-0403632d5b90/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k= +github.com/form3tech-oss/jwt-go v3.2.2+incompatible/go.mod h1:pbq4aXjuKjdthFRnoDwaVPLA+WlJuPGy+QneDUgJi2k= +github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g= +github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.6.3/go.mod h1:75u5sXoLsGZoRN5Sgbi1eraJ4GU3++wFwWzhwvtwp4M= +github.com/gin-gonic/gin v1.7.3/go.mod h1:jD2toBW3GZUr5UMcdrwQA10I7RuaFOl/SGeDjXkfUtY= +github.com/go-fonts/dejavu v0.1.0/go.mod h1:4Wt4I4OU2Nq9asgDCteaAaWZOV24E+0/Pwo0gppep4g= +github.com/go-fonts/latin-modern v0.2.0/go.mod h1:rQVLdDMK+mK1xscDwsqM5J8U2jrRa3T0ecnM9pNujks= +github.com/go-fonts/liberation v0.1.1/go.mod h1:K6qoJYypsmfVjWg8KOVDQhLc8UDgIK2HYqyqAO9z7GY= +github.com/go-fonts/stix v0.1.0/go.mod h1:w/c1f0ldAUlJmLBvlbkvVXLAD+tAMqobIIQpmnUIzUY= +github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= +github.com/go-ini/ini v1.25.4/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8= +github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= +github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-latex/latex v0.0.0-20210118124228-b3d85cf34e07/go.mod h1:CO1AlKB2CSIqUrmQPqA0gdRIlnLEY0gK5JGjh37zN5U= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= +github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= +github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= +github.com/go-playground/validator/v10 v10.2.0/go.mod h1:uOYAAleCW8F/7oMFd6aG0GOhaH6EGOAJShg8Id5JGkI= +github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.6.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= +github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= +github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs= +github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= +github.com/gobwas/httphead v0.0.0-20180130184737-2c6c146eadee/go.mod h1:L0fX3K22YWvt/FAX9NnzrNzcI4wNYi9Yku4O0LKYflo= +github.com/gobwas/pool v0.2.0/go.mod h1:q8bcK0KcYlCgd9e7WYLm9LpyS+YeLd8JVDW6WezmKEw= +github.com/gobwas/ws v1.0.2/go.mod h1:szmBTxLgaFppYjEmNtny/v3w89xOydFnnZMcgRRu/EM= +github.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4= +github.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/gocraft/dbr/v2 v2.7.6 h1:ASHKFgCbTLODbb9f756Cl8VAlnvQLKqIzx9E1Cfb7eo= +github.com/gocraft/dbr/v2 v2.7.6/go.mod h1:8IH98S8M8J0JSEiYk0MPH26ZDUKemiQ/GvmXL5jo+Uw= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/gofrs/flock v0.8.1 h1:+gYjHKf32LDeiEEFhQaotPbLuUXjY5ZqxKgXy7n59aw= +github.com/gofrs/flock v0.8.1/go.mod h1:F1TvTiK9OcQqauNUHlbJvyl9Qa1QvF/gOUDKA14jxHU= +github.com/gofrs/uuid v4.0.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM= +github.com/golang-jwt/jwt v3.2.1+incompatible/go.mod h1:8pz2t5EyA70fFQQSrl6XZXzqecmYZeUEB8OUGHkxJ+I= +github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= +github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= +github.com/golang-jwt/jwt/v4 v4.4.1/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v4 v4.4.3/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo= +github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE= +github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang-sql/sqlexp v0.0.0-20170517235910-f1bb20e5a188/go.mod h1:vXjM/+wXQnTPR4KqTKDgJukSZ6amVRtWMPEjE6sQoK8= +github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20191227052852-215e87163ea7/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y= +github.com/golang/mock v1.4.0/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.1/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.3/go.mod h1:UOMv5ysSaYNkG+OFQykRIcU/QvvxJf3p21QfJ2Bt3cw= +github.com/golang/mock v1.4.4/go.mod h1:l3mdAwkq5BuhzHwde/uurv3sEJeZMXNpwsxVWU71h+4= +github.com/golang/mock v1.5.0/go.mod h1:CWnOUgYIOo4TcNZ0wHX3YZCqsaM1I1Jvs6v3mP3KVu8= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.1.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.4/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.3.5/go.mod h1:6O5/vntMXwX2lRkT1hjjk0nAC1IDOTvTlVgjlRvqsdk= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.1/go.mod h1:DopwsBzvsk0Fs44TXzsVbJyPhcCPeIwnvohx4u74HPM= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.3/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/btree v1.1.2/go.mod h1:qOPhT0dTNdNzV6Z/lhRX0YXUafgPLFUh+gZMl761Gm4= +github.com/google/flatbuffers v1.11.0/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/flatbuffers v2.0.0+incompatible/go.mod h1:1AeVuKshWv4vARoZatz6mlQ0JxURH0Kv5+zNeJKJCa8= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.4.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.1/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.7/go.mod h1:n+brtR0CgQNWTVd5ZUFpTBC8YFBDLK/h/bpaJ8/DtOE= +github.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +github.com/google/go-github/v57 v57.0.0 h1:L+Y3UPTY8ALM8x+TV0lg+IEBI+upibemtBD8Q9u7zHs= +github.com/google/go-github/v57 v57.0.0/go.mod h1:s0omdnye0hvK/ecLvpsGfJMiRt85PimQh4oygmLIxHw= +github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= +github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= +github.com/google/go-replayers/grpcreplay v1.1.0/go.mod h1:qzAvJ8/wi57zq7gWqaE6AwLM6miiXUQwP1S+I9icmhk= +github.com/google/go-replayers/httpreplay v1.1.1/go.mod h1:gN9GeLIs7l6NUoVaSSnv2RiqK1NiwAmD0MrKeC9IIks= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian v2.1.1-0.20190517191504-25dcb96d9e51+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs= +github.com/google/martian/v3 v3.0.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.1.0/go.mod h1:y5Zk1BBys9G+gd6Jrk0W3cC1+ELVxBWuIGO+w/tUAp0= +github.com/google/martian/v3 v3.2.1/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/martian/v3 v3.3.2/go.mod h1:oBOf6HBosgwRXnUGWUB05QECsc6uvmMiJ3+6W4l/CUk= +github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc= +github.com/google/pprof v0.0.0-20191218002539-d4f498aebedc/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200212024743-f11f1df84d12/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200229191704-1ebb73c60ed3/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200430221834-fc25d7d30c6d/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200708004538-1a94d8640e99/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20200905233945-acf8798be1f7/go.mod h1:ZgVRPoUq/hfqzAqh7sHMqb3I9Rq5C59dIz2SbBwJ4eM= +github.com/google/pprof v0.0.0-20201023163331-3e6fc7fc9c4c/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20201203190320-1bf35d6f28c2/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210122040257-d980be63207e/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210226084205-cbba55b83ad5/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210506205249-923b5ab0fc1a/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= +github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4= +github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ= +github.com/google/subcommands v1.0.1/go.mod h1:ZjhPrFU+Olkh9WazFPsl27BQ4UPiG37m3yTrtFlrHVk= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/wire v0.5.0/go.mod h1:ngWDr9Qvq3yZA10YrxfyGELY/AFWGVpy9c1LTRi1EoU= +github.com/googleapis/enterprise-certificate-proxy v0.3.6 h1:GW/XbdyBFQ8Qe+YAmFU9uHLo7OnF5tL52HFAgMmyrf4= +github.com/googleapis/enterprise-certificate-proxy v0.3.6/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg= +github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk= +github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pfu6SK+H1/DsU0= +github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= +github.com/googleapis/gax-go/v2 v2.2.0/go.mod h1:as02EH8zWkzwUoLbBaFeQ+arQaj/OthfcblKl4IGNaM= +github.com/googleapis/gax-go/v2 v2.14.2 h1:eBLnkZ9635krYIPD+ag1USrOAI0Nr0QYF3+/3GqO0k0= +github.com/googleapis/gax-go/v2 v2.14.2/go.mod h1:ON64QhlJkhVtSqp4v1uaK92VyZ2gmvDQsweuyLV+8+w= +github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/hanwen/go-fuse v1.0.0/go.mod h1:unqXarDXqzAk0rt98O2tVndEPIpUgLD9+rwFisZH3Ok= +github.com/hanwen/go-fuse/v2 v2.1.0/go.mod h1:oRyA5eK+pvJyv5otpO/DgccS8y/RvYMaO00GgRLGryc= +github.com/hashicorp/go-uuid v0.0.0-20180228145832-27454136f036/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro= +github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8= +github.com/hashicorp/golang-lru v1.0.2 h1:dV3g9Z/unq5DpblPpw+Oqcv4dU/1omnb4Ok8iPY6p1c= +github.com/hashicorp/golang-lru v1.0.2/go.mod h1:iADmTwqILo4mZ8BN3D2Q6+9jd8WM5uGBxy+E8yxSoD4= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= +github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo= +github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/chunkreader/v2 v2.0.1/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk= +github.com/jackc/pgconn v0.0.0-20190420214824-7e0022ef6ba3/go.mod h1:jkELnwuX+w9qN5YIfX0fl88Ehu4XC3keFuOJJk9pcnA= +github.com/jackc/pgconn v0.0.0-20190824142844-760dd75542eb/go.mod h1:lLjNuW/+OfW9/pnVKPazfWOgNfH2aPem8YQ7ilXGvJE= +github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsUgOEh9hBm+xYTstcNHg7UPMVJqRfQxq4s= +github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o= +github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY= +github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI= +github.com/jackc/pgconn v1.11.0/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI= +github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8= +github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= +github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= +github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= +github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= +github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg= +github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= +github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM= +github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgproto3/v2 v2.2.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= +github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= +github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= +github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= +github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= +github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM= +github.com/jackc/pgtype v1.10.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4= +github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y= +github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM= +github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= +github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs= +github.com/jackc/pgx/v4 v4.15.0/go.mod h1:D/zyOyXiaM1TmVWnOM18p0xdDtdakRBa0RsVGI3U3bw= +github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jackc/puddle v1.2.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= +github.com/jcmturner/gofork v0.0.0-20180107083740-2aebee971930/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= +github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= +github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo= +github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U= +github.com/joho/godotenv v1.3.0/go.mod h1:7hK45KPybAkOC6peb+G5yklZfMxEjkZhHbwpqxOKXbg= +github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= +github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= +github.com/juju/gnuflag v1.0.0 h1:E6OmPEi2nqJYanlIw7a+bUF+FDiK3uSBHftRmQi3muQ= +github.com/juju/gnuflag v1.0.0/go.mod h1:2PavIy+JPciBPrBUjwbNvtwB6RQlve+hkpll6QSNmOE= +github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/jung-kurt/gofpdf v1.0.3-0.20190309125859-24315acbbda5/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes= +github.com/kch42/buzhash v0.0.0-20160816060738-9bdec3dec7c6 h1:l6Y3mFnF46A+CeZsTrT8kVIuhayq1266oxWpDKE7hnQ= +github.com/kch42/buzhash v0.0.0-20160816060738-9bdec3dec7c6/go.mod h1:UtDV9qK925GVmbdjR+e1unqoo+wGWNHHC6XB1Eu6wpE= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.9.7/go.mod h1:RyIbtBH6LamlWaDj8nUwkbUhJ87Yi3uG0guNDohfE1A= +github.com/klauspost/compress v1.10.3/go.mod h1:aoV0uJVorq1K+umq18yTdKaF57EivdYsUV+/s2qKfXs= +github.com/klauspost/compress v1.13.1/go.mod h1:8dP1Hq4DHOhN9w426knH3Rhby4rFm6D8eO+e+Dq5Gzg= +github.com/klauspost/compress v1.15.1/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= +github.com/klauspost/compress v1.18.5 h1:/h1gH5Ce+VWNLSWqPzOVn6XBO+vJbCNGvjoaGBFW2IE= +github.com/klauspost/compress v1.18.5/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.0.4/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.1.0/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= +github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/pty v1.1.8/go.mod h1:O1sed60cT9XZ5uDucP5qwvh+TE3NnUj51EiZO/lmSfw= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= +github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= +github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= +github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= +github.com/lestrrat-go/strftime v1.2.0 h1:8fAUYOeaJKCuLzNvUWBAo8t6I6hkFfodDTndEzJIun0= +github.com/lestrrat-go/strftime v1.2.0/go.mod h1:GtsIA/7ddIGJjEdfadUafEb1sbutvlvpMdPCMglykYo= +github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.1.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.2.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo= +github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= +github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ= +github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-ieproxy v0.0.1/go.mod h1:pYabZ6IHcRpFh7vIaLfK7rdcWgFEb3SFJ6/gNWuh88E= +github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s= +github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.22 h1:j8l17JJ9i6VGPUFUYoTUKPSgKe/83EYU2zBC7YNKMw4= +github.com/mattn/go-isatty v0.0.22/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4= +github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw= +github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs= +github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM= +github.com/minio/minio-go/v7 v7.0.34/go.mod h1:nCrRzjoSUQh8hgKKtu3Y708OLvRLtuASMg2/nvmbarw= +github.com/minio/sha256-simd v1.0.0/go.mod h1:OuYzVNI5vcoYIAmbIvHPl3N3jUzVedXbKy5RFepssQM= +github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= +github.com/mitchellh/mapstructure v1.3.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/modocache/gover v0.0.0-20171022184752-b58185e213c5/go.mod h1:caMODM3PzxT8aQXRPkAt8xlV/e7d7w8GM5g0fa5F0D8= +github.com/mohae/uvarint v0.0.0-20160208145430-c3f9e62bf2b0 h1:fXRYk7YXVIBMGAHT+GmAcbiXrudXMPtqdLfbkVfUhkI= +github.com/mohae/uvarint v0.0.0-20160208145430-c3f9e62bf2b0/go.mod h1:+6ZKJfAk1B0oKLOwdzYuRVJn3upG1c7uOm5Ih7Rrkvc= +github.com/montanaflynn/stats v0.6.6/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/montanaflynn/stats v0.7.0/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/ncw/swift v1.0.52/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/oracle/oci-go-sdk/v65 v65.55.0 h1:enKyHVLdJYDJrc9232w33u5F6t2p8Din4593kn3nh/w= +github.com/oracle/oci-go-sdk/v65 v65.55.0/go.mod h1:IBEV9l1qBzUpo7zgGaRUhbB05BVfcDGYRFBCPlTcPp0= +github.com/pborman/getopt v0.0.0-20180729010549-6fdd0a2c7117/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= +github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4= +github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= +github.com/phpdave11/gofpdf v1.4.2/go.mod h1:zpO6xFn9yxo3YLyMvW8HcKWVdbNqgIfOOp2dXMnm1mY= +github.com/phpdave11/gofpdi v1.0.12/go.mod h1:vBmVV0Do6hSBHC8uKUQ71JGW+ZGQq74llk/7bXwjDoI= +github.com/pierrec/lz4/v4 v4.1.8/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= +github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pkg/browser v0.0.0-20180916011732-0a3d74bf9ce4/go.mod h1:4OwLy04Bl9Ef3GJJCoec+30X3LQs/0/m4HFRt/2LUSA= +github.com/pkg/browser v0.0.0-20210115035449-ce105d075bb4/go.mod h1:N6UoU20jOqggOuDwUaBQpluzLNDqif3kq9z2wpdYEfQ= +github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ= +github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/profile v1.5.0 h1:042Buzk+NhDI+DeSAA62RwJL8VAuZUMQZUjCsRz1Mug= +github.com/pkg/profile v1.5.0/go.mod h1:qBsxPvzyUincmltOk6iyRVxHYg4adc0OFOv72ZdLa18= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= +github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= +github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rs/xid v1.2.1/go.mod h1:+uKXf+4Djp6Md1KODXJxgGQPKngRmWyn10oCKFzNHOQ= +github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= +github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThCjNc= +github.com/ruudk/golang-pdf417 v0.0.0-20181029194003-1af4ab5afa58/go.mod h1:6lfFZQK844Gfx8o5WFuvpxWRwnSoipWe/p622j1v06w= +github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc= +github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= +github.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4= +github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4= +github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sirupsen/logrus v1.9.0/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= +github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA= +github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog= +github.com/sony/gobreaker v0.5.0 h1:dRCvqm0P490vZPmy7ppEk2qCnCieBooFJ+YoXGYB+yg= +github.com/sony/gobreaker v0.5.0/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw= +github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U= +github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA= +github.com/spf13/afero v1.2.2/go.mod h1:9ZxEEn6pIJ8Rxe320qSDBk6AsU0r9pR7Q4OcevTdifk= +github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= +github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg= +github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY= +github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo= +github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= +github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= +github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= +github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= +github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.2.0/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/tealeg/xlsx v1.0.5 h1:+f8oFmvY8Gw1iUXzPk+kz+4GpbDZPK1FhPiQRd+ypgE= +github.com/tealeg/xlsx v1.0.5/go.mod h1:btRS8dz54TDnvKNosuAqxrM1QgN1udgk9O34bDCnORM= +github.com/tidwall/gjson v1.14.2/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= +github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= +github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= +github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= +github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= +github.com/vbauerster/mpb/v8 v8.7.2 h1:SMJtxhNho1MV3OuFgS1DAzhANN1Ejc5Ct+0iSaIkB14= +github.com/vbauerster/mpb/v8 v8.7.2/go.mod h1:ZFnrjzspgDHoxYLGvxIruiNk73GNTPG4YHgVNpR10VY= +github.com/xitongsys/parquet-go v1.5.1/go.mod h1:xUxwM8ELydxh4edHGegYq1pA8NnMKDx0K/GyB0o2bww= +github.com/xitongsys/parquet-go v1.6.2 h1:MhCaXii4eqceKPu9BwrjLqyK10oX9WF+xGhwvwbw7xM= +github.com/xitongsys/parquet-go v1.6.2/go.mod h1:IulAQyalCm0rPiZVNnCgm/PCL64X2tdSVGMQ/UeKqWA= +github.com/xitongsys/parquet-go-source v0.0.0-20190524061010-2b72cbee77d5/go.mod h1:xxCx7Wpym/3QCo6JhujJX51dzSXrwmb0oH6FQb39SEA= +github.com/xitongsys/parquet-go-source v0.0.0-20200817004010-026bad9b25d0/go.mod h1:HYhIKsdns7xz80OgkbgJYrtQY7FjHWHKH6cvN7+czGE= +github.com/xitongsys/parquet-go-source v0.0.0-20240122235623-d6294584ab18 h1:Loknf8YcZNXiweAsfz8GD79m4WE0MSbf1Bl4YCAfFYQ= +github.com/xitongsys/parquet-go-source v0.0.0-20240122235623-d6294584ab18/go.mod h1:2ActxmJ4q17Cdruar9nKEkzKSOL1Ol03737Bkz10rTY= +github.com/xtaci/smux v1.5.56 h1:Eyv/dUULmkGZZNucLUisnkzJ/4UQ5YZTschhugFBM0U= +github.com/xtaci/smux v1.5.56/go.mod h1:IGQ9QYrBphmb/4aTnLEcJby0TNr3NV+OslIOMrX825Q= +github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= +github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= +github.com/zenazn/goji v0.9.0/go.mod h1:7S9M489iMyHBNxwZnk9/EHS098H4/F6TATF2mIxtB1Q= +go.opencensus.io v0.15.0/go.mod h1:UffZAU+4sDEINUGP/B7UfBBkq4fqLu9zXAX7ke6CHW0= +go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU= +go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8= +go.opencensus.io v0.22.2/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw= +go.opencensus.io v0.22.5/go.mod h1:5pWMHQbX5EPX2/62yrJeAkowc+lfs/XD7Uxpq3pI6kk= +go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= +go.opentelemetry.io/contrib/detectors/gcp v1.42.0 h1:kpt2PEJuOuqYkPcktfJqWWDjTEd/FNgrxcniL7kQrXQ= +go.opentelemetry.io/contrib/detectors/gcp v1.42.0/go.mod h1:W9zQ439utxymRrXsUOzZbFX4JhLxXU4+ZnCt8GG7yA8= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0 h1:q4XOmH/0opmeuJtPsbFNivyl7bCt7yRBbeEm2sC/XtQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.61.0/go.mod h1:snMWehoOh2wsEwnvvwtDyFCxVeDAODenXHtn5vzrKjo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0 h1:F7Jx+6hwnZ41NSFTO5q4LYDtJRXBf2PD0rNBkeB/lus= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.61.0/go.mod h1:UHB22Z8QsdRDrnAtX4PntOl36ajSxcdUMt1sF7Y6E7Q= +go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= +go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= +go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= +go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= +go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= +go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= +go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= +go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= +go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/atomic v1.3.2/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE= +go.uber.org/atomic v1.5.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.6.0/go.mod h1:sABNBOSYdrvTF6hTgEIbc7YasKWGhgEQZyfxyTvoXHQ= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.11/go.mod h1:cwTWslyiVhfpKIDGSZEM2HlOvcqm+tG4zioyIeLoqMQ= +go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0= +go.uber.org/multierr v1.3.0/go.mod h1:VgVr7evmIr6uPjLBxg28wmKNXyqE9akIJ5XnfpiKl+4= +go.uber.org/multierr v1.5.0/go.mod h1:FeouvMocqHpRaaGuG9EjoKcStLC43Zu/fmqdUMPcKYU= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.8.0/go.mod h1:7EAYxJLBy9rStEaz58O2t4Uvip6FSURkq8/ppBp95ak= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/tools v0.0.0-20190618225709-2cfd321de3ee/go.mod h1:vJERXedbb3MVM5f9Ejo0C68/HhF8uaILCdgjnY+goOA= +go.uber.org/zap v1.9.1/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q= +go.uber.org/zap v1.13.0/go.mod h1:zwrFLgMcdUuIBviXEYEH1YKNaOBnKXsx2IPda5bBwHM= +go.uber.org/zap v1.21.0/go.mod h1:wjWOCqI0f2ZZrJF/UufIOkiC8ii6tm1iqIsLo76RfJw= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= +go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= +gocloud.dev v0.26.0/go.mod h1:mkUgejbnbLotorqDyvedJO20XcZNTynmSeVSQS9btVg= +golang.org/x/crypto v0.0.0-20180723164146-c126467f60eb/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201002170205-7f63de1d35b0/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201016220609-9e8e0b390897/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I= +golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20211115234514-b4de73f9ece8/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220511200225-c6db032c6c88/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220722155217-630584e8d5aa/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.7.0/go.mod h1:pYwdfH91IfpZVANVyUOhSIPZaFoJGxTFbZhFTx+dXZU= +golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= +golang.org/x/exp v0.0.0-20180321215751-8460e604b9de/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20180807140117-3d87b88a115f/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190125153040-c74c464bbbf2/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8= +golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek= +golang.org/x/exp v0.0.0-20191002040644-a1355ae1e2c3/go.mod h1:NOZ3BPKG0ec/BKJQgnvsSFpcKLM5xXVWnvZS97DWHgE= +golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY= +golang.org/x/exp v0.0.0-20191129062945-2f5052295587/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20191227195350-da58074b4299/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200119233911-0405dc783f0a/go.mod h1:2RIsYlXP63K8oxa1u096TMicItID8zy7Y6sNkU49FU4= +golang.org/x/exp v0.0.0-20200207192155-f17229e696bd/go.mod h1:J/WKrq2StrnmMY6+EHIKF9dgMWnmCNThgcyBT1FY9mM= +golang.org/x/exp v0.0.0-20200224162631-6cc2880d07d6/go.mod h1:3jZMyOhIsHpP37uCMkUooju7aAi5cS1Q23tOzKc+0MU= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o= golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8= +golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs= +golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js= +golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20190910094157-69e4b8554b2a/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200119044424-58c23975cae1/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200430140353-33d19683fad8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20200618115811-c13761719519/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20201208152932-35266b937fa6/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/image v0.0.0-20210216034530-4410531fe030/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/lint v0.0.0-20191125180803-fdd1cda4f05f/go.mod h1:5qLYkcX4OjUUV8bRuDixDT3tpyyb+LUpUlRWLxfhWrs= +golang.org/x/lint v0.0.0-20200130185559-910be7a94367/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20200302205851-738671d3881b/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/lint v0.0.0-20210508222113-6edffad5e616/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY= +golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE= +golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY= +golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.1.1-0.20191107180719-034126e5016b/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.5.0/go.mod h1:5OXOZSfqPIIbmVBIIKWRFfZjPR0E5r58TLhUjH0a2Ro= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/mod v0.29.0 h1:HV8lRxZC4l2cr3Zq1LvtOsi/ThTgWnUk/y64QSs8GwA= golang.org/x/mod v0.29.0/go.mod h1:NyhrlYXJ2H4eJiRy/WDBO6HMqZQ6q9nk4JzS3NuCK+w= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190628185345-da137c7871d7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190724013045-ca1201d0de80/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20190813141303-74dc4d7220e7/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191112182307-2180aed22343/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200114155413-6afb5195e5aa/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200202094626-16171245cfb2/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200222125558-5a598a2470a0/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200301022130-244492dfa37a/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200324143707-d3edc9973b7e/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200501053045-e0ff5e5a1de5/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200506145744-7e3656a0809f/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200520182314-0ba52f642ac2/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A= +golang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200707034311-ab3426394381/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20200904194848-62affa334b73/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201010224723-4f7140c49acb/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201031054903-ff519b6c9102/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20201209123823-ac852fbbde11/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210119194325-5f4716e94777/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210610132358-84b48f89b13b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20210614182718-04defd469f4e/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211020060615-d418f374d309/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220127200216-cd36cc0744dd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220325170049-de3da57026de/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220401154927-543a649e0bdd/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220425223048-2871e0cb64e4/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.8.0/go.mod h1:QVkue5JL9kW//ek3r6jTKnTFis1tRmNAW2P1shuFdJc= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8= +golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20191202225959-858c2ad4c8b6/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/oauth2 v0.0.0-20200902213428-5d25da1a8d43/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201109201403-9fd604954f58/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20201208152858-08078c50e5b5/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210218202405-ba52d332ba99/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210220000619-9bb904979d93/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210313182246-cd4f82c27b84/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210427180440-81ed05c6b58c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210514164344-f6687ab2804c/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210628180205-a41e5a781914/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210805134026-6f1e6394065a/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20211005180243-6b3c2da341f1/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20211104180415-d3ed0bb246c8/go.mod h1:KelEdhl1UZF7XfJ4dDtk6s++YSgaE7mD/BuKKDLBl4A= +golang.org/x/oauth2 v0.0.0-20220223155221-ee480838109b/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.0.0-20220309155454-6242fa91716a/go.mod h1:DAh4E804XQdzx2j+YRIaUnCqCV2RuMz24cGBJ5QYIrc= +golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= +golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200317015054-43a5402ce75a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201207232520-09787c993a3a/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8= golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4= +golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191112214154-59a1497f0cea/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200113162924-86b910548bc1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200122134326-e047566fdf82/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200202164722-d101bd2416d5/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200212091648-12a6c2dcc1e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200223170610-d5e6a3e2c0ae/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200302150141-5c8b2ff67527/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200331124033-c3d80250170d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200501052902-10377860bb8e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200828194041-157a740278f4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210304124612-50617c2ba197/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210305230114-8fe3ee5dd75b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210503080704-8803ae5d1324/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210603125802-9665404d3644/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211007075335-d3039528d8ac/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220114195835-da31bd327af9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220128215802-99c3d69c2c27/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220204135822-1c1b9b1eba6a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220328115105-d36c6a25d886/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY= +golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw= +golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4= +golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk= +golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.8.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc= +golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38= +golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.0.0-20220224211638-0e9765cccd65/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= +golang.org/x/time v0.12.0 h1:ScB/8o8olJvc+CQPWrK3fPZNfh7qgwCrY0zJmoEQLSE= +golang.org/x/time v0.12.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +golang.org/x/tools v0.0.0-20180525024113-a5b4c53f6e8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190206041539-40960b6deb8e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190422233926-fe54fb35175b/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190425163242-31fd60d6bfdc/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190823170909-c4a336ef6a2f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20190927191325-030b2cf1153e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029041327-9cc4af7d6b2c/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191029190741-b9c20aec41a5/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191113191852-77e3bb0ad9e7/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191115202509-3a792d9c32b2/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191125144606-a911d9008d1f/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20191216173652-a0e659d51361/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20191227053925-7b8e75db28f4/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200103221440-774c71fcf114/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200117161641-43d50277825c/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200122220014-bf1340f18c4a/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200204074204-1cc6d1ef6c74/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200207183749-b753a1ba74fa/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200212150539-ea181f53ac56/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200224181240-023911ca70b2/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200227222343-706bc42d1f0d/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28= +golang.org/x/tools v0.0.0-20200304193943-95d2e580d8eb/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200312045724-11d5b4c81c7d/go.mod h1:o4KQGtdN14AW+yjsvvwRTJJuXz8XRtIHtEnmAXLyFUw= +golang.org/x/tools v0.0.0-20200331025713-a30bf2db82d4/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8= +golang.org/x/tools v0.0.0-20200501065659-ab2804fb9c9d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200512131952-2bc93b1c0c88/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200515010526-7d3b6ebf133d/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200618134242-20370b0cb4b2/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20200729194436-6467de6f59a7/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200804011535-6c149bb5ef0d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200825202427-b303f430e36d/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200828161849-5deb26317202/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA= +golang.org/x/tools v0.0.0-20200904185747-39188db58858/go.mod h1:Cj7w3i3Rnn0Xh82ur9kSqwfTHTeVxaDqrfMjpcNT6bE= +golang.org/x/tools v0.0.0-20200915173823-2db8f0ff891c/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20200918232735-d647fc253266/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU= +golang.org/x/tools v0.0.0-20201110124207-079ba7bd75cd/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201201161351-ac6f37ff4c2a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20201208233053-a543418bbed2/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210105154028-b0ab187a4818/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.2/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.3/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.4/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= golang.org/x/tools v0.37.0 h1:DVSRzp7FwePZW356yEAChSdNcQo6Nsp+fex1SUW09lE= golang.org/x/tools v0.37.0/go.mod h1:MBN5QPQtLMHVdvsbtarmTNukZDdgwdwlO5qGacAzF0w= +golang.org/x/tools v0.45.0 h1:18qN3FAooORvApf5XjCXgsuayZOEtXf6JK18I3+ONa8= +golang.org/x/tools v0.45.0/go.mod h1:LuUGqqaXcXMEFEruIVJVm5mgDD8vww/z/SR1gQ4uE/0= +golang.org/x/xerrors v0.0.0-20190410155217-1f06c39b4373/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20190513163551-3ee3066db522/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU= +golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= +gonum.org/v1/gonum v0.0.0-20180816165407-929014505bf4/go.mod h1:Y+Yx5eoAFn32cQvJDxZx5Dpnq+c3wtXuadVZAcxbbBo= +gonum.org/v1/gonum v0.8.2/go.mod h1:oe/vMfY3deqTw+1EZJhuvEW2iwGF1bW9wwu7XCu0+v0= +gonum.org/v1/gonum v0.9.3/go.mod h1:TZumC3NeyVQskjXqmyWt4S3bINhy7B4eYwW69EbyX+0= +gonum.org/v1/netlib v0.0.0-20190313105609-8cb42192e0e0/go.mod h1:wa6Ws7BG/ESfp6dHfk7C6KdzKA7wR7u/rKwOGE66zvw= +gonum.org/v1/plot v0.0.0-20190515093506-e2840ee46a6b/go.mod h1:Wt8AAjI+ypCyYX3nZBvf6cAIx93T+c/OS2HFAYskSZc= +gonum.org/v1/plot v0.9.0/go.mod h1:3Pcqqmp6RHvJI72kgb8fThyUnav364FOsdDo2aGW5lY= +google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE= +google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M= +google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg= +google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.14.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.15.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI= +google.golang.org/api v0.17.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.18.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.19.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.20.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.22.0/go.mod h1:BwFmGc8tA3vsd7r/7kR8DY7iEEGSU04BFxCo5jP/sfE= +google.golang.org/api v0.24.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.28.0/go.mod h1:lIXQywCXRcnZPGlsd8NbLnOjtAoL6em04bJ9+z0MncE= +google.golang.org/api v0.29.0/go.mod h1:Lcubydp8VUV7KeIHD9z2Bys/sm/vGKnG1UHuDBSrHWM= +google.golang.org/api v0.30.0/go.mod h1:QGmEvQ87FHZNiUVJkT14jQNYJ4ZJjdRF23ZXz5138Fc= +google.golang.org/api v0.31.0/go.mod h1:CL+9IBCa2WWU6gRuBWaKqGWLFFwbEUXkfeMkHLQWYWo= +google.golang.org/api v0.32.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.35.0/go.mod h1:/XrVsuzM0rZmrsbjJutiuftIzeuTQcEeaYcSk/mQ1dg= +google.golang.org/api v0.36.0/go.mod h1:+z5ficQTmoYpPn8LCUNVpK5I7hwkpjbcgqA7I34qYtE= +google.golang.org/api v0.40.0/go.mod h1:fYKFpnQN0DsDSKRVRcQSDQNtqWPfM9i+zNPxepjRCQ8= +google.golang.org/api v0.41.0/go.mod h1:RkxM5lITDfTzmyKFPt+wGrCJbVfniCr2ool8kTBzRTU= +google.golang.org/api v0.43.0/go.mod h1:nQsDGjRXMo4lvh5hP0TKqF244gqhGcr/YSIykhUk/94= +google.golang.org/api v0.46.0/go.mod h1:ceL4oozhkAiTID8XMmJBsIxID/9wMXJVVFXPg4ylg3I= +google.golang.org/api v0.47.0/go.mod h1:Wbvgpq1HddcWVtzsVLyfLp8lDg6AA241LmgIL59tHXo= +google.golang.org/api v0.48.0/go.mod h1:71Pr1vy+TAZRPkPs/xlCf5SsU8WjuAWv1Pfjbtukyy4= +google.golang.org/api v0.50.0/go.mod h1:4bNT5pAuq5ji4SRZm+5QIkjny9JAyVD/3gaSihNefaw= +google.golang.org/api v0.51.0/go.mod h1:t4HdrdoNgyN5cbEfm7Lum0lcLDLiise1F8qDKX00sOU= +google.golang.org/api v0.54.0/go.mod h1:7C4bFFOvVDGXjfDTAsgGwDgAxRDeQ4X8NvUedIt6z3k= +google.golang.org/api v0.55.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.56.0/go.mod h1:38yMfeP1kfjsl8isn0tliTjIb1rJXcQi4UXlbqivdVE= +google.golang.org/api v0.57.0/go.mod h1:dVPlbZyBo2/OjBpmvNdpn2GRm6rPy75jyU7bmhdrMgI= +google.golang.org/api v0.58.0/go.mod h1:cAbP2FsxoGVNwtgNAmmn3y5G1TWAiVYRmg4yku3lv+E= +google.golang.org/api v0.59.0/go.mod h1:sT2boj7M9YJxZzgeZqXogmhfmRWDtPzT31xkieUbuZU= +google.golang.org/api v0.61.0/go.mod h1:xQRti5UdCmoCEqFxcz93fTl338AVqDgyaDRuOZ3hg9I= +google.golang.org/api v0.63.0/go.mod h1:gs4ij2ffTRXwuzzgJl/56BdwJaA194ijkfn++9tDuPo= +google.golang.org/api v0.64.0/go.mod h1:931CdxA8Rm4t6zqTFGSsgwbAEZ2+GMYurbndwSimebM= +google.golang.org/api v0.66.0/go.mod h1:I1dmXYpX7HGwz/ejRxwQp2qj5bFAz93HiCU1C1oYd9M= +google.golang.org/api v0.67.0/go.mod h1:ShHKP8E60yPsKNw/w8w+VYaj9H6buA5UqDp8dhbQZ6g= +google.golang.org/api v0.68.0/go.mod h1:sOM8pTpwgflXRhz+oC8H2Dr+UcbMqkPPWNJo88Q7TH8= +google.golang.org/api v0.69.0/go.mod h1:boanBiw+h5c3s+tBPgEzLDRHfFLWV0qXxRHz3ws7C80= +google.golang.org/api v0.70.0/go.mod h1:Bs4ZM2HGifEvXwd50TtW70ovgJffJYw2oRCOFU/SkfA= +google.golang.org/api v0.71.0/go.mod h1:4PyU6e6JogV1f9eA4voyrTY2batOLdgZ5qZ5HOCc4j8= +google.golang.org/api v0.74.0/go.mod h1:ZpfMZOVRMywNyvJFeqL9HRWBgAuRfSjJFpe9QtRRyDs= +google.golang.org/api v0.241.0 h1:QKwqWQlkc6O895LchPEDUSYr22Xp3NCxpQRiWTB6avE= +google.golang.org/api v0.241.0/go.mod h1:cOVEm2TpdAGHL2z+UwyS+kmlGr3bVWQQ6sYEqkKje50= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0= +google.golang.org/appengine v1.6.5/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.6/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE= +google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= +google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191115194625-c23dd37a84c9/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191216164720-4f79533eabd1/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200115191322-ca5a22157cba/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200122232147-0452cf42e150/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= +google.golang.org/genproto v0.0.0-20200204135345-fa8e72b47b90/go.mod h1:GmwEX6Z4W5gMy59cAlVYjN9JhxgbQH6Gn+gFDQe2lzA= +google.golang.org/genproto v0.0.0-20200212174721-66ed5ce911ce/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200224152610-e50cd9704f63/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200228133532-8c2c7df3a383/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200305110556-506484158171/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200312145019-da6875a35672/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200331122359-1ee6d9798940/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200430143042-b979b6f78d84/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200511104702-f5ebc3bea380/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200515170657-fc4c6c6a6587/go.mod h1:YsZOwe1myG/8QRHRsmBRE1LrgQY60beZKjly0O1fX9U= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20200618031413-b414f8b61790/go.mod h1:jDfRM7FcilCzHH/e9qn6dsT145K34l5v+OpcnNgKAAA= +google.golang.org/genproto v0.0.0-20200729003335-053ba62fc06f/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200831141814-d751682dd103/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200904004341-0bd0a958aa1d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200914193844-75d14daec038/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20200921151605-7abf4a1a14d5/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201109203340-2640f1f9cdfb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201201144952-b05cb90ed32e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201210142538-e3217bee35cc/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20201214200347-8c77b98c765d/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210222152913-aa3ee6e6a81c/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210303154014-9728d6b83eeb/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210310155132-4ce2db91004e/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210319143718-93e7006c17a6/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no= +google.golang.org/genproto v0.0.0-20210402141018-6c239bbf2bb1/go.mod h1:9lPAdzaEmUacj36I+k7YKbEc5CXzPIeORRgDAUOu28A= +google.golang.org/genproto v0.0.0-20210429181445-86c259c2b4ab/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210513213006-bf773b8c8384/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210517163617-5e0236093d7a/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A= +google.golang.org/genproto v0.0.0-20210602131652-f16073e35f0c/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210604141403-392c879c8b08/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210608205507-b6d2f5bf0d7d/go.mod h1:UODoCrxHCcBojKKwX1terBiRUaqAsFqJiF615XL43r0= +google.golang.org/genproto v0.0.0-20210624195500-8bfb893ecb84/go.mod h1:SzzZ/N+nwJDaO1kznhnlzqS8ocJICar6hYhVyhi++24= +google.golang.org/genproto v0.0.0-20210630183607-d20f26d13c79/go.mod h1:yiaVoXHpRzHGyxV3o4DktVWY4mSUErTKaeEOq6C3t3U= +google.golang.org/genproto v0.0.0-20210713002101-d411969a0d9a/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210716133855-ce7ef5c701ea/go.mod h1:AxrInvYm1dci+enl5hChSFPOmmUF1+uAa/UsgNRWd7k= +google.golang.org/genproto v0.0.0-20210728212813-7823e685a01f/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210805201207-89edb61ffb67/go.mod h1:ob2IJxKrgPT52GcgX759i1sleT07tiKowYBGbczaW48= +google.golang.org/genproto v0.0.0-20210813162853-db860fec028c/go.mod h1:cFeNkxwySK631ADgubI+/XFU/xp8FD5KIVV4rj8UC5w= +google.golang.org/genproto v0.0.0-20210821163610-241b8fcbd6c8/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210828152312-66f60bf46e71/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210831024726-fe130286e0e2/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210903162649-d08c68adba83/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210909211513-a8c4777a87af/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210917145530-b395a37504d4/go.mod h1:eFjDcFEctNawg4eG61bRv87N7iHBWyVhJu7u1kqDUXY= +google.golang.org/genproto v0.0.0-20210921142501-181ce0d877f6/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20210924002016-3dee208752a0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211008145708-270636b82663/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211018162055-cf77aa76bad2/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211028162531-8db9c33dc351/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211118181313-81c1377c94b1/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211206160659-862468c7d6e0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211221195035-429b39de9b1c/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20211223182754-3ac035c7e7cb/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220111164026-67b88f271998/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220114231437-d2e6a121cae0/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220126215142-9970aeb2e350/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220201184016-50beb8ab5c44/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220204002441-d6cc3cc0770e/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220207164111-0872dc986b00/go.mod h1:5CzLGKJ67TSI2B9POpiiyGha0AjJvZIUgRMt1dSmuhc= +google.golang.org/genproto v0.0.0-20220211171837-173942840c17/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220216160803-4663080d8bc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220218161850-94dd64e39d7c/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220222213610-43724f9ea8cf/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220304144024-325a89244dc8/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220310185008-1973136f34c6/go.mod h1:kGP+zUP2Ddo0ayMi4YuN7C3WZyJvGLZRh8Z5wnAqvEI= +google.golang.org/genproto v0.0.0-20220324131243-acbaeb5b85eb/go.mod h1:hAL49I2IFola2sVEjAn7MEwsja0xp51I0tlGAf9hz4E= +google.golang.org/genproto v0.0.0-20220401170504-314d38edb7de/go.mod h1:8w6bsBMX6yCPbAVTeqQHvzxW0EIFigd5lZyahWgyfDo= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2 h1:1tXaIXCracvtsRxSBsYDiSBN0cuJvM7QYW+MrpIRY78= +google.golang.org/genproto v0.0.0-20250505200425-f936aa4a68b2/go.mod h1:49MsLSx0oWMOZqcpB3uL8ZOkAh1+TndpJ8ONoCBWiZk= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa h1:Kjn0N0tCrDgiAFW+lGO4JZ3ck44CehvJQMAwj9QF0G8= +google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:q4lMZS6kskjT5HvCPrnnypcDPVJqT/f4nfxmkE7gryY= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa h1:mZHHdPZl0dbGHCflZgAq/Q468DWVFcU2whhB2KAo8fk= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38= +google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.26.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.27.1/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKal+60= +google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.31.1/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.32.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.34.0/go.mod h1:WotjhfgOW/POjDeRt8vscBtXq+2VjORFy659qA51WJ8= +google.golang.org/grpc v1.35.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.37.1/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.38.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM= +google.golang.org/grpc v1.39.0/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.39.1/go.mod h1:PImNr+rS9TWYb2O4/emRugxiyHZ5JyHW5F+RPnDzfrE= +google.golang.org/grpc v1.40.0/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.40.1/go.mod h1:ogyxbiOoUXAkP+4+xa6PZSE9DZgIHtSpzjDTB9KAK34= +google.golang.org/grpc v1.44.0/go.mod h1:k+4IHHFw41K8+bbowsex27ge2rCb65oeWqe4jJ590SU= +google.golang.org/grpc v1.45.0/go.mod h1:lN7owxKUQEqMfSyQikvvk5tf/6zMPsrK+ONuO11+0rQ= +google.golang.org/grpc v1.81.1 h1:VnnIIZ88UzOOKLukQi+ImGz8O1Wdp8nAGGnvOfEIWQQ= +google.golang.org/grpc v1.81.1/go.mod h1:xGH9GfzOyMTGIOXBJmXt+BX/V0kcdQbdcuwQ/zNw42I= +google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.1.0/go.mod h1:6Kw0yEErY5E/yWrBtf03jp27GLLJujG4z/JK95pnjjw= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE= +google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/go-jose/go-jose.v2 v2.6.3 h1:nt80fvSDlhKWQgSWyHyy5CfmlQr+asih51R8PTWNKKs= +gopkg.in/go-jose/go-jose.v2 v2.6.3/go.mod h1:zzZDPkNNw/c9IE7Z9jr11mBZQhKQTMzoEEIoEdZlFBI= +gopkg.in/inconshreveable/log15.v2 v2.0.0-20180818164646-67afb5ed74ec/go.mod h1:aPpfJ7XW+gOuirDoZ8gHhLh3kZ1B08FtV2bbmy7Jv3s= +gopkg.in/ini.v1 v1.66.6/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/jcmturner/aescts.v1 v1.0.1/go.mod h1:nsR8qBOg+OucoIW+WMhB3GspUQXq9XorLnQb9XtvcOo= +gopkg.in/jcmturner/dnsutils.v1 v1.0.1/go.mod h1:m3v+5svpVOhtFAP/wSz+yzh4Mc0Fg7eRhxkJMWSIz9Q= +gopkg.in/jcmturner/goidentity.v3 v3.0.0/go.mod h1:oG2kH0IvSYNIu80dVAyu/yoefjq1mNfM5bm88whjWx4= +gopkg.in/jcmturner/gokrb5.v7 v7.3.0/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM= +gopkg.in/jcmturner/rpc.v1 v1.1.0/go.mod h1:YIdkC4XfD6GXbzje11McwsDuOlZQSb9W4vfLvuNnlv8= +gopkg.in/src-d/go-errors.v1 v1.0.0 h1:cooGdZnCjYbeS1zb1s6pVAAimTdKceRrpn7aKOnNIfc= +gopkg.in/src-d/go-errors.v1 v1.0.0/go.mod h1:q1cBlomlw2FnDBDNGlnh6X0jPihy+QxZfMMNxPCbdYg= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= +honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= modernc.org/cc/v4 v4.26.2 h1:991HMkLjJzYBIfha6ECZdjrIYz2/1ayr+FL8GN+CNzM= modernc.org/cc/v4 v4.26.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0= modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU= @@ -48,3 +1446,8 @@ modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= +rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= +rsc.io/quote/v3 v3.1.0/go.mod h1:yEA65RcK8LyAZtP9Kv3t0HmxON59tX3rD+tICJqUlj0= +rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA= diff --git a/examples/library-usage/main.go b/examples/library-usage/main.go index 3596776d7..0517f2e41 100644 --- a/examples/library-usage/main.go +++ b/examples/library-usage/main.go @@ -16,16 +16,16 @@ import ( func main() { ctx := context.Background() - // Find the Beads database (looks for .beads/*.db in current/parent dirs) - dbPath := beads.FindDatabasePath() - if dbPath == "" { - log.Fatal("No Beads database found. Run 'bd init' first.") + // Find the Beads workspace so backend selection can follow metadata.json. + beadsDir := beads.FindBeadsDir() + if beadsDir == "" { + log.Fatal("No Beads workspace found. Run 'bd init' first.") } - fmt.Printf("Using database: %s\n\n", dbPath) + fmt.Printf("Using workspace: %s\n\n", beadsDir) - // Open the database - store, err := beads.Open(ctx, dbPath) + // Open the configured Dolt implementation (embedded or server mode). + store, err := beads.OpenBestAvailable(ctx, beadsDir) if err != nil { log.Fatalf("Failed to open storage: %v", err) } diff --git a/examples/library-usage/main_test.go b/examples/library-usage/main_test.go index 92953c6ff..985d52c1c 100644 --- a/examples/library-usage/main_test.go +++ b/examples/library-usage/main_test.go @@ -18,16 +18,28 @@ func TestExampleCompiles(t *testing.T) { } defer os.RemoveAll(tmpDir) - dbPath := filepath.Join(tmpDir, "dolt") + beadsDir := filepath.Join(tmpDir, ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatalf("Failed to create .beads dir: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(`{"backend":"dolt"}`), 0o600); err != nil { + t.Fatalf("Failed to create metadata.json: %v", err) + } // Open storage ctx := context.Background() - store, err := beads.Open(ctx, dbPath) + store, err := beads.OpenBestAvailable(ctx, beadsDir) if err != nil { t.Fatalf("Failed to open storage: %v", err) } defer store.Close() + // A fresh workspace needs an issue prefix before issues can be created + // (bd init normally seeds this). + if err := store.SetConfig(ctx, "issue_prefix", "ex"); err != nil { + t.Fatalf("Failed to seed issue prefix: %v", err) + } + // Create an issue (from example code) newIssue := &beads.Issue{ ID: "", diff --git a/flake.nix b/flake.nix index 6d93dc07a..7ccc5bfda 100644 --- a/flake.nix +++ b/flake.nix @@ -59,7 +59,7 @@ gopls gotools golangci-lint - sqlite + sqlite # sqlite3 CLI for the legacy pre-Dolt migration scripts (scripts/migrate-sqlite-to-current.sh, scripts/migration-test/) ]; shellHook = '' echo "beads development shell" diff --git a/go.mod b/go.mod index abfdb204a..fbf3c061b 100644 --- a/go.mod +++ b/go.mod @@ -14,7 +14,6 @@ require ( github.com/dolthub/driver/v2 v2.2.0 github.com/dolthub/eventkit v0.0.0-20260611184414-99f5693e696a github.com/go-sql-driver/mysql v1.10.0 - github.com/jackc/pgx/v5 v5.10.0 github.com/olebedev/when v1.1.0 github.com/spf13/cobra v1.10.2 github.com/spf13/viper v1.21.0 @@ -33,7 +32,6 @@ require ( golang.org/x/sys v0.45.0 golang.org/x/term v0.43.0 gopkg.in/yaml.v3 v3.0.1 - modernc.org/sqlite v1.53.0 rsc.io/script v0.0.2 ) @@ -45,20 +43,12 @@ require ( github.com/cockroachdb/apd/v3 v3.2.3 // indirect github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/invopop/jsonschema v0.13.0 // indirect - github.com/jackc/pgpassfile v1.0.0 // indirect - github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect - github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/mailru/easyjson v0.7.7 // indirect github.com/moby/moby/api v1.54.1 // indirect github.com/moby/moby/client v0.4.0 // indirect - github.com/ncruces/go-strftime v1.0.0 // indirect github.com/prometheus/procfs v0.16.1 // indirect - github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect github.com/standard-webhooks/standard-webhooks/libraries v0.0.1 // indirect github.com/wk8/go-ordered-map/v2 v2.1.8 // indirect - modernc.org/libc v1.73.4 // indirect - modernc.org/mathutil v1.7.1 // indirect - modernc.org/memory v1.11.0 // indirect ) require ( @@ -228,7 +218,7 @@ require ( github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect - github.com/spf13/pflag v1.0.10 + github.com/spf13/pflag v1.0.10 // indirect github.com/spiffe/go-spiffe/v2 v2.6.0 // indirect github.com/subosito/gotenv v1.6.0 github.com/tealeg/xlsx v1.0.5 // indirect diff --git a/go.sum b/go.sum index 29901bb04..d85d5cc71 100644 --- a/go.sum +++ b/go.sum @@ -661,8 +661,6 @@ github.com/google/pprof v0.0.0-20210506205249-923b5ab0fc1a/go.mod h1:kpwsk12EmLe github.com/google/pprof v0.0.0-20210601050228-01bbb1931b22/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210609004039-a478d1d731e9/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE= -github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs= -github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA= github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= @@ -724,7 +722,6 @@ github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bY github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE= github.com/jackc/pgmock v0.0.0-20201204152224-4fe30f7445fd/go.mod h1:hrBW0Enj2AZTNpt/7Y5rr2xe/9Mn757Wtb2xeBzPv2c= github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak= -github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78= github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA= @@ -735,8 +732,6 @@ github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwX github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= github.com/jackc/pgproto3/v2 v2.2.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA= github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b/go.mod h1:vsD4gTJCa9TptPL8sPkXrLZ+hDuNrZCnj29CQpr4X1E= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo= -github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01CGwFsrv11mJRHWJ6aifDLfdV3aVjFF0zg= github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc= github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw= @@ -747,14 +742,10 @@ github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9 github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc= github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs= github.com/jackc/pgx/v4 v4.15.0/go.mod h1:D/zyOyXiaM1TmVWnOM18p0xdDtdakRBa0RsVGI3U3bw= -github.com/jackc/pgx/v5 v5.10.0 h1:VhSvgU2jSli8o3AqIEOTJr7rZwAEUVo4E4XhR94Zfr0= -github.com/jackc/pgx/v5 v5.10.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4= github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= github.com/jackc/puddle v1.2.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk= -github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo= -github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jcmturner/gofork v0.0.0-20180107083740-2aebee971930/go.mod h1:MK8+TM0La+2rjBD4jE12Kj1pCCxK7d2LK/UM3ncEo0o= github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= @@ -885,8 +876,6 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= -github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w= -github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= github.com/ncw/swift v1.0.52/go.mod h1:23YIA4yWVnGwv2dQlN4bB7egfYX6YLn0Yo/S6zZO/ZM= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/olebedev/when v1.1.0 h1:dlpoRa7huImhNtEx4yl0WYfTHVEWmJmIWd7fEkTHayc= @@ -931,8 +920,6 @@ github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9Z github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA= github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg= github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is= -github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= -github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ= github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= @@ -1737,34 +1724,6 @@ honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWh honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg= honnef.co/go/tools v0.0.1-2020.1.3/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= -modernc.org/cc/v4 v4.28.4 h1:Hd/4Es+MBj+/7hSdZaisNyu6bv3V0Dp2MdllyfqaH+c= -modernc.org/cc/v4 v4.28.4/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI= -modernc.org/ccgo/v4 v4.34.4 h1:OVnSOWQjVKOYkFxoHYB+qQmSHK5gqMqARM+K9DpR/Ws= -modernc.org/ccgo/v4 v4.34.4/go.mod h1:qdKqE8FNIYyysougB1RX9MxCzp5oJOcQXSobANJ4TuE= -modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM= -modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU= -modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI= -modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito= -modernc.org/gc/v3 v3.1.3 h1:6QAplYyVO+KdPW3pGnqmJDUxtkec8ooEWvks/hhU3lc= -modernc.org/gc/v3 v3.1.3/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY= -modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks= -modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI= -modernc.org/libc v1.73.4 h1:+ra4Ui8ngyt8HDcO1FTDPWlkAh6yOdaO2yAoh8MddQA= -modernc.org/libc v1.73.4/go.mod h1:DXZ3eO8qMCNn2SnmTNCiC71nJ9Rcq3PsnpU6Vc4rWK8= -modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU= -modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg= -modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI= -modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw= -modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg= -modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns= -modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w= -modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE= -modernc.org/sqlite v1.53.0 h1:20WG8N9q4ji/dEqGk4uiI0c6OPjSeLTNYGFCc3+7c1M= -modernc.org/sqlite v1.53.0/go.mod h1:xoEpOIpGrgT48H5iiyt/YXPCZPEzlfmfFwtk8Lklw8s= -modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0= -modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A= -modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= -modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= nhooyr.io/websocket v1.8.7/go.mod h1:B70DZP8IakI65RVQ51MsWP/8jndNma26DVA/nFSCgW0= pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= diff --git a/internal/beads/beads.go b/internal/beads/beads.go index baf010799..c254b8cd1 100644 --- a/internal/beads/beads.go +++ b/internal/beads/beads.go @@ -421,13 +421,27 @@ func findLocalBeadsDir() string { } // findDatabaseInBeadsDir searches for a database within a .beads directory. -// Checks metadata.json for the Dolt database path. For server mode, no local -// directory is required. For embedded mode, checks both the embeddeddolt/ -// directory (where the embedded engine stores data) and the legacy dolt/ path. -// Returns empty string if no database is found. +// Checks metadata.json for the selected implementation's database path. For +// server mode, no local path needs to exist yet: authoritative +// metadata is enough to route the caller without falling through to Dolt. +// Embedded Dolt checks both embeddeddolt/ and the legacy dolt/ path. Returns +// empty string if no database is configured or found. func findDatabaseInBeadsDir(beadsDir string, _ bool) string { // Check for metadata.json first (single source of truth) - if cfg, err := configfile.Load(beadsDir); err == nil && cfg != nil { + cfg, err := configfile.Load(beadsDir) + if err != nil { + // A present but unreadable/invalid metadata file is authoritative. Do + // not bypass it by discovering a leftover local Dolt directory; callers + // that need the detailed error should use OpenBestAvailable. + return "" + } + if cfg != nil { + if !configfile.IsSupportedBackend(cfg.Backend) { + // Unknown and removed backend markers are not Dolt aliases. Let the + // storage-selection layer report the metadata error without routing + // through a leftover local Dolt directory. + return "" + } // For Dolt server mode, database is on the server - no local directory required if cfg.IsDoltServerMode() { return cfg.DatabasePath(beadsDir) @@ -491,6 +505,7 @@ func FindDatabasePath() string { // BEADS_DIR is set but no database found - this is OK for --no-db mode // Return empty string and let the caller handle it + return "" } // 2. Check BEADS_DB environment variable (deprecated but still supported) diff --git a/internal/beads/sqlite_database_path_test.go b/internal/beads/sqlite_database_path_test.go new file mode 100644 index 000000000..f4325cd18 --- /dev/null +++ b/internal/beads/sqlite_database_path_test.go @@ -0,0 +1,88 @@ +package beads + +import ( + "os" + "path/filepath" + "testing" +) + +// The sqlite backend is a removed-backend tombstone: discovery must return "" +// so store selection reports the metadata error, and it must never create the +// database file the removed backend would have provisioned. +func TestFindDatabasePathSQLiteMetadataOutsideCWD(t *testing.T) { + tests := []struct { + name string + metadata string + relativePath string + }{ + { + name: "default path", + metadata: `{"backend":"sqlite","sqlite_path":"beads.db"}`, + relativePath: "beads.db", + }, + { + name: "custom relative path", + metadata: `{"backend":"sqlite","sqlite_path":"data/custom.db"}`, + relativePath: filepath.Join("data", "custom.db"), + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + root := t.TempDir() + cwd := filepath.Join(root, "working-directory") + beadsDir := filepath.Join(root, "external-workspace", ".beads") + if err := os.MkdirAll(cwd, 0o750); err != nil { + t.Fatalf("create working directory: %v", err) + } + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatalf("create beads directory: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(tt.metadata), 0o600); err != nil { + t.Fatalf("write metadata.json: %v", err) + } + + t.Chdir(cwd) + t.Setenv("BEADS_DIR", beadsDir) + t.Setenv("BEADS_DB", "") + t.Setenv("BD_DB", "") + + dbPath := filepath.Join(beadsDir, tt.relativePath) + if _, err := os.Stat(dbPath); !os.IsNotExist(err) { + t.Fatalf("SQLite database unexpectedly exists before discovery: %v", err) + } + + if got := FindDatabasePath(); got != "" { + t.Errorf("FindDatabasePath() = %q, want \"\" for the removed sqlite backend", got) + } + if _, err := os.Stat(dbPath); !os.IsNotExist(err) { + t.Fatalf("FindDatabasePath created SQLite database path %q: %v", dbPath, err) + } + }) + } +} + +func TestFindDatabasePathDoesNotBypassCorruptMetadata(t *testing.T) { + root := t.TempDir() + beadsDir := filepath.Join(root, "selected", ".beads") + leftoverDolt := filepath.Join(beadsDir, "embeddeddolt") + if err := os.MkdirAll(leftoverDolt, 0o750); err != nil { + t.Fatalf("create leftover Dolt directory: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte("{"), 0o600); err != nil { + t.Fatalf("write corrupt metadata.json: %v", err) + } + ambiguousCWD := filepath.Join(root, "ambient") + if err := os.MkdirAll(filepath.Join(ambiguousCWD, ".beads", "embeddeddolt"), 0o750); err != nil { + t.Fatalf("create ambient Dolt workspace: %v", err) + } + t.Chdir(ambiguousCWD) + + t.Setenv("BEADS_DIR", beadsDir) + t.Setenv("BEADS_DB", "") + t.Setenv("BD_DB", "") + + if got := FindDatabasePath(); got != "" { + t.Fatalf("FindDatabasePath() = %q with corrupt metadata, want empty path instead of leftover Dolt", got) + } +} diff --git a/internal/configfile/backend_messages.go b/internal/configfile/backend_messages.go new file mode 100644 index 000000000..74dba9310 --- /dev/null +++ b/internal/configfile/backend_messages.go @@ -0,0 +1,51 @@ +package configfile + +import "fmt" + +// This file is the single source of truth for the user-facing removed-backend +// and unknown-backend messages. cmd/bd, the public beads package, and the Dolt +// store must all fail closed with the same text, so the wording is deliberately +// centralized here. The framing of these messages is pending a separate +// maintainer decision — reword them here, in one place, once that lands. + +// RemovedBackendRationale explains why direct PostgreSQL/MySQL support was +// removed. Shortened site-specific messages (e.g. bd init flag guidance) +// compose with this clause directly. +const RemovedBackendRationale = "direct support for general-purpose server databases was rolled back to keep Beads simple and resource-light" + +// RemovedSQLiteRationale explains why the SQLite backend was removed. SQLite is +// not a server database, so it carries its own rationale instead of reusing +// RemovedBackendRationale. +const RemovedSQLiteRationale = "the SQLite backend was rolled back to consolidate storage on a single engine and dialect and keep Beads simple and robust" + +// BackendNotOpenedGuarantee is the fail-closed data-safety guarantee included +// in backend rejection errors: refusing a workspace never opens, creates, or +// modifies its storage. +const BackendNotOpenedGuarantee = "no storage database was opened or modified" + +// removedBackendRationale picks the rationale clause for a removed backend. +func removedBackendRationale(backend string) string { + if backend == BackendSQLite { + return RemovedSQLiteRationale + } + return RemovedBackendRationale +} + +// RemovedBackendDetail returns the shared body of every removed-backend error: +// the rationale, the untouched-data guarantee, and the migration path. Callers +// prepend a site-specific lead-in; RemovedBackendError carries the standard one. +func RemovedBackendDetail(backend string) string { + return fmt.Sprintf("%s; the configured %s database was not opened or modified; export it with a bd version that supports %s, then follow bd help init-safety to reinitialize with Dolt and import the exported data", removedBackendRationale(backend), backend, backend) +} + +// RemovedBackendError is the standard fail-closed error for metadata that +// selects a backend whose direct support was removed. +func RemovedBackendError(backend string) error { + return fmt.Errorf("storage backend %q is no longer supported: %s", backend, RemovedBackendDetail(backend)) +} + +// UnknownBackendError is the standard fail-closed error for metadata that +// names a backend this build does not recognize. +func UnknownBackendError(backend string) error { + return fmt.Errorf("storage backend %q in metadata.json is not recognized or supported; %s; the supported backend is %q; fix or restore metadata.json and retry", backend, BackendNotOpenedGuarantee, BackendDolt) +} diff --git a/internal/configfile/configfile.go b/internal/configfile/configfile.go index 712d2a4cf..8ec06008b 100644 --- a/internal/configfile/configfile.go +++ b/internal/configfile/configfile.go @@ -17,7 +17,7 @@ const ConfigFileName = "metadata.json" type Config struct { Database string `json:"database"` - Backend string `json:"backend,omitempty"` // Storage backend: "dolt" (default), "postgres", "mysql", or "sqlite". Read via GetBackend(). + Backend string `json:"backend,omitempty"` // Storage backend: "dolt" (default); legacy "postgres"/"mysql"/"sqlite" values are rejection tombstones. Read via GetBackend(). // Deletions configuration DeletionsRetentionDays int `json:"deletions_retention_days,omitempty"` // 0 means use default (3 days) @@ -36,17 +36,16 @@ type Config struct { DoltRemotesAPIPort int `json:"dolt_remotesapi_port,omitempty"` // Dolt remotesapi port for federation (default: 8080) // Note: Password should be set via BEADS_DOLT_PASSWORD env var for security - // Postgres backend (backend="postgres"). Password is NEVER persisted; it - // comes from BEADS_PG_PASSWORD or BEADS_POSTGRES_URL. - PostgresDSN string `json:"postgres_dsn,omitempty"` // e.g. postgres://user@host:5432/db (no password) - PostgresSchema string `json:"postgres_schema,omitempty"` // per-workspace schema (search_path) + // Deprecated backend fields are retained only to round-trip metadata written by + // the short-lived PostgreSQL/MySQL implementations. They are not connection + // configuration for current builds; store selection rejects those backends. + PostgresDSN string `json:"postgres_dsn,omitempty"` + PostgresSchema string `json:"postgres_schema,omitempty"` + MySQLDSN string `json:"mysql_dsn,omitempty"` + MySQLDatabase string `json:"mysql_database,omitempty"` - // MySQL backend (backend="mysql"). Password is NEVER persisted; it comes from - // BEADS_MYSQL_PASSWORD or BEADS_MYSQL_URL. - MySQLDSN string `json:"mysql_dsn,omitempty"` // e.g. user@tcp(host:3306)/ (no password) - MySQLDatabase string `json:"mysql_database,omitempty"` // per-workspace database (MySQL's isolation unit) - - // SQLite backend (backend="sqlite"). File-based, embedded; no credentials. + // Deprecated: retained only to round-trip metadata written by the removed + // SQLite backend (backend="sqlite"); store selection rejects that backend. SQLitePath string `json:"sqlite_path,omitempty"` // database file, relative to the beads dir (default beads.db) // Project identity — unique ID generated at bd init time. @@ -231,9 +230,9 @@ type BackendCapabilities struct { SingleProcessOnly bool } -// CapabilitiesForBackend returns capabilities for a backend string. -// Dolt is the only supported backend. Returns SingleProcessOnly=true by default; -// use Config.GetCapabilities() to properly handle server mode. +// CapabilitiesForBackend returns capabilities for a backend string. Embedded Dolt +// is single-process-only; use Config.GetCapabilities() to account for +// Dolt server and proxied-server modes. func CapabilitiesForBackend(_ string) BackendCapabilities { return BackendCapabilities{SingleProcessOnly: true} } @@ -249,10 +248,19 @@ func (c *Config) GetCapabilities() BackendCapabilities { return CapabilitiesForBackend(backend) } -// GetBackend returns the configured storage backend. Only the explicitly-allowlisted -// non-default backends ("postgres", "mysql") are honored; "", "dolt", and any legacy -// or unknown value resolve to dolt so the default path stays byte-identical and a -// typo fails safe to Dolt. +// IsSupportedBackend reports whether backend selects an implementation shipped by +// beads. The empty value is the legacy/default spelling of Dolt. +func IsSupportedBackend(backend string) bool { + return backend == "" || backend == BackendDolt +} + +// GetBackend returns the configured storage backend. PostgreSQL, MySQL, and +// SQLite remain recognizable here so workspaces created by earlier builds can +// fail loudly at store selection instead of silently falling back to an empty +// Dolt database. +// Empty and explicit Dolt retain the established Dolt behavior. GetBackend keeps +// the historical Dolt fallback for unknown values, so storage-selection callers +// must check IsSupportedBackend(c.Backend) before opening or creating storage. func (c *Config) GetBackend() string { if c != nil { switch c.Backend { @@ -276,82 +284,6 @@ func (c *Config) GetSQLitePath() string { return c.SQLitePath } -// GetPostgresDSN returns the base Postgres connection string: BEADS_POSTGRES_URL (a -// full override that may carry a password) if set, else the persisted, -// password-free metadata postgres_dsn. It never merges a password — password -// resolution (BEADS_PG_PASSWORD_COMMAND, BEADS_PG_PASSWORD, the credentials file) -// and placement happen at open time in the postgres backend, which owns the pgx -// parser this low-level package must not import (see the note at RedactPassword). -func (c *Config) GetPostgresDSN() string { - if u := os.Getenv("BEADS_POSTGRES_URL"); u != "" { - return u - } - if c == nil { - return "" - } - return c.PostgresDSN -} - -// GetPostgresPasswordCommand returns the credential command that resolves the -// Postgres password: BEADS_PG_PASSWORD_COMMAND. Empty means no command — the static -// BEADS_PG_PASSWORD / credentials-file path applies. The command's stdout is a -// password (a bare token or a {token,expires_in} envelope); it is run at open time, -// out-ranking the static password so a rotating secret is never shadowed by a stale -// env value. It is deliberately read from the environment only, NOT metadata.json: -// a metadata-sourced command is arbitrary code run on open, so persisting it waits -// on a workspace-trust gate. -func (c *Config) GetPostgresPasswordCommand() string { - return os.Getenv("BEADS_PG_PASSWORD_COMMAND") -} - -// GetPostgresSchema returns the per-workspace Postgres schema (search_path). -func (c *Config) GetPostgresSchema() string { - if c == nil { - return "" - } - return c.PostgresSchema -} - -// GetMySQLDSN returns the base MySQL server DSN: BEADS_MYSQL_URL (a full override -// that may carry a password) if set, else the persisted, password-free metadata -// mysql_dsn. It never merges a password — password resolution -// (BEADS_MYSQL_PASSWORD_COMMAND, BEADS_MYSQL_PASSWORD, the credentials file) and -// placement happen at open time in the mysql backend, which owns the go-sql-driver -// parser this low-level package must not import (see the note at RedactPassword). -func (c *Config) GetMySQLDSN() string { - if u := os.Getenv("BEADS_MYSQL_URL"); u != "" { - return u - } - if c == nil { - return "" - } - return c.MySQLDSN -} - -// GetMySQLPasswordCommand returns the credential command that resolves the MySQL -// password: BEADS_MYSQL_PASSWORD_COMMAND. Empty means no command — the static -// BEADS_MYSQL_PASSWORD / credentials-file path applies. The command's stdout is a -// password (a bare token or a {token,expires_in} envelope); it is run at open time, -// out-ranking the static password so a rotating secret is never shadowed by a stale -// env value. It is deliberately read from the environment only, NOT metadata.json: -// a metadata-sourced command is arbitrary code run on open, so persisting it waits -// on a workspace-trust gate. -func (c *Config) GetMySQLPasswordCommand() string { - return os.Getenv("BEADS_MYSQL_PASSWORD_COMMAND") -} - -// GetMySQLDatabase returns the per-workspace MySQL database (isolation unit). -func (c *Config) GetMySQLDatabase() string { - if c == nil { - return "" - } - return c.MySQLDatabase -} - -// Password redaction for persistence lives in pgdialect.RedactPassword, not here: -// it must fail closed (verify with pgx that no password survives) and therefore -// depends on the pgx parser, which this low-level config package must not import. - // Dolt mode constants const ( DoltModeEmbedded = "embedded" diff --git a/internal/configfile/configfile_test.go b/internal/configfile/configfile_test.go index 9f9bbed8e..f4ba09981 100644 --- a/internal/configfile/configfile_test.go +++ b/internal/configfile/configfile_test.go @@ -629,10 +629,10 @@ func TestProxiedServerClientInfo_ResolvedPaths(t *testing.T) { }) } -// TestGetBackendAllowlist verifies the allowlist semantics: the SQL backends -// (postgres, mysql, sqlite) are honored; every other value (empty, legacy, -// genuinely unknown) falls back to Dolt. This is the guard behind backend selection -// — a typo in metadata.json must fail safe to Dolt, never to an unintended backend. +// TestGetBackendAllowlist verifies the metadata-routing semantics: current backends +// and removed-backend tombstones remain recognizable, while empty or unknown values +// retain the historical Dolt fallback. Store selection rejects the tombstones before +// it can open an empty Dolt database. func TestGetBackendAllowlist(t *testing.T) { fallsBackToDolt := []struct { name string @@ -662,6 +662,29 @@ func TestGetBackendAllowlist(t *testing.T) { } } +func TestSupportedBackendAllowlist(t *testing.T) { + tests := []struct { + name string + backend string + supported bool + }{ + {name: "implicit dolt", backend: "", supported: true}, + {name: "dolt", backend: BackendDolt, supported: true}, + {name: "sqlite", backend: BackendSQLite, supported: false}, + {name: "postgres", backend: BackendPostgres, supported: false}, + {name: "mysql", backend: BackendMySQL, supported: false}, + {name: "unknown", backend: "mystery", supported: false}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := IsSupportedBackend(tt.backend); got != tt.supported { + t.Fatalf("IsSupportedBackend(%q) = %v, want %v", tt.backend, got, tt.supported) + } + }) + } +} + // TestDatabasePathAlwaysDolt tests that DatabasePath always returns the dolt path. func TestDatabasePathAlwaysDolt(t *testing.T) { beadsDir := "/home/user/project/.beads" diff --git a/internal/configfile/mysql_dsn_test.go b/internal/configfile/mysql_dsn_test.go deleted file mode 100644 index 7749a22f3..000000000 --- a/internal/configfile/mysql_dsn_test.go +++ /dev/null @@ -1,37 +0,0 @@ -package configfile - -import "testing" - -// GetMySQLDSN returns the BASE DSN and never merges a password: BEADS_MYSQL_PASSWORD -// is resolved and placed at open time in the mysql backend (which owns the -// go-sql-driver parser), so the persisted, password-free metadata DSN comes back -// unchanged here. -func TestGetMySQLDSNReturnsBaseUnmerged(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD", "secret") - c := &Config{MySQLDSN: "bts@tcp(127.0.0.1:3306)/"} - if got, want := c.GetMySQLDSN(), "bts@tcp(127.0.0.1:3306)/"; got != want { - t.Fatalf("GetMySQLDSN() = %q, want %q (must not merge the password)", got, want) - } -} - -// BEADS_MYSQL_URL (full override) takes precedence over the metadata DSN. -func TestGetMySQLDSNEnvURLPrecedence(t *testing.T) { - t.Setenv("BEADS_MYSQL_URL", "root:pw@tcp(host:3306)/db") - c := &Config{MySQLDSN: "other@tcp(127.0.0.1:3306)/"} - if got, want := c.GetMySQLDSN(), "root:pw@tcp(host:3306)/db"; got != want { - t.Fatalf("GetMySQLDSN() = %q, want %q", got, want) - } -} - -// GetMySQLPasswordCommand reads BEADS_MYSQL_PASSWORD_COMMAND from the environment -// only (metadata is deliberately excluded until a workspace-trust gate exists). -func TestGetMySQLPasswordCommand(t *testing.T) { - c := &Config{} - if got := c.GetMySQLPasswordCommand(); got != "" { - t.Fatalf("GetMySQLPasswordCommand() = %q, want empty when unset", got) - } - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "get-credential") - if got, want := c.GetMySQLPasswordCommand(), "get-credential"; got != want { - t.Fatalf("GetMySQLPasswordCommand() = %q, want %q", got, want) - } -} diff --git a/internal/configfile/postgres_dsn_test.go b/internal/configfile/postgres_dsn_test.go deleted file mode 100644 index 0ffbc57d3..000000000 --- a/internal/configfile/postgres_dsn_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package configfile - -import "testing" - -// GetPostgresDSN returns the BASE DSN and never merges a password: BEADS_PG_PASSWORD -// is resolved and placed at open time in the postgres backend (which owns the pgx -// parser), so the persisted, password-free metadata DSN comes back unchanged here. -func TestGetPostgresDSNReturnsBaseUnmerged(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD", "secret") - c := &Config{PostgresDSN: "postgres://bts@127.0.0.1:5432/db"} - if got, want := c.GetPostgresDSN(), "postgres://bts@127.0.0.1:5432/db"; got != want { - t.Fatalf("GetPostgresDSN() = %q, want %q (must not merge the password)", got, want) - } -} - -// BEADS_POSTGRES_URL (full override) takes precedence over the metadata DSN. -func TestGetPostgresDSNEnvURLPrecedence(t *testing.T) { - t.Setenv("BEADS_POSTGRES_URL", "postgres://a:b@host:5432/db") - c := &Config{PostgresDSN: "postgres://other@127.0.0.1:5432/db"} - if got, want := c.GetPostgresDSN(), "postgres://a:b@host:5432/db"; got != want { - t.Fatalf("GetPostgresDSN() = %q, want %q", got, want) - } -} - -// GetPostgresPasswordCommand reads BEADS_PG_PASSWORD_COMMAND from the environment -// only (metadata is deliberately excluded until a workspace-trust gate exists). -func TestGetPostgresPasswordCommand(t *testing.T) { - c := &Config{} - if got := c.GetPostgresPasswordCommand(); got != "" { - t.Fatalf("GetPostgresPasswordCommand() = %q, want empty when unset", got) - } - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "get-credential") - if got, want := c.GetPostgresPasswordCommand(), "get-credential"; got != want { - t.Fatalf("GetPostgresPasswordCommand() = %q, want %q", got, want) - } -} diff --git a/internal/storage/backend_marker.go b/internal/storage/backend_marker.go deleted file mode 100644 index 717b9614b..000000000 --- a/internal/storage/backend_marker.go +++ /dev/null @@ -1,16 +0,0 @@ -package storage - -// NonCommitGraphBackend is an affirmative *negative* marker: it is implemented -// only by backends whose Commit/GetCurrentCommit/Push do NOT participate in a -// real version-control commit graph (e.g. Postgres, SQLite). cmd/bd's PostRun -// skips its Dolt-only maintenance tail (auto-commit, auto-export, auto-backup, -// auto-push) when the active store implements this and returns true. -// -// The marker is negative and lives only on non-Dolt backends by design: a store -// that does NOT implement it is assumed to be Dolt, so the default path runs the -// full maintenance tail unchanged and stays byte-identical. New SQL backends opt -// OUT of Dolt maintenance by implementing this; they never have to touch the -// Dolt constructors. -type NonCommitGraphBackend interface { - CommitGraphUnsupported() bool -} diff --git a/internal/storage/conformance/audit_config_metadata_slots_repomtime.go b/internal/storage/conformance/audit_config_metadata_slots_repomtime.go index 5dc11eba2..116891e02 100644 --- a/internal/storage/conformance/audit_config_metadata_slots_repomtime.go +++ b/internal/storage/conformance/audit_config_metadata_slots_repomtime.go @@ -43,9 +43,8 @@ func auditFoldCount(all map[string]string, want string) int { // testAuditConfigKeyCaseSensitive pins the reference's config key-column collation. // The finding predicted Dolt's VARCHAR primary key would be case-insensitive, but // the embedded-Dolt oracle treats "MyKey" and "mykey" as DISTINCT keys: each holds -// its own value and GetAllConfig carries both rows. Postgres text and SQLite BINARY -// are case-sensitive too, so they match; the divergence suspect is real MySQL, whose -// server-default utf8mb4 collation is case-insensitive and would collapse the two. +// its own value and GetAllConfig carries both rows. SQLite's BINARY collation matches +// that behavior. func testAuditConfigKeyCaseSensitive(t *testing.T, f Factory) { s := f(t) c := ctx() diff --git a/internal/storage/conformance/audit_labels-comments-events.go b/internal/storage/conformance/audit_labels-comments-events.go index 8f2088cba..7aa69e159 100644 --- a/internal/storage/conformance/audit_labels-comments-events.go +++ b/internal/storage/conformance/audit_labels-comments-events.go @@ -10,7 +10,7 @@ import ( // Audit cases for the "labels-comments-events" slice. Each case pins a strange // but real behavior of the issueops label/comment/event helpers, validated // against the embedded-Dolt oracle. See the audit findings for provenance -// (issueops/events.go, issueops/labels.go, issueops/comments.go, sqlkit/annotations.go). +// (issueops/events.go, issueops/labels.go, issueops/comments.go; formerly sqlkit/annotations.go). // auditEventsOfType returns the events of exactly the given type, in the order // GetEvents returned them. @@ -245,7 +245,7 @@ func testAuditImportCommentSubSecond(t *testing.T, f Factory) { c := ctx() must(t, s.CreateIssue(c, withDefaults(&types.Issue{ID: "test-i", Title: "I"}), "a")) // Sub-second precision is intentionally backend-specific (Dolt datetime(0) rounds - // half-up; SQLite keeps the fraction; Postgres keeps microseconds), so we test the + // half-up; SQLite keeps the fraction), so we test the // portable contract every backend honors: a whole-second UTC timestamp round-trips // exactly. Higher fidelity on some backends is accepted, not asserted. ts := time.Date(2020, 1, 2, 3, 4, 5, 0, time.UTC) diff --git a/internal/storage/conformance/audit_molecule_wisp_batch_iter.go b/internal/storage/conformance/audit_molecule_wisp_batch_iter.go index 05c0ca51f..c56457bde 100644 --- a/internal/storage/conformance/audit_molecule_wisp_batch_iter.go +++ b/internal/storage/conformance/audit_molecule_wisp_batch_iter.go @@ -665,9 +665,8 @@ func testAuditGetNextChildID(t *testing.T, f Factory) { } } -// The self-heal scan (id LIKE parent.'%') is case-sensitive on every backend -// (Dolt/MySQL bin collation, Postgres "C", SQLite case_sensitive_like — see -// bd-oyvc2.10), so a different-cased sibling parent's children never advance +// The self-heal scan (id LIKE parent.'%') is case-sensitive on Dolt and SQLite +// (see bd-oyvc2.10), so a different-cased sibling parent's children never advance // this parent's counter. func testAuditGetNextChildIDCaseSensitive(t *testing.T, f Factory) { s := f(t) diff --git a/internal/storage/conformance/audit_search-counts-stats.go b/internal/storage/conformance/audit_search-counts-stats.go index 13acbde54..72068faba 100644 --- a/internal/storage/conformance/audit_search-counts-stats.go +++ b/internal/storage/conformance/audit_search-counts-stats.go @@ -182,7 +182,7 @@ func testAuditReadyWorkDepCreatedAtParity(t *testing.T, f Factory) { } // countByColumnInTx emits COALESCE(priority, ”) GROUP BY priority; priority is -// integer NOT NULL. MySQL/Dolt coerce the int to a string key, then +// integer NOT NULL. Both maintained implementations return a string key, then // countGroupForTablesInTx prepends 'P'. Reference keys: P0/P1/P2. func testAuditCountByPriority(t *testing.T, f Factory) { s := f(t) @@ -366,7 +366,7 @@ func testAuditSearchIdenticalTimestampIDOrder(t *testing.T, f Factory) { } // SortBy="closed" emits ORDER BY closed_at DESC, id ASC. closed_at is nullable; -// MySQL/Dolt place NULLs LAST on DESC. The open (NULL-closed) rows follow the +// the storage contract places NULLs last on DESC. The open (NULL-closed) rows follow the // closed ones, ordered by id ASC. func testAuditSearchSortByClosedNullsLast(t *testing.T, f Factory) { s := f(t) @@ -409,9 +409,9 @@ func testAuditSearchTextIDBranchExternalRef(t *testing.T, f Factory) { } } -// LIKE over raw-cased operands is case-sensitive on every backend: Dolt/MySQL use -// the utf8mb4_0900_bin table collation, Postgres uses collation "C", and SQLite -// sets PRAGMA case_sensitive_like (sqlite/dsn.go) — its default LIKE is +// LIKE over raw-cased operands is case-sensitive on both implementations: Dolt uses +// a binary table collation, and SQLite set PRAGMA case_sensitive_like (formerly sqlite/dsn.go). +// SQLite's default LIKE is // ASCII-case-insensitive and silently diverged (bd-oyvc2.10). IDPrefix filtering // (sqlbuild/filter.go `id LIKE ?`) must therefore distinguish test-AB from test-ab. func testAuditSearchIDPrefixCaseSensitive(t *testing.T, f Factory) { diff --git a/internal/storage/conformance/claim.go b/internal/storage/conformance/claim.go index 0dbc9ca05..5684e5c28 100644 --- a/internal/storage/conformance/claim.go +++ b/internal/storage/conformance/claim.go @@ -2,8 +2,6 @@ package conformance import ( "errors" - "fmt" - "sync" "testing" "time" @@ -12,10 +10,10 @@ import ( "github.com/steveyegge/beads/internal/types" ) -// Claim / lease behavior (Gas Station v1.1 dead-worker recovery). Every backend +// Claim / lease behavior (Gas Station v1.1 dead-worker recovery). Each backend // routes ClaimIssue/ClaimReadyIssue/HeartbeatIssue/ReclaimExpiredLeases through the -// shared issueops implementations, so these assertions hold identically on the Dolt -// reference and every SQL backend. issueops.WithLeaseTTL pins the lease deterministically +// shared issueops implementations, so these assertions hold identically on Dolt and +// SQLite. issueops.WithLeaseTTL pins the lease deterministically // so the reclaim path is testable without wall-clock waits. // testClaim: claiming an open issue stamps assignee, in_progress, started_at, and a @@ -156,102 +154,6 @@ func issueID(i *types.Issue) string { return i.ID } -// requireMultiWriter skips the caller unless the backend backs concurrent writers on -// separate connections. Postgres and MySQL use a multi-connection pool; SQLite pins its -// pool to a single connection (sqliteDialect.Open sets MaxOpenConns(1)) and embedded-Dolt -// serializes writers, so a "concurrent" claim race there only ever exercises the trivial -// serialized path. The dialect name is the profile signal: sqlkit-backed SQL stores -// expose DialectName(); the Dolt reference does not, so it skips via the type assertion. -func requireMultiWriter(t *testing.T, s storage.DoltStorage) { - t.Helper() - dn, ok := s.(interface{ DialectName() string }) - if !ok { - t.Skip("backend does not expose a SQL dialect; concurrent multi-writer claim race not applicable") - } - switch dn.DialectName() { - case "postgres", "mysql": - // multi-connection pool: a genuine cross-connection race. - default: - t.Skipf("dialect %q is single-writer (pool pinned to one connection); concurrent claim race not applicable", dn.DialectName()) - } -} - -// testClaimReadyIssueConcurrentExclusivity races many workers, each on its own pooled -// connection, to claim a small pool of ready issues and asserts every issue is claimed by -// exactly one worker. This is the multi-writer property the SQL backends exist for — the -// whole reason to run bd on Postgres/MySQL instead of single-writer Dolt — and the shared -// claim path's cross-process exclusivity (a conditional-UPDATE CAS: only the writer whose -// UPDATE finds the row still unassigned wins; the losers' ClaimReadyIssue retries the next -// ready candidate) is otherwise only asserted, never raced. Gated to the multi-connection -// backends; see requireMultiWriter. -func testClaimReadyIssueConcurrentExclusivity(t *testing.T, f Factory) { - s := f(t) - requireMultiWriter(t, s) - - const readyCount = 8 - for i := 0; i < readyCount; i++ { - must(t, s.CreateIssue(ctx(), withDefaults(&types.Issue{ - ID: fmt.Sprintf("ccx-%d", i), - Title: "ready", - Priority: 1, - }), "a")) - } - - const workers = 24 // > readyCount, so workers must contend and most must lose a race - - var ( - mu sync.Mutex - claims = make(map[string]string) // issueID -> claiming worker - dupes []string - errs []error - ) - start := make(chan struct{}) - var wg sync.WaitGroup - for w := 0; w < workers; w++ { - wg.Add(1) - go func(worker string) { - defer wg.Done() - <-start // barrier: release all workers together to maximize contention - // Drain: keep claiming until no ready work remains. Bounded so a bug that - // kept returning issues can never hang the suite. - for attempt := 0; attempt < readyCount+workers; attempt++ { - claimed, err := s.ClaimReadyIssue(ctx(), types.WorkFilter{}, worker) - if err != nil { - mu.Lock() - errs = append(errs, err) - mu.Unlock() - return - } - if claimed == nil { - return // no ready work left to claim - } - if claimed.Assignee != worker || claimed.Status != types.StatusInProgress { - t.Errorf("claimed %s not owned by claimer: assignee=%q status=%q", claimed.ID, claimed.Assignee, claimed.Status) - } - mu.Lock() - if prev, ok := claims[claimed.ID]; ok { - dupes = append(dupes, fmt.Sprintf("%s claimed by both %s and %s", claimed.ID, prev, worker)) - } else { - claims[claimed.ID] = worker - } - mu.Unlock() - } - }(fmt.Sprintf("worker-%d", w)) - } - close(start) - wg.Wait() - - for _, e := range errs { - t.Errorf("ClaimReadyIssue errored under concurrency: %v", e) - } - for _, d := range dupes { - t.Errorf("claim exclusivity violated — %s", d) - } - if len(claims) != readyCount { - t.Errorf("distinct claimed issues = %d, want %d (every ready issue claimed exactly once, none lost)", len(claims), readyCount) - } -} - // testHeartbeatRenewsLease: a heartbeat extends the lease (and keeps the claim). // Heartbeating with a one-hour TTL must push lease_expires_at far into the future. func testHeartbeatRenewsLease(t *testing.T, f Factory) { diff --git a/internal/storage/conformance/conformance.go b/internal/storage/conformance/conformance.go index 242e3ea87..9c625e2f3 100644 --- a/internal/storage/conformance/conformance.go +++ b/internal/storage/conformance/conformance.go @@ -149,7 +149,6 @@ func RunAll(t *testing.T, factory Factory) { t.Run("ClaimNotClaimable", func(t *testing.T) { testClaimNotClaimable(t, factory) }) t.Run("ClaimReadyIssue", func(t *testing.T) { testClaimReadyIssue(t, factory) }) t.Run("ClaimReadyIssueLabelFilters", func(t *testing.T) { testClaimReadyIssueLabelFilters(t, factory) }) - t.Run("ClaimReadyIssueConcurrentExclusivity", func(t *testing.T) { testClaimReadyIssueConcurrentExclusivity(t, factory) }) t.Run("HeartbeatRenewsLease", func(t *testing.T) { testHeartbeatRenewsLease(t, factory) }) t.Run("HeartbeatWisp", func(t *testing.T) { testHeartbeatWisp(t, factory) }) t.Run("ReclaimExpiredLease", func(t *testing.T) { testReclaimExpiredLease(t, factory) }) @@ -191,12 +190,10 @@ func RunAll(t *testing.T, factory Factory) { t.Run("Transaction", func(t *testing.T) { testTransaction(t, factory) }) } -// RunDeferredReads runs the subset of the suite covering the shared "deferred" -// non-version-control reads — statistics, external-ref lookup, and staleness — that -// the SQL-family backends (postgres/mysql/sqlite) implement through issueops. RunAll -// is the full fail-loud measurement (and stays red on genuinely Dolt-only methods -// like slots), so these backends run this focused GREEN gate instead. The Dolt -// reference covers the same cases via RunAll. +// RunDeferredReads runs the subset of the suite covering SQLite's shared +// non-version-control reads: statistics, external-ref lookup, and staleness. RunAll +// remains the full Dolt reference; SQLite runs this focused gate for methods supplied +// by issueops while its Dolt-only methods fail loudly as unsupported. func RunDeferredReads(t *testing.T, factory Factory) { t.Helper() t.Run("Statistics", func(t *testing.T) { testStatistics(t, factory) }) diff --git a/internal/storage/conformance/portable.go b/internal/storage/conformance/portable.go index 7cd0afaba..990520a51 100644 --- a/internal/storage/conformance/portable.go +++ b/internal/storage/conformance/portable.go @@ -12,9 +12,9 @@ import ( "github.com/steveyegge/beads/internal/types" ) -// This file holds the behavior contract for the "portable" non-version-control methods -// that the SQL-family backends (postgres/mysql/sqlite) implement through shared issueops -// helpers — molecule rollups, repo-mtime cache, event/dependency streams, dependent +// This file holds the behavior contract for the portable, non-version-control methods +// that SQLite implements through shared issueops helpers: molecule rollups, repo-mtime +// cache, event/dependency streams, dependent // counts, wisp cascade discovery, comment/audit writes, id rekey, source-repo purge, and // batch create. Each case is validated against the embedded-Dolt reference (the oracle) // and, once a method is wired into a backend, must match it there too. @@ -23,7 +23,7 @@ import ( // ties, tie-broken "current step") is asserted as a set, never positionally. // RunPortableMethods runs the portable-method behavior contract. The Dolt reference runs -// it via RunAll; each SQL backend runs it once the methods are implemented. +// it via RunAll; SQLite runs it for the methods supplied by the shared layer. func RunPortableMethods(t *testing.T, factory Factory) { t.Helper() t.Run("MoleculeProgress", func(t *testing.T) { testGetMoleculeProgress(t, factory) }) diff --git a/internal/storage/dolt/open.go b/internal/storage/dolt/open.go index 7cc664cb7..da371a1aa 100644 --- a/internal/storage/dolt/open.go +++ b/internal/storage/dolt/open.go @@ -48,6 +48,25 @@ func ApplyCLIAutoStart(beadsDir string, cfg *Config) { cfg.AutoStart = resolveAutoStart(true, autoStartCfg, mode) } +// requireDoltBackend keeps metadata-driven callers from bypassing the storage +// factory and interpreting another backend's workspace as Dolt. Removed backend +// identifiers deliberately remain recognizable in metadata so this check can fail +// closed instead of opening a new, empty Dolt database. +func requireDoltBackend(fileCfg *configfile.Config) error { + switch fileCfg.Backend { + case configfile.BackendPostgres, configfile.BackendMySQL, configfile.BackendSQLite: + return fmt.Errorf("configured storage backend %q is no longer supported and cannot be opened as Dolt: %s", fileCfg.Backend, configfile.RemovedBackendDetail(fileCfg.Backend)) + } + if !configfile.IsSupportedBackend(fileCfg.Backend) { + return fmt.Errorf("configured storage backend %q in metadata.json is not recognized and cannot be opened as Dolt; %s", fileCfg.Backend, configfile.BackendNotOpenedGuarantee) + } + backend := fileCfg.GetBackend() + if backend != configfile.BackendDolt { + return fmt.Errorf("configured storage backend %q cannot be opened as Dolt", backend) + } + return nil +} + // NewFromConfig creates a DoltStore based on the metadata.json configuration. // beadsDir is the path to the .beads directory. func NewFromConfig(ctx context.Context, beadsDir string) (*DoltStore, error) { @@ -66,6 +85,9 @@ func NewFromConfigWithCLIOptions(ctx context.Context, beadsDir string, cfg *Conf if fileCfg == nil { fileCfg = configfile.DefaultConfig() } + if err := requireDoltBackend(fileCfg); err != nil { + return nil, err + } // Apply central server config as defaults for any server fields not // set in the per-project metadata.json. This eliminates the need to @@ -93,6 +115,9 @@ func NewFromConfigWithOptions(ctx context.Context, beadsDir string, cfg *Config) if fileCfg == nil { fileCfg = configfile.DefaultConfig() } + if err := requireDoltBackend(fileCfg); err != nil { + return nil, err + } // Apply central server config as defaults for any server fields not // set in the per-project metadata.json. diff --git a/internal/storage/dolt/open_test.go b/internal/storage/dolt/open_test.go index 2e5b0b9af..9a3228d8b 100644 --- a/internal/storage/dolt/open_test.go +++ b/internal/storage/dolt/open_test.go @@ -162,6 +162,50 @@ func TestApplyCLIAutoStart_DisableAutoStartWins(t *testing.T) { } } +func TestConfigConstructorsRejectNonDoltBackends(t *testing.T) { + for _, backend := range []string{ + configfile.BackendSQLite, + configfile.BackendPostgres, + configfile.BackendMySQL, + "mystery", + } { + t.Run(backend, func(t *testing.T) { + beadsDir := t.TempDir() + if err := (&configfile.Config{Backend: backend}).Save(beadsDir); err != nil { + t.Fatalf("save metadata: %v", err) + } + + constructors := map[string]func() (*DoltStore, error){ + "standard": func() (*DoltStore, error) { + return NewFromConfigWithOptions(t.Context(), beadsDir, &Config{DisableAutoStart: true}) + }, + "cli": func() (*DoltStore, error) { + return NewFromConfigWithCLIOptions(t.Context(), beadsDir, &Config{DisableAutoStart: true}) + }, + } + for name, construct := range constructors { + t.Run(name, func(t *testing.T) { + store, err := construct() + if store != nil { + _ = store.Close() + t.Fatalf("non-Dolt backend %q unexpectedly opened as Dolt", backend) + } + if err == nil || !strings.Contains(err.Error(), "cannot be opened as Dolt") { + t.Fatalf("constructor error = %v, want backend mismatch", err) + } + if backend == configfile.BackendPostgres || backend == configfile.BackendMySQL { + for _, want := range []string{"no longer supported", "was not opened or modified", "bd help init-safety"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("removed-backend constructor error missing %q: %v", want, err) + } + } + } + }) + } + }) + } +} + func TestCLIDirUsesSharedDoltRootInSharedServerMode(t *testing.T) { sharedRoot := t.TempDir() t.Setenv("BEADS_DOLT_SHARED_SERVER", "1") diff --git a/internal/storage/domain/db/dependency_sqlite_parity_test.go b/internal/storage/domain/db/dependency_sqlite_parity_test.go deleted file mode 100644 index 415e0b264..000000000 --- a/internal/storage/domain/db/dependency_sqlite_parity_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package db - -import ( - "context" - "database/sql" - "path/filepath" - "strings" - "testing" - - "github.com/steveyegge/beads/internal/storage/domain" - storagesqlite "github.com/steveyegge/beads/internal/storage/sqlite" - "github.com/steveyegge/beads/internal/storage/sqlitedialect" - "github.com/steveyegge/beads/internal/types" -) - -func TestDependencyUseCaseSQLiteRejectsHierarchyBlockingButAllowsSiblings(t *testing.T) { - ctx := context.Background() - dbPath := filepath.Join(t.TempDir(), "beads.db") - - raw, err := sql.Open("sqlite", dbPath) - if err != nil { - t.Fatalf("open raw sqlite: %v", err) - } - if err := storagesqlite.InitSchema(ctx, raw); err != nil { - _ = raw.Close() - t.Fatalf("init sqlite schema: %v", err) - } - if err := raw.Close(); err != nil { - t.Fatalf("close raw sqlite: %v", err) - } - - runner, err := sqlitedialect.Open(dbPath) - if err != nil { - t.Fatalf("open translated sqlite: %v", err) - } - t.Cleanup(func() { _ = runner.Close() }) - - issueRepo := NewIssueSQLRepository(runner) - for _, id := range []string{"parent", "child", "sibling"} { - if err := issueRepo.Insert(ctx, newTestIssue(id, id), "tester", domain.InsertIssueOpts{}); err != nil { - t.Fatalf("insert issue %s: %v", id, err) - } - } - - depRepo := NewDependencySQLRepository(runner) - for _, childID := range []string{"child", "sibling"} { - if err := depRepo.Insert(ctx, - newDep(childID, "parent", types.DepParentChild), - "tester", domain.DepInsertOpts{}); err != nil { - t.Fatalf("insert parent-child %s -> parent: %v", childID, err) - } - } - - uc := domain.NewDependencyUseCase(depRepo) - if _, err := uc.AddDependencies(ctx, []*types.Dependency{ - newDep("sibling", "child", types.DepBlocks), - }, "tester", domain.BulkAddDepsOpts{}); err != nil { - t.Fatalf("siblings may carry ordering edges: %v", err) - } - - tests := []struct { - name string - dep *types.Dependency - wantError string - }{ - { - name: "child blocked by ancestor", - dep: newDep("child", "parent", types.DepBlocks), - wantError: "cannot be blocked by its ancestor", - }, - { - name: "conditional child blocked by ancestor", - dep: newDep("child", "parent", types.DepConditionalBlocks), - wantError: "cannot be blocked by its ancestor", - }, - { - name: "parent blocked by descendant", - dep: newDep("parent", "child", types.DepBlocks), - wantError: "cannot be blocked by its descendant", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - _, err := uc.AddDependencies(ctx, []*types.Dependency{tt.dep}, "tester", domain.BulkAddDepsOpts{}) - if err == nil { - t.Fatalf("AddDependencies(%s -> %s) succeeded, want hierarchy rejection", tt.dep.IssueID, tt.dep.DependsOnID) - } - if got := err.Error(); !strings.Contains(got, tt.wantError) { - t.Fatalf("error = %q, want substring %q", got, tt.wantError) - } - }) - } -} - -func TestDependencyUseCaseSQLiteRejectsCombinedSchedulingCycles(t *testing.T) { - ctx := context.Background() - dbPath := filepath.Join(t.TempDir(), "beads.db") - raw, err := sql.Open("sqlite", dbPath) - if err != nil { - t.Fatalf("open raw sqlite: %v", err) - } - if err := storagesqlite.InitSchema(ctx, raw); err != nil { - _ = raw.Close() - t.Fatalf("init sqlite schema: %v", err) - } - if err := raw.Close(); err != nil { - t.Fatalf("close raw sqlite: %v", err) - } - runner, err := sqlitedialect.Open(dbPath) - if err != nil { - t.Fatalf("open translated sqlite: %v", err) - } - t.Cleanup(func() { _ = runner.Close() }) - - issueRepo := NewIssueSQLRepository(runner) - for _, id := range []string{ - "block-a", "block-b", "block-c", - "parent-a", "parent-b", "parent-c", - "bulk-a", "bulk-b", "bulk-c", - "deferred-a", "deferred-b", "deferred-c", - } { - if err := issueRepo.Insert(ctx, newTestIssue(id, id), "tester", domain.InsertIssueOpts{}); err != nil { - t.Fatalf("insert issue %s: %v", id, err) - } - } - uc := domain.NewDependencyUseCase(NewDependencySQLRepository(runner)) - - for _, dep := range []*types.Dependency{ - newDep("block-a", "block-b", types.DepBlocks), - newDep("block-b", "block-c", types.DepParentChild), - } { - if err := uc.AddDependency(ctx, dep, "tester"); err != nil { - t.Fatalf("seed block-closing path: %v", err) - } - } - if err := uc.AddDependency(ctx, newDep("block-c", "block-a", types.DepConditionalBlocks), "tester"); err == nil || !strings.Contains(err.Error(), "cycle") { - t.Fatalf("blocking closer error = %v, want combined-cycle rejection", err) - } - - for _, dep := range []*types.Dependency{ - newDep("parent-a", "parent-b", types.DepBlocks), - newDep("parent-b", "parent-c", types.DepConditionalBlocks), - } { - if err := uc.AddDependency(ctx, dep, "tester"); err != nil { - t.Fatalf("seed parent-child-closing path: %v", err) - } - } - if err := uc.AddDependency(ctx, newDep("parent-c", "parent-a", types.DepParentChild), "tester"); err == nil || !strings.Contains(err.Error(), "cycle") { - t.Fatalf("parent-child closer error = %v, want combined-cycle rejection", err) - } - - for _, tc := range []struct { - name string - ids [3]string - opts domain.BulkAddDepsOpts - }{ - {name: "per edge", ids: [3]string{"bulk-a", "bulk-b", "bulk-c"}}, - {name: "deferred whole graph", ids: [3]string{"deferred-a", "deferred-b", "deferred-c"}, opts: domain.BulkAddDepsOpts{SkipPerEdgeCycleCheck: true}}, - } { - t.Run(tc.name, func(t *testing.T) { - _, err := uc.AddDependencies(ctx, []*types.Dependency{ - newDep(tc.ids[0], tc.ids[1], types.DepBlocks), - newDep(tc.ids[1], tc.ids[2], types.DepParentChild), - newDep(tc.ids[2], tc.ids[0], types.DepBlocks), - }, "tester", tc.opts) - if err == nil || !strings.Contains(err.Error(), "cycle") { - t.Fatalf("bulk mixed cycle error = %v, want rejection", err) - } - }) - } -} - -func TestDependencyUseCaseSQLiteValidatesPlannedHierarchyBeforeBlocking(t *testing.T) { - ctx := context.Background() - dbPath := filepath.Join(t.TempDir(), "beads.db") - raw, err := sql.Open("sqlite", dbPath) - if err != nil { - t.Fatalf("open raw sqlite: %v", err) - } - if err := storagesqlite.InitSchema(ctx, raw); err != nil { - _ = raw.Close() - t.Fatalf("init sqlite schema: %v", err) - } - if err := raw.Close(); err != nil { - t.Fatalf("close raw sqlite: %v", err) - } - runner, err := sqlitedialect.Open(dbPath) - if err != nil { - t.Fatalf("open translated sqlite: %v", err) - } - t.Cleanup(func() { _ = runner.Close() }) - - issueRepo := NewIssueSQLRepository(runner) - for _, id := range []string{ - "anc-grand", "anc-parent", "anc-child", - "desc-grand", "desc-parent", "desc-child", - "pair-parent", "pair-child", - "sibs-parent", "sibs-a", "sibs-b", - "prec-parent", "prec-middle", "prec-child", - } { - if err := issueRepo.Insert(ctx, newTestIssue(id, id), "tester", domain.InsertIssueOpts{}); err != nil { - t.Fatalf("insert issue %s: %v", id, err) - } - } - - depRepo := NewDependencySQLRepository(runner) - uc := domain.NewDependencyUseCase(depRepo) - tests := []struct { - name string - deps []*types.Dependency - wantError string - }{ - { - name: "block-first child to planned ancestor", - deps: []*types.Dependency{ - newDep("anc-child", "anc-grand", types.DepConditionalBlocks), - newDep("anc-child", "anc-parent", types.DepParentChild), - newDep("anc-parent", "anc-grand", types.DepParentChild), - }, - wantError: "cannot be blocked by its ancestor", - }, - { - name: "block-first ancestor to planned descendant", - deps: []*types.Dependency{ - newDep("desc-grand", "desc-child", types.DepBlocks), - newDep("desc-child", "desc-parent", types.DepParentChild), - newDep("desc-parent", "desc-grand", types.DepParentChild), - }, - wantError: "cannot be blocked by its descendant", - }, - { - name: "block-first same pair conflict reports hierarchy", - deps: []*types.Dependency{ - newDep("pair-child", "pair-parent", types.DepBlocks), - newDep("pair-child", "pair-parent", types.DepParentChild), - }, - wantError: "cannot be blocked by its ancestor", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - _, err := uc.AddDependencies(ctx, tt.deps, "tester", domain.BulkAddDepsOpts{}) - if err == nil || !strings.Contains(err.Error(), tt.wantError) { - t.Fatalf("error = %v, want %q", err, tt.wantError) - } - }) - } - _, err = uc.AddDependencies(ctx, []*types.Dependency{ - newDep("sibs-a", "sibs-b", types.DepBlocks), // Deliberately first. - newDep("sibs-a", "sibs-parent", types.DepParentChild), - newDep("sibs-b", "sibs-parent", types.DepParentChild), - }, "tester", domain.BulkAddDepsOpts{}) - if err != nil { - t.Fatalf("planned sibling ordering edge: %v", err) - } - - for _, id := range []string{"wplan-grand", "wplan-parent", "wplan-child"} { - issue := newTestIssue(id, id) - issue.Ephemeral = true - if err := issueRepo.Insert(ctx, issue, "tester", domain.InsertIssueOpts{UseWispsTable: true}); err != nil { - t.Fatalf("insert wisp %s: %v", id, err) - } - } - _, err = uc.AddWispDependencies(ctx, []*types.Dependency{ - newDep("wplan-child", "wplan-grand", types.DepConditionalBlocks), // Deliberately first. - newDep("wplan-child", "wplan-parent", types.DepParentChild), - newDep("wplan-parent", "wplan-grand", types.DepParentChild), - }, "tester", domain.BulkAddDepsOpts{}) - if err == nil || !strings.Contains(err.Error(), "cannot be blocked by its ancestor") { - t.Fatalf("planned wisp hierarchy error = %v, want ancestor rejection", err) - } - - // If a legacy blocking path also forms a cycle, hierarchy remains the - // canonical error, matching the classic issueops path. - for _, dep := range []*types.Dependency{ - newDep("prec-child", "prec-parent", types.DepParentChild), - newDep("prec-parent", "prec-middle", types.DepBlocks), - newDep("prec-middle", "prec-child", types.DepBlocks), - } { - if err := depRepo.Insert(ctx, dep, "tester", domain.DepInsertOpts{CycleValidated: true}); err != nil { - t.Fatalf("seed dependency %s -> %s: %v", dep.IssueID, dep.DependsOnID, err) - } - } - err = uc.AddDependency(ctx, newDep("prec-child", "prec-parent", types.DepBlocks), "tester") - if err == nil || !strings.Contains(err.Error(), "cannot be blocked by its ancestor") { - t.Fatalf("combined hierarchy/cycle error = %v, want ancestor rejection", err) - } -} diff --git a/internal/storage/embeddeddolt/iter_stubs.go b/internal/storage/embeddeddolt/iter_stubs.go index cb5f76fcb..39f8e9a4b 100644 --- a/internal/storage/embeddeddolt/iter_stubs.go +++ b/internal/storage/embeddeddolt/iter_stubs.go @@ -4,8 +4,8 @@ // // Slice-wrapping stubs for the Iter* methods. The embedded Dolt backend // uses a per-method short-lived connection model (`withConn`) which is -// incompatible with the dedicated-conn cursor pattern used by the -// streaming iterators in internal/storage/dolt and internal/storage/postgres. +// incompatible with the dedicated-connection cursor pattern used by the +// streaming iterators in internal/storage/dolt. // The interface ships complete now (be-jaavsb / be-yinl4d); a follow-up // child of be-yinl4d may add a streaming variant if EmbeddedDoltStore // gains a cursor-conn API. For now every Iter* method materializes the diff --git a/internal/storage/errors_unsupported.go b/internal/storage/errors_unsupported.go index fd4c70359..6867b739a 100644 --- a/internal/storage/errors_unsupported.go +++ b/internal/storage/errors_unsupported.go @@ -7,7 +7,7 @@ import "fmt" // taxonomy; this is the embryo of the seam's ErrUnsupported{Op, Backend}. type ErrUnsupported struct { Op string // method name, e.g. "AddLabel" or "Transaction.CreateIssues" - Backend string // e.g. "postgres" + Backend string // e.g. "sqlite" } func (e *ErrUnsupported) Error() string { diff --git a/internal/storage/issueops/blocked_state.go b/internal/storage/issueops/blocked_state.go index 61090dd9f..79a37065a 100644 --- a/internal/storage/issueops/blocked_state.go +++ b/internal/storage/issueops/blocked_state.go @@ -334,29 +334,6 @@ func unmarkBlockedTemplateForWisps() string { `, waitsForGateBlockedSQL) } -// SelfReferentialRecomputeTemplates returns the four is_blocked recompute UPDATE -// statements exactly as issueops emits them to the driver (with a representative -// IN-clause batch substituted for the placeholder). Each one updates issues/wisps -// while its WHERE clause self-references that same target table in EXISTS subqueries, -// which MySQL 8 rejects with error 1093 unless the mysqldialect driver rewrites the -// statement into a materialized derived-table form. -// -// It is exported solely so that rewrite can be regression-tested against these real -// templates instead of a hand-copied fixture: if a template ever drifts out of the -// shape the rewrite recognizes (a predicate before `id IN`, a backticked table, a -// renamed alias, changed whitespace), the mysqldialect rewrite test fails in a normal -// non-gated `go test` run rather than only under the env-gated MySQL conformance suite. -func SelfReferentialRecomputeTemplates() []string { - placeholders, _ := buildSQLInClause([]string{"a", "b", "c"}) - render := func(tmpl string) string { return fmt.Sprintf(tmpl, placeholders) } - return []string{ - render(markBlockedTemplateForIssues()), - render(unmarkBlockedTemplateForIssues()), - render(markBlockedTemplateForWisps()), - render(unmarkBlockedTemplateForWisps()), - } -} - //nolint:gosec // G201: callers pass constant templates; only IN-clause placeholders are formatted in. func runMarkUnmarkBatchedInTx(ctx context.Context, tx DBTX, markTmpl, unmarkTmpl string, ids []string) (int64, error) { var changed int64 diff --git a/internal/storage/issueops/count.go b/internal/storage/issueops/count.go index 92c4d9d21..71d7fcd3a 100644 --- a/internal/storage/issueops/count.go +++ b/internal/storage/issueops/count.go @@ -186,9 +186,7 @@ func countByColumnInTx(ctx context.Context, tx *sql.Tx, filter types.IssueFilter whereSQL = " WHERE " + strings.Join(clauses, " AND ") } // CAST the group column to text before COALESCE so an integer column (priority) - // COALESCEs with '' consistently. MySQL/Dolt coerce int->text implicitly, but - // Postgres rejects COALESCE(integer, '') (22P02); CAST(... AS CHAR) is portable - // (pgdialect -> ::text, native on MySQL/SQLite) and byte-identical on every backend. + // COALESCEs with '' consistently across Dolt and SQLite. //nolint:gosec // G201: tables.Main hardcoded; col validated by caller query := fmt.Sprintf("SELECT COALESCE(CAST(%s AS CHAR), ''), COUNT(*) FROM %s%s GROUP BY %s", col, tables.Main, whereSQL, col) rows, err := tx.QueryContext(ctx, query, args...) diff --git a/internal/storage/issueops/create.go b/internal/storage/issueops/create.go index 1803e7dd4..cf77aa61f 100644 --- a/internal/storage/issueops/create.go +++ b/internal/storage/issueops/create.go @@ -905,10 +905,9 @@ func ReconcileChildCounters(ctx context.Context, tx *sql.Tx, issues []*types.Iss if err == nil && current >= b.maxChild { continue } - // Qualify the existing-row column with the table name. Bare `last_child` - // on the update RHS is a valid MySQL "current row value" reference, but - // Postgres sees it as ambiguous between the target row and EXCLUDED - // (SQLSTATE 42702); table-qualifying it is unambiguous on every backend. + // Qualify the existing-row column with the table name so the canonical + // MySQL form and SQLite's translated ON CONFLICT form both unambiguously + // refer to the target row rather than the incoming value. //nolint:gosec // G201: table is one of two hardcoded constants. if _, err := tx.ExecContext(ctx, fmt.Sprintf(` INSERT INTO %[1]s (parent_id, last_child) VALUES (?, ?) diff --git a/internal/storage/issueops/helpers.go b/internal/storage/issueops/helpers.go index 86d1e584d..bebd719f5 100644 --- a/internal/storage/issueops/helpers.go +++ b/internal/storage/issueops/helpers.go @@ -89,10 +89,9 @@ func issueUpsertAssignments(table string, rejectStaleUpdate bool) string { assignments := make([]string, 0, len(issueUpsertColumns)) for _, col := range issueUpsertColumns { if rejectStaleUpdate { - // Qualify the existing-row references with the table name. Postgres's - // ON CONFLICT DO UPDATE rejects a bare `updated_at` as ambiguous (it could - // be the target row or EXCLUDED); .updated_at is unambiguous and is - // also accepted by MySQL/Dolt/SQLite. VALUES(...) is the incoming row. + // Qualify existing-row references with the table name so the target value + // remains unambiguous after the SQLite upsert translation. VALUES(...) is + // the incoming row in the canonical Dolt/MySQL-dialect statement. assignments = append(assignments, fmt.Sprintf("%s = IF(VALUES(updated_at) > %s.updated_at, VALUES(%s), %s.%s)", col, table, col, table, col)) } else { diff --git a/internal/storage/iter.go b/internal/storage/iter.go index 365ff27ab..848a593a7 100644 --- a/internal/storage/iter.go +++ b/internal/storage/iter.go @@ -2,7 +2,7 @@ // // Iter[T] is a generic streaming-iterator shape that lets storage callers // walk an unbounded result set without materializing the whole slice. -// Per-method implementations live in the dolt/ and postgres/ sub-packages. +// Per-method implementations live in the concrete backend packages. // // See be-jaavsb (design) and be-yinl4d (architecture) for the motivation. package storage diff --git a/internal/storage/mysql/completeness_test.go b/internal/storage/mysql/completeness_test.go deleted file mode 100644 index 7fd092bed..000000000 --- a/internal/storage/mysql/completeness_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package mysql - -import ( - "os" - "regexp" - "sort" - "testing" - - "github.com/steveyegge/beads/internal/storage/conformance" -) - -// legitimatelyUnsupported is the EXPLICIT denominator of every storage.DoltStorage -// method the Postgres wedge deliberately does not implement, each with a reason. -// -// The interface-completeness gate (TestInterfaceCompleteness) asserts the -// generated capability shell (unsupported_gen.go) contains EXACTLY these methods -// — no more, no less. This is the guard the red-team had to stand in for: a -// method that silently resolves to the typed-unsupported shell (the class that -// bit us: DeleteIssues, GetCustomStatuses, the batch reads, …) fails this test -// at build time instead of failing a user at runtime. Adding a method to the -// shell without an entry here is a hard error that forces the triage question: -// "implement it in sqlkit, or record here why the wedge legitimately omits it." -var legitimatelyUnsupported = map[string]string{ - // VersionControl — the Dolt commit graph. The wedge's whole premise is - // "bd on Postgres, history/version-control simply absent". - "Branch": "VC: Dolt branch", "Checkout": "VC: Dolt checkout", - "CurrentBranch": "VC", "DeleteBranch": "VC", "ListBranches": "VC", - // Commit/CommitWithConfig/CommitMergeResolution are NO-OPS on Postgres (data - // is already durable per-tx), not unsupported — implemented on postgres.Store. - "CommitExists": "VC", "GetCurrentCommit": "VC: Dolt hash", "Status": "VC", - "Log": "VC: dolt_log", "Merge": "VC", "GetConflicts": "VC", "ResolveConflicts": "VC", - - // HistoryViewer — Dolt time-travel. - "History": "history: dolt_log", "AsOf": "history: as-of ref", "Diff": "history: dolt_diff", - - // RemoteStore — Dolt remotes. - "AddRemote": "remote", "RemoveRemote": "remote", "HasRemote": "remote", "ListRemotes": "remote", - "Push": "remote", "Pull": "remote", "ForcePush": "remote", "PushRemote": "remote", - "PullRemote": "remote", "Fetch": "remote", "PushTo": "remote", "PullFrom": "remote", - - // SyncStore — Dolt peer sync. - "Sync": "sync", "SyncStatus": "sync", - - // FederationStore — Dolt-remote-backed peer table. - "AddFederationPeer": "federation", "GetFederationPeer": "federation", - "ListFederationPeers": "federation", "RemoveFederationPeer": "federation", - - // CompactionStore — bound to Dolt commit hashes. - "CheckEligibility": "compaction", "ApplyCompaction": "compaction", - "GetTier1Candidates": "compaction", "GetTier2Candidates": "compaction", - "SnapshotIssue": "compaction", "GetCompactionSnapshot": "compaction", "RestoreFromSnapshot": "compaction", - - // MergeSlot — the Dolt merge-serialization primitive. - "MergeSlotCreate": "merge-slot", "MergeSlotCheck": "merge-slot", - "MergeSlotAcquire": "merge-slot", "MergeSlotRelease": "merge-slot", -} - -var shellMethodRe = regexp.MustCompile(`func \(unsupportedDoltStorage\) ([A-Za-z0-9]+)\(`) - -// TestInterfaceCompleteness is the interface-completeness gate: the generated -// shell must equal the audited legitimatelyUnsupported set, both directions. -func TestInterfaceCompleteness(t *testing.T) { - src, err := os.ReadFile("unsupported_gen.go") - if err != nil { - t.Fatalf("read unsupported_gen.go: %v", err) - } - shell := map[string]bool{} - for _, m := range shellMethodRe.FindAllStringSubmatch(string(src), -1) { - shell[m[1]] = true - } - if len(shell) == 0 { - t.Fatal("parsed 0 shell methods — regex or file drift") - } - - // (1) No SILENT gap: every shell method must be explicitly justified. - var unjustified []string - for m := range shell { - if _, ok := legitimatelyUnsupported[m]; !ok { - unjustified = append(unjustified, m) - } - } - sort.Strings(unjustified) - for _, m := range unjustified { - t.Errorf("method %q resolves to the typed-unsupported shell but is NOT in legitimatelyUnsupported: implement it on *sqlkit.Store, or add it here with a reason", m) - } - - // (2) No STALE allowlist: every justified method must still be in the shell - // (else it was implemented and the entry should be removed). - var stale []string - for m := range legitimatelyUnsupported { - if !shell[m] { - stale = append(stale, m) - } - } - sort.Strings(stale) - for _, m := range stale { - t.Errorf("method %q is in legitimatelyUnsupported but no longer in the shell (implemented?): remove the allowlist entry", m) - } -} - -// TestUnsupportedContract is the behavioral complement to TestInterfaceCompleteness: -// every allowlisted method must actually return a typed storage.ErrUnsupported when -// called, not panic or return a different error. DB-free — the generated stubs ignore -// their receiver, so a zero-value store answers them. -func TestUnsupportedContract(t *testing.T) { - conformance.RunUnsupportedContract(t, &Store{}, legitimatelyUnsupported) -} diff --git a/internal/storage/mysql/conformance_test.go b/internal/storage/mysql/conformance_test.go deleted file mode 100644 index e7946f517..000000000 --- a/internal/storage/mysql/conformance_test.go +++ /dev/null @@ -1,80 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - "fmt" - "os" - "sync/atomic" - "testing" - "time" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/conformance" -) - -// TestConformance runs bd's backend-agnostic storage conformance suite against the -// MySQL backend. Every failure is a MySQL gap: an allowlisted-unsupported method -// (expected — completeness_test.go) or a latent divergence. Gated on -// BEADS_MYSQL_TEST_URL (a server DSN, e.g. user:pass@tcp(host:3306)/). -func TestConformance(t *testing.T) { - url := os.Getenv("BEADS_MYSQL_TEST_URL") - if url == "" { - t.Skip("BEADS_MYSQL_TEST_URL not set") - } - conformance.RunAll(t, mysqlConformanceFactory(url)) -} - -// TestDeferredReads runs the shared deferred non-version-control reads (statistics, -// external-ref, stale) that the backend now implements through issueops, as a GREEN -// gate. RunAll stays the fail-loud measurement (red on genuinely Dolt-only methods -// like slots), so this focused gate is what conformance.sh runs. Gated on -// BEADS_MYSQL_TEST_URL. -func TestDeferredReads(t *testing.T) { - url := os.Getenv("BEADS_MYSQL_TEST_URL") - if url == "" { - t.Skip("BEADS_MYSQL_TEST_URL not set") - } - conformance.RunDeferredReads(t, mysqlConformanceFactory(url)) -} - -// TestPortableMethods runs the full portable-method behavior contract. Red until the -// methods are wired into sqlkit; green after. Gated on BEADS_MYSQL_TEST_URL. -func TestPortableMethods(t *testing.T) { - url := os.Getenv("BEADS_MYSQL_TEST_URL") - if url == "" { - t.Skip("BEADS_MYSQL_TEST_URL not set") - } - conformance.RunPortableMethods(t, mysqlConformanceFactory(url)) -} - -// mysqlConformanceFactory provisions a fresh, isolated database per sub-test against -// the MySQL server at url, seeded with issue_prefix as `bd init` leaves it. -func mysqlConformanceFactory(url string) conformance.Factory { - base := time.Now().UnixNano() - var seq int64 - return func(t *testing.T) storage.DoltStorage { - ctx := context.Background() - database := fmt.Sprintf("conf_%d_%d", base, atomic.AddInt64(&seq, 1)) - - st, err := Provision(ctx, url, database) - if err != nil { - t.Fatalf("Provision: %v", err) - } - // The conformance factory contract wants an init'd store (issue_prefix set), - // as `bd init` leaves it. No Commit — MySQL has no commit graph. - if err := st.SetConfig(ctx, "issue_prefix", "test"); err != nil { - t.Fatalf("SetConfig(issue_prefix): %v", err) - } - t.Cleanup(func() { - if serverDSN, e := withDatabase(url, ""); e == nil { - if srv, e2 := sql.Open("mysql", serverDSN); e2 == nil { - _, _ = srv.ExecContext(context.Background(), "DROP DATABASE IF EXISTS `"+database+"`") - _ = srv.Close() - } - } - _ = st.Close() - }) - return st - } -} diff --git a/internal/storage/mysql/credential.go b/internal/storage/mysql/credential.go deleted file mode 100644 index 7026176c3..000000000 --- a/internal/storage/mysql/credential.go +++ /dev/null @@ -1,67 +0,0 @@ -package mysql - -import ( - "context" - "fmt" - "os" - - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/creds" - "github.com/steveyegge/beads/internal/storage/mysqldialect" -) - -// resolveDSNCredential returns baseDSN with a credential resolved and placed, ready to -// connect. The precedence, high to low: -// -// - BEADS_MYSQL_CREDENTIAL_COMMAND set is a hard error: an identity credential is -// presented as a username to a gateway, and this backend connects directly; -// - the DSN already carries a password (a full BEADS_MYSQL_URL, or an explicit -// --mysql-url) — it wins outright, no ladder is applied; -// - BEADS_MYSQL_PASSWORD_COMMAND — a credential command (e.g. Vault / RDS-IAM / GCP-IAM); -// run at open time, cached until near expiry; -// - BEADS_MYSQL_PASSWORD — a static password; -// - the credentials file [host:port] ($BEADS_CREDENTIALS_FILE or -// ~/.config/beads/credentials); -// - nothing configured — baseDSN is returned untouched and the connection is -// attempted with an empty password (valid only for an unsecured dev server; -// go-sql-driver reads no env vars or option files, so there is no ~/.my.cnf -// fallback). -// -// It fails closed: if a configured credential command errors, the open aborts — it -// never silently downgrades to a lower rung. -func resolveDSNCredential(ctx context.Context, cfg *configfile.Config, baseDSN string) (string, error) { - if os.Getenv("BEADS_MYSQL_CREDENTIAL_COMMAND") != "" { - return "", fmt.Errorf("mysql: BEADS_MYSQL_CREDENTIAL_COMMAND is reserved: an identity credential is presented as a username to a gateway, and the mysql backend connects directly to the database with no gateway to present it to; use BEADS_MYSQL_PASSWORD_COMMAND for a helper that produces a password") - } - // host:port keys the credentials-file lookup; ok=false (unix socket / unparseable) - // leaves the file rung not-configured (zero Host/Port), never failing. - host, port, _ := mysqldialect.HostPort(baseDSN) - return resolveDSNWithSources(ctx, baseDSN, - creds.CommandSource{Command: cfg.GetMySQLPasswordCommand(), Kind: creds.KindSecret, Label: "BEADS_MYSQL_PASSWORD_COMMAND"}, - creds.EnvSource{Var: "BEADS_MYSQL_PASSWORD"}, - creds.FileSource{Host: host, Port: port, Lookup: configfile.LookupCredentialsPassword, Label: "credentials-file"}, - ) -} - -// resolveDSNWithSources is the testable core of resolveDSNCredential: it applies the -// given credential ladder to baseDSN. -func resolveDSNWithSources(ctx context.Context, baseDSN string, sources ...creds.Source) (string, error) { - if mysqldialect.HasPassword(baseDSN) { - return baseDSN, nil - } - cred, ok, err := creds.ResolveLadder(ctx, sources...) - if err != nil { - return "", err - } - if !ok { - return baseDSN, nil - } - // The SQL backends take a secret in the password slot; an identity credential - // (presented as a username to a gateway) has no home on a direct connection, so - // refuse it loudly rather than land a token where a password belongs. Defense in - // depth behind the BEADS_MYSQL_CREDENTIAL_COMMAND reject above. - if cred.Kind != creds.KindSecret { - return "", fmt.Errorf("mysql: credential from %s is an identity, not a password; the mysql backend connects directly and has no gateway to present it to", cred.Source) - } - return mysqldialect.WithCredential(baseDSN, cred.Username, cred.Value) -} diff --git a/internal/storage/mysql/credential_test.go b/internal/storage/mysql/credential_test.go deleted file mode 100644 index 5d488a0ba..000000000 --- a/internal/storage/mysql/credential_test.go +++ /dev/null @@ -1,288 +0,0 @@ -package mysql - -import ( - "context" - "os" - "path/filepath" - "strings" - "testing" - - gomysql "github.com/go-sql-driver/mysql" - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/creds" -) - -const baseDSN = "bts@tcp(127.0.0.1:55441)/" - -// TestMain points the credentials-file rung at a nonexistent path in a private temp -// dir so tests never read the developer's real ~/.config/beads/credentials. -// go-sql-driver reads no ambient env/option files, so there is nothing else to -// neutralize. Tests that exercise the file rung override it per-test with t.Setenv. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "beads-mysql-cred-test") - if err != nil { - panic(err) - } - os.Setenv("BEADS_CREDENTIALS_FILE", filepath.Join(dir, "none")) - code := m.Run() - _ = os.RemoveAll(dir) - os.Exit(code) -} - -// password parses out and returns the password go-sql-driver sees. -func password(t *testing.T, dsn string) string { - t.Helper() - cfg, err := gomysql.ParseDSN(dsn) - if err != nil { - t.Fatalf("gomysql.ParseDSN(%q): %v", dsn, err) - } - return cfg.Passwd -} - -// user parses out and returns the username go-sql-driver sees. -func user(t *testing.T, dsn string) string { - t.Helper() - cfg, err := gomysql.ParseDSN(dsn) - if err != nil { - t.Fatalf("gomysql.ParseDSN(%q): %v", dsn, err) - } - return cfg.User -} - -// writeCredsFile writes an INI credentials file and returns its path. -func writeCredsFile(t *testing.T, body string) string { - t.Helper() - p := filepath.Join(t.TempDir(), "credentials") - if err := os.WriteFile(p, []byte(body), 0o600); err != nil { - t.Fatal(err) - } - return p -} - -func TestResolveDSNCredentialCommand(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "printf cmd-pw") - t.Setenv("BEADS_MYSQL_PASSWORD", "") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "cmd-pw" { - t.Fatalf("password = %q, want cmd-pw", pw) - } -} - -func TestResolveDSNCredentialEnv(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "") - t.Setenv("BEADS_MYSQL_PASSWORD", "env-pw") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "env-pw" { - t.Fatalf("password = %q, want env-pw", pw) - } -} - -// The command out-ranks the static env password. -func TestResolveDSNCredentialCommandBeatsEnv(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "printf cmd-wins") - t.Setenv("BEADS_MYSQL_PASSWORD", "env-loses") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "cmd-wins" { - t.Fatalf("password = %q, want cmd-wins", pw) - } -} - -// A configured-but-erroring command aborts the open and does NOT fall through to the -// env password. Here a bare token with whitespace is rejected by parseCredential — a -// configured error, not a command exit failure. -func TestResolveDSNCredentialFailsClosed(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", `printf 'access denied'`) - t.Setenv("BEADS_MYSQL_PASSWORD", "env-would-be-wrong") - _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err == nil { - t.Fatal("expected an error (fail-closed); a broken command must not fall through to BEADS_MYSQL_PASSWORD") - } -} - -// A command that exits non-zero also aborts (the other configured-error shape). -func TestResolveDSNCredentialFailsClosedOnExit(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "false") - t.Setenv("BEADS_MYSQL_PASSWORD", "env-would-be-wrong") - _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err == nil { - t.Fatal("expected an error when the command exits non-zero") - } -} - -// A getToken/ExecCredential JSON envelope resolves the password end-to-end. -func TestResolveDSNCredentialJSONEnvelope(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", `printf '{"access_token":"tok-pw","expires_in":90}'`) - t.Setenv("BEADS_MYSQL_PASSWORD", "") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "tok-pw" { - t.Fatalf("password = %q, want tok-pw", pw) - } -} - -// End-to-end: resolving a password into a userless base DSN must fail loudly (the -// grammar would silently drop it), not connect passwordless. -func TestResolveDSNCredentialUserlessDSNFailsLoudly(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "") - t.Setenv("BEADS_MYSQL_PASSWORD", "some-pw") - _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, "tcp(127.0.0.1:55441)/") - if err == nil { - t.Fatal("expected an error placing a password into a userless DSN") - } -} - -// withDatabase refuses a userless password-bearing DSN (the path that skips the -// ladder via an inline ":secret@tcp(host)/" URL) rather than silently dropping it. -func TestWithDatabaseRefusesUserlessPassword(t *testing.T) { - if _, err := withDatabase(":secret@tcp(127.0.0.1:55441)/", "db"); err == nil { - t.Fatal("expected withDatabase to refuse a userless password-bearing DSN") - } - // A normal user:pass DSN still works. - if _, err := withDatabase("bts:bts@tcp(127.0.0.1:55441)/", "db"); err != nil { - t.Fatalf("withDatabase rejected a valid DSN: %v", err) - } -} - -func TestResolveDSNCredentialNothingConfigured(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "") - t.Setenv("BEADS_MYSQL_PASSWORD", "") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if got != baseDSN { - t.Fatalf("dsn = %q, want it unchanged (%q)", got, baseDSN) - } -} - -func TestResolveDSNCredentialExistingPasswordWins(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "printf should-not-run") - t.Setenv("BEADS_MYSQL_PASSWORD", "should-not-run") - withPw := "bts:already-here@tcp(127.0.0.1:55441)/" - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, withPw) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "already-here" { - t.Fatalf("password = %q, want already-here (existing password must win)", pw) - } -} - -// The credentials file resolves the password when no command or env is set. -func TestResolveDSNCredentialFile(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "") - t.Setenv("BEADS_MYSQL_PASSWORD", "") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:55441]\npassword=file-pw\n")) - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "file-pw" { - t.Fatalf("password = %q, want file-pw", pw) - } -} - -// The env password out-ranks the credentials file. -func TestResolveDSNCredentialEnvBeatsFile(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "") - t.Setenv("BEADS_MYSQL_PASSWORD", "env-pw") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:55441]\npassword=file-pw\n")) - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "env-pw" { - t.Fatalf("password = %q, want env-pw (env out-ranks file)", pw) - } -} - -// A broken command fails closed even when the file could supply a valid password. -func TestResolveDSNCredentialBrokenCommandNotRescuedByFile(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "false") - t.Setenv("BEADS_MYSQL_PASSWORD", "") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:55441]\npassword=file-pw\n")) - if _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN); err == nil { - t.Fatal("expected fail-closed; the credentials file must not rescue a broken command") - } -} - -// A unix-socket DSN has no [host:port] endpoint, so the file rung degrades to -// not-configured (no crash), leaving the DSN untouched. -func TestResolveDSNCredentialFileUnixSocketDegrades(t *testing.T) { - t.Setenv("BEADS_MYSQL_PASSWORD_COMMAND", "") - t.Setenv("BEADS_MYSQL_PASSWORD", "") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:55441]\npassword=file-pw\n")) - unixDSN := "bts@unix(/tmp/mysql.sock)/db" - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, unixDSN) - if err != nil { - t.Fatal(err) - } - if got != unixDSN { - t.Fatalf("dsn = %q, want it unchanged (unix socket has no file-rung endpoint)", got) - } -} - -// A set BEADS_MYSQL_CREDENTIAL_COMMAND is a hard error, pre-empting even a -// password-bearing DSN and any lower rung. -func TestResolveDSNCredentialRejectsReservedIdentityVar(t *testing.T) { - t.Setenv("BEADS_MYSQL_CREDENTIAL_COMMAND", "get-credential") - t.Setenv("BEADS_MYSQL_PASSWORD", "would-otherwise-work") - _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, "bts:has-pw@tcp(127.0.0.1:55441)/") - if err == nil || !strings.Contains(err.Error(), "BEADS_MYSQL_CREDENTIAL_COMMAND") { - t.Fatalf("expected a reserved-var rejection naming BEADS_MYSQL_CREDENTIAL_COMMAND, got %v", err) - } -} - -// staticSource is a test Source with a fixed credential, used to exercise placement -// and the identity-refusal guard directly. -type staticSource struct{ cred creds.Credential } - -func (s staticSource) Name() string { return "test" } -func (s staticSource) Resolve(context.Context) (creds.Credential, bool, error) { - return s.cred, true, nil -} - -func TestResolveDSNCredentialRefusesIdentity(t *testing.T) { - src := staticSource{cred: creds.Credential{Value: "an-identity-token", Kind: creds.KindIdentity, Source: "test"}} - _, err := resolveDSNWithSources(context.Background(), baseDSN, src) - if err == nil || !strings.Contains(err.Error(), "identity") { - t.Fatalf("expected an identity-refusal error, got %v", err) - } -} - -// A credential carrying a username (a Vault dynamic user/password pair) places both, -// overriding the base DSN's user. -func TestResolveDSNCredentialPlacesUsername(t *testing.T) { - src := staticSource{cred: creds.Credential{Value: "pw", Username: "dyn", Kind: creds.KindSecret}} - got, err := resolveDSNWithSources(context.Background(), baseDSN, src) - if err != nil { - t.Fatal(err) - } - if u, pw := user(t, got), password(t, got); u != "dyn" || pw != "pw" { - t.Fatalf("(user,password) = (%q,%q), want (dyn,pw)", u, pw) - } -} - -// A dynamic username satisfies the userless-DSN requirement: a bare tcp(host)/ base -// plus a user/password pair is a valid configuration. -func TestResolveDSNWithSourcesUsernameSatisfiesUserlessBase(t *testing.T) { - src := staticSource{cred: creds.Credential{Value: "pw", Username: "dyn", Kind: creds.KindSecret}} - got, err := resolveDSNWithSources(context.Background(), "tcp(127.0.0.1:55441)/", src) - if err != nil { - t.Fatal(err) - } - if u, pw := user(t, got), password(t, got); u != "dyn" || pw != "pw" { - t.Fatalf("(user,password) = (%q,%q), want (dyn,pw)", u, pw) - } -} diff --git a/internal/storage/mysql/dialect.go b/internal/storage/mysql/dialect.go deleted file mode 100644 index 24ef3200b..000000000 --- a/internal/storage/mysql/dialect.go +++ /dev/null @@ -1,23 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/mysqldialect" -) - -// mysqlDialect is the MySQL SQL flavor. bd's canonical SQL is already MySQL, so this -// is nearly the identity dialect: mysqldialect.Open wraps go-sql-driver with a single -// rewrite (the self-referential is_blocked recompute UPDATE that MySQL 8 rejects) and -// passes everything else through verbatim. The dsn already targets the workspace -// database. -type mysqlDialect struct { - dsn string -} - -func (d mysqlDialect) Name() string { return "mysql" } - -func (d mysqlDialect) Open(_ context.Context) (*sql.DB, error) { - return mysqldialect.Open(d.dsn) -} diff --git a/internal/storage/mysql/dsn.go b/internal/storage/mysql/dsn.go deleted file mode 100644 index 5097e549a..000000000 --- a/internal/storage/mysql/dsn.go +++ /dev/null @@ -1,53 +0,0 @@ -package mysql - -import ( - "fmt" - - gomysql "github.com/go-sql-driver/mysql" -) - -// RedactPassword returns dsn with the password removed, or an error if it cannot be -// stripped. It uses go-sql-driver's own parser (never hand-rolled string surgery) and -// verifies with a re-parse that no password survives, failing closed. bd init persists -// the returned string to metadata.json; the password is re-supplied at open time by -// the credential ladder (see resolveDSNCredential in credential.go). -func RedactPassword(dsn string) (string, error) { - cfg, err := gomysql.ParseDSN(dsn) - if err != nil { - return "", fmt.Errorf("parse DSN: %w", err) - } - cfg.Passwd = "" - stripped := cfg.FormatDSN() - if again, err := gomysql.ParseDSN(stripped); err != nil || again.Passwd != "" { - return "", fmt.Errorf("refusing to persist a connection string that still carries a password; supply it via BEADS_MYSQL_PASSWORD instead of embedding it in --mysql-url") - } - return stripped, nil -} - -// withDatabase returns dsn with its default database set to database (or cleared when -// database is ""). Used to derive a server connection (for CREATE DATABASE) and the -// per-workspace connection from one base DSN. It also forces parseTime and UTC so -// datetime columns round-trip identically to the Dolt reference. -func withDatabase(dsn, database string) (string, error) { - cfg, err := gomysql.ParseDSN(dsn) - if err != nil { - return "", err - } - // The go-sql-driver grammar cannot carry a password without a username — - // FormatDSN would silently drop it. Refuse loudly rather than reformat this DSN - // into a passwordless one and connect (the same invariant mysqldialect.WithPassword - // enforces; this covers the path where a userless password-bearing DSN reaches us - // directly, e.g. an inline ":secret@tcp(host)/" URL that skips the credential ladder). - if cfg.User == "" && cfg.Passwd != "" { - return "", fmt.Errorf("connection string carries a password but no username; the MySQL DSN grammar cannot carry a password without a user (it would be silently dropped) — add a user to the DSN") - } - cfg.DBName = database - cfg.ParseTime = true - if cfg.Params == nil { - cfg.Params = map[string]string{} - } - // Pin the session time zone to UTC so CURRENT_TIMESTAMP defaults and reads match - // the shared layer's UTC assumption (and the Dolt reference). - cfg.Params["time_zone"] = "'+00:00'" - return cfg.FormatDSN(), nil -} diff --git a/internal/storage/mysql/fromconfig.go b/internal/storage/mysql/fromconfig.go deleted file mode 100644 index 4ee3d5112..000000000 --- a/internal/storage/mysql/fromconfig.go +++ /dev/null @@ -1,57 +0,0 @@ -package mysql - -import ( - "context" - "fmt" - - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/storage" -) - -// NewFromConfig opens the MySQL backend for a workspace. It reads the base server DSN -// and per-workspace database from .beads/metadata.json, resolves the password through -// the credential ladder (command > env > credentials file, fail-closed) and places it into the DSN — -// never persisting it — then provisions and returns the store. It is the factory arm -// cmd/bd dispatches to when metadata.json has backend="mysql". -func NewFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { - cfg, err := configfile.Load(beadsDir) - if err != nil { - return nil, fmt.Errorf("mysql: load config: %w", err) - } - dsn := cfg.GetMySQLDSN() - if dsn == "" { - return nil, fmt.Errorf("mysql: no DSN (set mysql_dsn in metadata.json, or BEADS_MYSQL_URL)") - } - dsn, err = resolveDSNCredential(ctx, cfg, dsn) - if err != nil { - return nil, fmt.Errorf("mysql: resolve credential: %w", err) - } - database := cfg.GetMySQLDatabase() - if database == "" { - return nil, fmt.Errorf("mysql: no database (set mysql_database in metadata.json)") - } - return Provision(ctx, dsn, database) -} - -// Provision opens the MySQL backend from an explicit server DSN and workspace -// database: it creates the database if absent and applies the schema (InitSchema — -// idempotent, config seeds on first provision only), then returns the store over the -// per-workspace connection. baseDSN may carry a password; it is used only to connect -// and is never persisted. bd init calls this directly; NewFromConfig calls it after -// resolving DSN/database from metadata. -func Provision(ctx context.Context, baseDSN, database string) (storage.DoltStorage, error) { - if baseDSN == "" { - return nil, fmt.Errorf("mysql: empty DSN") - } - if database == "" { - return nil, fmt.Errorf("mysql: empty database") - } - if err := InitSchema(ctx, baseDSN, database); err != nil { - return nil, err - } - wsDSN, err := withDatabase(baseDSN, database) - if err != nil { - return nil, fmt.Errorf("mysql: parse DSN: %w", err) - } - return New(ctx, Config{DSN: wsDSN}) -} diff --git a/internal/storage/mysql/redact_test.go b/internal/storage/mysql/redact_test.go deleted file mode 100644 index 4bd55a76e..000000000 --- a/internal/storage/mysql/redact_test.go +++ /dev/null @@ -1,117 +0,0 @@ -package mysql - -import ( - "testing" - - gomysql "github.com/go-sql-driver/mysql" -) - -// placeholderPW is an obvious non-secret stand-in used wherever a password appears in -// these tests, so nothing here can be mistaken for a leaked real credential. -const placeholderPW = "s3cr3t-PLACEHOLDER" - -// TestRedactPassword locks the security invariant for mysql.RedactPassword across every -// secret-bearing DSN shape the go-sql-driver grammar accepts. For each case it asserts -// BOTH: -// -// (a) the persisted string, re-parsed by go-sql-driver — the SAME parser that opens -// the connection — carries NO password (prove the secret is gone); and -// (b) every non-secret component (user, host:port, network, database, params, and the -// parseTime flag) survives redaction. -// -// A no-password DSN must additionally round-trip byte-for-byte unchanged. -func TestRedactPassword(t *testing.T) { - cases := []struct { - name string - dsn string - wantUser string - wantAddr string - wantNet string - wantDB string - wantParseTime bool - wantParams map[string]string - roundTripSame bool - }{ - { - name: "password present", - dsn: "bts:" + placeholderPW + "@tcp(127.0.0.1:3306)/beadsdb", - wantUser: "bts", wantAddr: "127.0.0.1:3306", wantNet: "tcp", wantDB: "beadsdb", - }, - { - // go-sql-driver splits the userinfo password on the LAST '@', so a password - // full of ':' '/' '#' '@' must still be stripped cleanly. - name: "password with special chars", - dsn: "bts:p@ss:w/rd#-" + placeholderPW + "@tcp(127.0.0.1:3306)/beadsdb", - wantUser: "bts", wantAddr: "127.0.0.1:3306", wantNet: "tcp", wantDB: "beadsdb", - }, - { - name: "password present, params + parseTime preserved", - dsn: "bts:" + placeholderPW + "@tcp(db.corp:3307)/beadsdb?parseTime=true&myapp=beads", - wantUser: "bts", wantAddr: "db.corp:3307", wantNet: "tcp", wantDB: "beadsdb", - wantParseTime: true, wantParams: map[string]string{"myapp": "beads"}, - }, - { - // The go-sql-driver grammar cannot carry a password without a username; - // FormatDSN drops the whole user:pass@ block, so redaction still removes the - // secret. (The loud refusal for this shape lives in withDatabase/WithPassword, - // not RedactPassword — here the invariant is only that the password is gone.) - name: "password but no username", - dsn: ":" + placeholderPW + "@tcp(127.0.0.1:3306)/beadsdb", - wantUser: "", wantAddr: "127.0.0.1:3306", wantNet: "tcp", wantDB: "beadsdb", - }, - { - // A canonical, param-free DSN must survive redaction byte-for-byte - // (go-sql-driver reorders query params on reformat, so the round-trip - // invariant is asserted only against a DSN already in canonical form). - name: "no password round-trips unchanged", - dsn: "bts@tcp(127.0.0.1:3306)/beadsdb", - wantUser: "bts", wantAddr: "127.0.0.1:3306", wantNet: "tcp", wantDB: "beadsdb", - roundTripSame: true, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := RedactPassword(tc.dsn) - if err != nil { - t.Fatalf("RedactPassword(%q) errored: %v", tc.dsn, err) - } - - // (a) The authoritative security check: the same parser go-sql-driver uses to - // open the connection must find no password in the persisted string. - if pw := password(t, got); pw != "" { - t.Fatalf("PASSWORD LEAK: RedactPassword(%q) = %q still carries password %q", tc.dsn, got, pw) - } - - // (b) Non-secret components must survive. - cfg, err := gomysql.ParseDSN(got) - if err != nil { - t.Fatalf("redacted DSN no longer parses: %q: %v", got, err) - } - if cfg.User != tc.wantUser { - t.Errorf("user = %q, want %q", cfg.User, tc.wantUser) - } - if cfg.Addr != tc.wantAddr { - t.Errorf("addr = %q, want %q", cfg.Addr, tc.wantAddr) - } - if cfg.Net != tc.wantNet { - t.Errorf("net = %q, want %q", cfg.Net, tc.wantNet) - } - if cfg.DBName != tc.wantDB { - t.Errorf("dbname = %q, want %q", cfg.DBName, tc.wantDB) - } - if cfg.ParseTime != tc.wantParseTime { - t.Errorf("parseTime = %v, want %v (must be preserved)", cfg.ParseTime, tc.wantParseTime) - } - for k, want := range tc.wantParams { - if got := cfg.Params[k]; got != want { - t.Errorf("param %q = %q, want %q (must be preserved)", k, got, want) - } - } - - if tc.roundTripSame && got != tc.dsn { - t.Errorf("no-password DSN must round-trip unchanged:\n in = %q\n out = %q", tc.dsn, got) - } - }) - } -} diff --git a/internal/storage/mysql/schema.go b/internal/storage/mysql/schema.go deleted file mode 100644 index d178b02c9..000000000 --- a/internal/storage/mysql/schema.go +++ /dev/null @@ -1,162 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - _ "embed" - "errors" - "fmt" - "regexp" - "strings" -) - -// ddl is the MySQL backend schema, embedded from schema.sql. It is the Dolt -// `SHOW CREATE TABLE` output at HEAD (all migrations applied) with the handful of -// Dolt-vs-MySQL-8 fixes required by stock MySQL: TEXT/JSON literal defaults → -// expression form `DEFAULT (”)`, the overlong `spec_id` index → a 191-char prefix -// (InnoDB's 3072-byte key cap), and the one-target CHECK constraints dropped (MySQL 8 -// forbids a column in both a CHECK and an FK cascade; issueops enforces the invariant -// in code). No data-plane translation is needed — bd's canonical SQL is MySQL. -// -//go:embed schema.sql -var ddl string - -const ( - schemaVersion = "1" - schemaVersionKey = "mysql_schema_version" -) - -// identRe restricts a database name to a plain identifier so it can be safely -// interpolated into CREATE DATABASE (which cannot take a placeholder). -var identRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) - -// InitSchema creates the workspace database if absent (via a server connection with -// no default database), applies the DDL to it, seeds the default config rows on first -// provision, and stamps the schema version. baseDSN is the server DSN; database is the -// per-workspace database (MySQL's unit of isolation, analogous to a Postgres schema). -func InitSchema(ctx context.Context, baseDSN, database string) error { - if !identRe.MatchString(database) { - return fmt.Errorf("mysql: invalid database name %q", database) - } - serverDSN, err := withDatabase(baseDSN, "") - if err != nil { - return fmt.Errorf("mysql: parse DSN: %w", err) - } - srv, err := sql.Open("mysql", serverDSN) - if err != nil { - return fmt.Errorf("mysql: open server: %w", err) - } - if _, err := srv.ExecContext(ctx, "CREATE DATABASE IF NOT EXISTS `"+database+"` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin"); err != nil { - _ = srv.Close() - return fmt.Errorf("mysql: create database %q: %w", database, err) - } - _ = srv.Close() - - wsDSN, err := withDatabase(baseDSN, database) - if err != nil { - return fmt.Errorf("mysql: parse DSN: %w", err) - } - db, err := sql.Open("mysql", wsDSN) - if err != nil { - return fmt.Errorf("mysql: open workspace db: %w", err) - } - defer db.Close() - for _, stmt := range splitStatements(ddl) { - if _, err := db.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("mysql: exec DDL statement: %w\n-- statement:\n%s", err, stmt) - } - } - fresh, err := stampSchemaVersion(ctx, db) - if err != nil { - return err - } - if fresh { - if err := seedDefaultConfig(ctx, db); err != nil { - return err - } - } - return nil -} - -// defaultConfigSeeds mirrors migration 0016 exactly — the config rows a fresh Dolt -// workspace materializes on init. Seeded only on first provision (like the one-shot -// migration), so a `config unset` is never resurrected on the next open. -var defaultConfigSeeds = [][2]string{ - {"compaction_enabled", "false"}, - {"compact_tier1_days", "30"}, - {"compact_tier1_dep_levels", "2"}, - {"compact_tier2_days", "90"}, - {"compact_tier2_dep_levels", "5"}, - {"compact_tier2_commits", "100"}, - {"compact_batch_size", "50"}, - {"compact_parallel_workers", "5"}, - {"auto_compact_enabled", "false"}, -} - -func seedDefaultConfig(ctx context.Context, db *sql.DB) error { - for _, kv := range defaultConfigSeeds { - if _, err := db.ExecContext(ctx, - "INSERT IGNORE INTO config (`key`, `value`) VALUES (?, ?)", kv[0], kv[1]); err != nil { - return fmt.Errorf("mysql: seed default config %q: %w", kv[0], err) - } - } - return nil -} - -// stampSchemaVersion records schemaVersion in the metadata table on first provision -// and refuses to open a workspace written by a binary with a different schema version -// (the proof-wedge has no migrator). Returns fresh=true only on the first stamp. -func stampSchemaVersion(ctx context.Context, db *sql.DB) (fresh bool, err error) { - var stored string - err = db.QueryRowContext(ctx, "SELECT `value` FROM metadata WHERE `key` = ?", schemaVersionKey).Scan(&stored) - switch { - case errors.Is(err, sql.ErrNoRows): - // Provision runs on every open; concurrent first opens of the same - // workspace database can both reach here. INSERT IGNORE lets both - // succeed; only the opener that inserted the row (RowsAffected==1) is - // fresh and seeds defaults (seedDefaultConfig is already INSERT IGNORE). - res, ierr := db.ExecContext(ctx, "INSERT IGNORE INTO metadata (`key`, `value`) VALUES (?, ?)", schemaVersionKey, schemaVersion) - if ierr != nil { - return false, fmt.Errorf("mysql: stamp schema version: %w", ierr) - } - if n, _ := res.RowsAffected(); n == 1 { - return true, nil - } - // Lost the race: re-read what the winner stored and version-check it. - if rerr := db.QueryRowContext(ctx, "SELECT `value` FROM metadata WHERE `key` = ?", schemaVersionKey).Scan(&stored); rerr != nil { - return false, fmt.Errorf("mysql: read schema version after conflict: %w", rerr) - } - if stored != schemaVersion { - return false, fmt.Errorf("mysql: workspace schema version %s, this binary requires %s — no migrator in the proof-wedge, recreate the workspace or use a matching binary", stored, schemaVersion) - } - return false, nil - case err != nil: - return false, fmt.Errorf("mysql: read schema version: %w", err) - case stored != schemaVersion: - return false, fmt.Errorf("mysql: workspace schema version %s, this binary requires %s — no migrator in the proof-wedge, recreate the workspace or use a matching binary", stored, schemaVersion) - default: - return false, nil - } -} - -// splitStatements splits the DDL on ';' at statement boundaries. The MySQL schema has -// no procedural bodies (triggers/procedures) or embedded ';' — the CHECK constraints -// that would complicate this were removed — so a plain split suffices. Blank fragments -// (and SQL line comments) are dropped. -func splitStatements(ddl string) []string { - var stmts []string - for _, raw := range strings.Split(ddl, ";") { - var b strings.Builder - for _, line := range strings.Split(raw, "\n") { - if strings.HasPrefix(strings.TrimSpace(line), "--") { - continue - } - b.WriteString(line) - b.WriteString("\n") - } - if s := strings.TrimSpace(b.String()); s != "" { - stmts = append(stmts, s) - } - } - return stmts -} diff --git a/internal/storage/mysql/schema.sql b/internal/storage/mysql/schema.sql deleted file mode 100644 index 4d6dc6537..000000000 --- a/internal/storage/mysql/schema.sql +++ /dev/null @@ -1,344 +0,0 @@ -CREATE TABLE IF NOT EXISTS `issues` ( - `id` varchar(255) NOT NULL, - `content_hash` varchar(64), - `title` varchar(500) NOT NULL, - `description` longtext NOT NULL, - `design` longtext NOT NULL, - `acceptance_criteria` longtext NOT NULL, - `notes` longtext NOT NULL, - `status` varchar(32) NOT NULL DEFAULT 'open', - `priority` int NOT NULL DEFAULT '2', - `issue_type` varchar(32) NOT NULL DEFAULT 'task', - `assignee` varchar(255), - `estimated_minutes` int, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) DEFAULT '', - `owner` varchar(255) DEFAULT '', - `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `closed_at` datetime, - `closed_by_session` varchar(255) DEFAULT '', - `external_ref` varchar(255), - `spec_id` varchar(1024), - `compaction_level` int DEFAULT '0', - `compacted_at` datetime, - `compacted_at_commit` varchar(64), - `original_size` int, - `sender` varchar(255) DEFAULT '', - `ephemeral` tinyint(1) DEFAULT '0', - `wisp_type` varchar(32) DEFAULT '', - `pinned` tinyint(1) DEFAULT '0', - `is_template` tinyint(1) DEFAULT '0', - `mol_type` varchar(32) DEFAULT '', - `work_type` varchar(32) DEFAULT 'mutex', - `source_system` varchar(255) DEFAULT '', - `metadata` json DEFAULT (json_object()), - `source_repo` varchar(512) DEFAULT '', - `close_reason` longtext DEFAULT (''), - `event_kind` varchar(32) DEFAULT '', - `actor` varchar(255) DEFAULT '', - `target` varchar(255) DEFAULT '', - `payload` text DEFAULT (''), - `await_type` varchar(32) DEFAULT '', - `await_id` varchar(255) DEFAULT '', - `timeout_ns` bigint DEFAULT '0', - `waiters` text DEFAULT (''), - `hook_bead` varchar(255) DEFAULT '', - `role_bead` varchar(255) DEFAULT '', - `agent_state` varchar(32) DEFAULT '', - `last_activity` datetime, - `role_type` varchar(32) DEFAULT '', - `rig` varchar(255) DEFAULT '', - `due_at` datetime, - `defer_until` datetime, - `no_history` tinyint(1) DEFAULT '0', - `started_at` datetime, - `is_blocked` tinyint(1) NOT NULL DEFAULT '0', - `row_lock` bigint NOT NULL DEFAULT 0, - PRIMARY KEY (`id`), - KEY `idx_issues_assignee` (`assignee`), - KEY `idx_issues_created_at` (`created_at`), - KEY `idx_issues_defer_until` (`defer_until`), - KEY `idx_issues_external_ref` (`external_ref`), - KEY `idx_issues_is_blocked` (`is_blocked`,`status`), - KEY `idx_issues_issue_type` (`issue_type`), - KEY `idx_issues_priority` (`priority`), - KEY `idx_issues_spec_id` (`spec_id`(191)), - KEY `idx_issues_status_updated_at` (`status`,`updated_at`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - --- Ephemeral claim leases (bd-lrgn1): node-local, never exported by backup. --- One row per live claim. See issueops.UpsertLeaseInTx for the invariant. -CREATE TABLE IF NOT EXISTS `leases` ( - `issue_id` varchar(255) NOT NULL, - `holder` varchar(255) NOT NULL, - `granted_at` datetime NOT NULL, - `lease_expires_at` datetime NOT NULL, - `heartbeat_at` datetime NOT NULL, - PRIMARY KEY (`issue_id`), - KEY `idx_leases_expires` (`lease_expires_at`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `wisps` ( - `id` varchar(255) NOT NULL, - `content_hash` varchar(64), - `title` varchar(500) NOT NULL, - `description` longtext NOT NULL DEFAULT (''), - `design` longtext NOT NULL DEFAULT (''), - `acceptance_criteria` longtext NOT NULL DEFAULT (''), - `notes` longtext NOT NULL DEFAULT (''), - `status` varchar(32) NOT NULL DEFAULT 'open', - `priority` int NOT NULL DEFAULT '2', - `issue_type` varchar(32) NOT NULL DEFAULT 'task', - `assignee` varchar(255), - `estimated_minutes` int, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) DEFAULT '', - `owner` varchar(255) DEFAULT '', - `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, - `closed_at` datetime, - `closed_by_session` varchar(255) DEFAULT '', - `external_ref` varchar(255), - `spec_id` varchar(1024), - `compaction_level` int DEFAULT '0', - `compacted_at` datetime, - `compacted_at_commit` varchar(64), - `original_size` int, - `sender` varchar(255) DEFAULT '', - `ephemeral` tinyint(1) DEFAULT '0', - `wisp_type` varchar(32) DEFAULT '', - `pinned` tinyint(1) DEFAULT '0', - `is_template` tinyint(1) DEFAULT '0', - `mol_type` varchar(32) DEFAULT '', - `work_type` varchar(32) DEFAULT 'mutex', - `source_system` varchar(255) DEFAULT '', - `metadata` json DEFAULT (json_object()), - `source_repo` varchar(512) DEFAULT '', - `close_reason` longtext DEFAULT (''), - `event_kind` varchar(32) DEFAULT '', - `actor` varchar(255) DEFAULT '', - `target` varchar(255) DEFAULT '', - `payload` text DEFAULT (''), - `await_type` varchar(32) DEFAULT '', - `await_id` varchar(255) DEFAULT '', - `timeout_ns` bigint DEFAULT '0', - `waiters` text DEFAULT (''), - `hook_bead` varchar(255) DEFAULT '', - `role_bead` varchar(255) DEFAULT '', - `agent_state` varchar(32) DEFAULT '', - `last_activity` datetime, - `role_type` varchar(32) DEFAULT '', - `rig` varchar(255) DEFAULT '', - `due_at` datetime, - `defer_until` datetime, - `no_history` tinyint(1) DEFAULT '0', - `started_at` datetime, - `is_blocked` tinyint(1) NOT NULL DEFAULT '0', - `row_lock` bigint NOT NULL DEFAULT 0, - PRIMARY KEY (`id`), - KEY `idx_wisps_assignee` (`assignee`), - KEY `idx_wisps_created_at` (`created_at`), - KEY `idx_wisps_external_ref` (`external_ref`), - KEY `idx_wisps_is_blocked` (`is_blocked`,`status`), - KEY `idx_wisps_issue_type` (`issue_type`), - KEY `idx_wisps_priority` (`priority`), - KEY `idx_wisps_spec_id` (`spec_id`(191)), - KEY `idx_wisps_status` (`status`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `labels` ( - `issue_id` varchar(255) NOT NULL, - `label` varchar(255) NOT NULL, - PRIMARY KEY (`issue_id`,`label`), - KEY `idx_labels_label` (`label`), - CONSTRAINT `fk_labels_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `wisp_labels` ( - `issue_id` varchar(255) NOT NULL, - `label` varchar(255) NOT NULL, - PRIMARY KEY (`issue_id`,`label`), - KEY `idx_wisp_labels_label` (`label`), - CONSTRAINT `fk_wisp_labels_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `dependencies` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `type` varchar(32) NOT NULL DEFAULT 'blocks', - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) NOT NULL, - `metadata` json DEFAULT (json_object()), - `thread_id` varchar(255) DEFAULT '', - `depends_on_issue_id` varchar(255), - `depends_on_wisp_id` varchar(255), - `depends_on_external` varchar(255), - PRIMARY KEY (`id`), - KEY `idx_dep_external_target` (`depends_on_external`), - KEY `idx_dep_issue_target` (`depends_on_issue_id`), - KEY `idx_dep_type_external` (`type`,`depends_on_external`), - KEY `idx_dep_type_issue` (`type`,`depends_on_issue_id`), - KEY `idx_dep_type_wisp` (`type`,`depends_on_wisp_id`), - KEY `idx_dep_wisp_target` (`depends_on_wisp_id`), - KEY `idx_dependencies_issue` (`issue_id`), - KEY `idx_dependencies_thread` (`thread_id`), - UNIQUE KEY `uk_dep_external_target` (`issue_id`,`depends_on_external`), - UNIQUE KEY `uk_dep_issue_target` (`issue_id`,`depends_on_issue_id`), - UNIQUE KEY `uk_dep_wisp_target` (`issue_id`,`depends_on_wisp_id`), - CONSTRAINT `fk_dep_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_dep_issue_target` FOREIGN KEY (`depends_on_issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `wisp_dependencies` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `depends_on_issue_id` varchar(255), - `depends_on_wisp_id` varchar(255), - `depends_on_external` varchar(255), - `type` varchar(32) NOT NULL DEFAULT 'blocks', - `created_at` datetime DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) DEFAULT '', - `metadata` json DEFAULT (json_object()), - `thread_id` varchar(255) DEFAULT '', - PRIMARY KEY (`id`), - KEY `fk_wisp_dep_issue_target` (`depends_on_issue_id`), - KEY `fk_wisp_dep_wisp_target` (`depends_on_wisp_id`), - KEY `idx_wisp_dep_type` (`type`), - KEY `idx_wisp_dep_type_external` (`type`,`depends_on_external`), - KEY `idx_wisp_dep_type_issue` (`type`,`depends_on_issue_id`), - KEY `idx_wisp_dep_type_wisp` (`type`,`depends_on_wisp_id`), - UNIQUE KEY `uk_wisp_dep_external_target` (`issue_id`,`depends_on_external`), - UNIQUE KEY `uk_wisp_dep_issue_target` (`issue_id`,`depends_on_issue_id`), - UNIQUE KEY `uk_wisp_dep_wisp_target` (`issue_id`,`depends_on_wisp_id`), - CONSTRAINT `fk_wisp_dep_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_wisp_dep_issue_target` FOREIGN KEY (`depends_on_issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_wisp_dep_wisp_target` FOREIGN KEY (`depends_on_wisp_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `comments` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `author` varchar(255) NOT NULL, - `text` longtext NOT NULL, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `idx_comments_created_at` (`created_at`), - KEY `idx_comments_issue` (`issue_id`), - CONSTRAINT `fk_comments_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `wisp_comments` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `author` varchar(255) DEFAULT '', - `text` text NOT NULL, - `created_at` datetime DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `idx_wisp_comments_issue` (`issue_id`), - CONSTRAINT `fk_wisp_comments_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `events` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `event_type` varchar(32) NOT NULL, - `actor` varchar(255) NOT NULL, - `old_value` longtext, - `new_value` longtext, - `comment` text, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `idx_events_created_at` (`created_at`), - KEY `idx_events_issue` (`issue_id`), - CONSTRAINT `fk_events_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `wisp_events` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `event_type` varchar(32) NOT NULL, - `actor` varchar(255) DEFAULT '', - `old_value` longtext DEFAULT (''), - `new_value` longtext DEFAULT (''), - `comment` text DEFAULT (''), - `created_at` datetime DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - KEY `idx_wisp_events_created_at` (`created_at`), - KEY `idx_wisp_events_issue` (`issue_id`), - CONSTRAINT `fk_wisp_events_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `config` ( - `key` varchar(255) NOT NULL, - `value` text NOT NULL, - PRIMARY KEY (`key`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `metadata` ( - `key` varchar(255) NOT NULL, - `value` text NOT NULL, - PRIMARY KEY (`key`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `local_metadata` ( - `key` varchar(255) NOT NULL, - `value` text NOT NULL DEFAULT (''), - PRIMARY KEY (`key`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `issue_counter` ( - `prefix` varchar(255) NOT NULL, - `last_id` int NOT NULL DEFAULT '0', - PRIMARY KEY (`prefix`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `child_counters` ( - `parent_id` varchar(255) NOT NULL, - `last_child` int NOT NULL DEFAULT '0', - PRIMARY KEY (`parent_id`), - CONSTRAINT `fk_counter_parent` FOREIGN KEY (`parent_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `wisp_child_counters` ( - `parent_id` varchar(255) NOT NULL, - `last_child` int NOT NULL DEFAULT '0', - PRIMARY KEY (`parent_id`), - CONSTRAINT `fk_wisp_child_counters_parent` FOREIGN KEY (`parent_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `custom_statuses` ( - `name` varchar(64) NOT NULL, - `category` varchar(32) NOT NULL DEFAULT 'unspecified', - PRIMARY KEY (`name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `custom_types` ( - `name` varchar(64) NOT NULL, - PRIMARY KEY (`name`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; - - -CREATE TABLE IF NOT EXISTS `repo_mtimes` ( - `repo_path` varchar(512) NOT NULL, - `jsonl_path` varchar(512) NOT NULL, - `mtime_ns` bigint NOT NULL, - `last_checked` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`repo_path`), - KEY `idx_repo_mtimes_checked` (`last_checked`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_bin; diff --git a/internal/storage/mysql/seed_test.go b/internal/storage/mysql/seed_test.go deleted file mode 100644 index 6a6f8353b..000000000 --- a/internal/storage/mysql/seed_test.go +++ /dev/null @@ -1,54 +0,0 @@ -package mysql - -import ( - "context" - "database/sql" - "fmt" - "os" - "testing" - "time" -) - -// TestSeedOnlyOnFirstProvision guards the same regression the Postgres backend has: -// InitSchema runs on every open, so seeding default config unconditionally would -// resurrect a key the user `config unset`. Seeding must be gated on first provision. -func TestSeedOnlyOnFirstProvision(t *testing.T) { - url := os.Getenv("BEADS_MYSQL_TEST_URL") - if url == "" { - t.Skip("BEADS_MYSQL_TEST_URL not set") - } - database := fmt.Sprintf("seedonce_%d", time.Now().UnixNano()) - ctx := context.Background() - t.Cleanup(func() { - if serverDSN, e := withDatabase(url, ""); e == nil { - if srv, e2 := sql.Open("mysql", serverDSN); e2 == nil { - _, _ = srv.ExecContext(context.Background(), "DROP DATABASE IF EXISTS `"+database+"`") - _ = srv.Close() - } - } - }) - - st, err := Provision(ctx, url, database) - if err != nil { - t.Fatalf("Provision: %v", err) - } - if v, _ := st.GetConfig(ctx, "auto_compact_enabled"); v != "false" { - t.Fatalf("first provision: want seeded auto_compact_enabled=false, got %q", v) - } - if err := st.DeleteConfig(ctx, "auto_compact_enabled"); err != nil { - t.Fatalf("DeleteConfig: %v", err) - } - if v, _ := st.GetConfig(ctx, "auto_compact_enabled"); v != "" { - t.Fatalf("after unset: want empty, got %q", v) - } - _ = st.Close() - - st2, err := Provision(ctx, url, database) - if err != nil { - t.Fatalf("re-Provision: %v", err) - } - defer st2.Close() - if v, _ := st2.GetConfig(ctx, "auto_compact_enabled"); v != "" { - t.Fatalf("REGRESSION: re-provision resurrected an unset key: auto_compact_enabled=%q (want empty)", v) - } -} diff --git a/internal/storage/mysql/store.go b/internal/storage/mysql/store.go deleted file mode 100644 index 14cd7d325..000000000 --- a/internal/storage/mysql/store.go +++ /dev/null @@ -1,69 +0,0 @@ -// Package mysql is the MySQL backend for bd: the shared sqlkit.Store bundled with -// the identity MySQL dialect and a no-op readiness strategy, plus the non-Dolt -// markers. bd's canonical SQL is MySQL-dialect, so unlike Postgres there is no -// translating driver — the only backend-specific work is a curated MySQL-8 schema -// (Dolt is more permissive than stock MySQL 8 at the DDL level). -package mysql - -import ( - "context" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/sqlkit" -) - -// Backend is the metadata.json backend identifier for this store. -const Backend = "mysql" - -// Store is the MySQL backend. It embeds *sqlkit.Store (inheriting every core method) -// and the generated typed-unsupported shell for the non-core surface. -type Store struct { - *sqlkit.Store - unsupportedDoltStorage -} - -// Compile-time guard on the generated skip list: the composite backend (real -// *sqlkit.Store methods plus the typed-unsupported shell) must fully satisfy -// storage.DoltStorage. This fails the build on skip-list drift — a skipped -// method sqlkit does not actually implement (missing method), or a method both -// implemented and stubbed (ambiguous selector) — so no method can silently -// become "unsupported". -var _ storage.DoltStorage = (*Store)(nil) - -// Config configures a MySQL backend. DSN targets the per-workspace database; the -// password is merged from env at open and never persisted to metadata.json. -type Config struct { - DSN string -} - -// New builds the MySQL backend from its strategy bundle: the identity mysql dialect -// and a no-op readiness strategy (issueops already maintains is_blocked in-tx, exactly -// like the Dolt reference). -func New(ctx context.Context, cfg Config) (*Store, error) { - base, err := sqlkit.New(ctx, sqlkit.Config{ - Dialect: mysqlDialect{dsn: cfg.DSN}, - Readiness: sqlkit.NoopReadiness{}, - }) - if err != nil { - return nil, err - } - return &Store{Store: base}, nil -} - -// CommitGraphUnsupported tells cmd/bd's PostRun to skip Dolt-only maintenance. -func (s *Store) CommitGraphUnsupported() bool { return true } - -// CommitPending is a no-op on a non-version-controlled backend. -func (s *Store) CommitPending(_ context.Context, _ string) (bool, error) { return false, nil } - -// Commit and its variants are no-ops on MySQL, not unsupported: every sqlkit write -// already committed its own SQL transaction, so the data is durable. Command paths -// call store.Commit() opportunistically; returning nil lets those writes stand. -func (s *Store) Commit(_ context.Context, _ string) error { return nil } -func (s *Store) CommitWithConfig(_ context.Context, _ string) error { return nil } -func (s *Store) CommitMergeResolution(_ context.Context, _ string) error { return nil } - -var ( - _ storage.DoltStorage = (*Store)(nil) - _ storage.NonCommitGraphBackend = (*Store)(nil) -) diff --git a/internal/storage/mysql/unsupported.go b/internal/storage/mysql/unsupported.go deleted file mode 100644 index 6fe9487c0..000000000 --- a/internal/storage/mysql/unsupported.go +++ /dev/null @@ -1,17 +0,0 @@ -package mysql - -import ( - "github.com/steveyegge/beads/internal/storage" -) - -// Regeneration mirrors postgres: the mysql shell is the exact complement of -// *sqlkit.Store's method set (identical base + identical Commit/CommitGraph overrides, -// so the complement is identical to postgres's shell modulo package name). -// -//go:generate go run ../unsupportedgen -pkg mysql -src .. -out unsupported_gen.go -type DoltStorage -skip AddDependency,AddIssueComment,AddLabel,ClaimIssue,ClaimReadyIssue,Close,CloseIssue,Commit,CommitMergeResolution,CommitPending,CommitWithConfig,CountDependencies,CountDependents,CountEvents,CountIssueComments,CountIssues,CountIssuesByGroup,CreateIssue,CreateIssues,DeleteConfig,DeleteIssue,DeleteIssues,DetectCycles,GetAllConfig,GetBlockedIssues,GetBlockingInfoForIssues,GetCommentCounts,GetCommentsForIssues,GetConfig,GetCustomStatuses,GetCustomStatusesDetailed,GetCustomTypes,GetDependencies,GetDependenciesWithMetadata,GetDependencyCounts,GetDependencyRecords,GetDependencyRecordsForIssues,GetDependencyTree,GetDependents,GetDependentsWithMetadata,GetEpicsEligibleForClosure,GetEvents,GetInfraTypes,GetIssue,GetIssueByExternalRef,GetIssueComments,GetIssuesByIDs,GetIssuesByLabel,GetLabels,GetLabelsForIssues,GetLocalMetadata,GetMetadata,GetNewlyUnblockedByClose,GetNextChildID,GetReadyWork,GetReadyWorkWithCounts,GetStaleIssues,GetStatistics,IsBlocked,IsInfraTypeCtx,IterBlockedIssues,IterDependenciesWithMetadata,IterDependentsWithMetadata,IterEvents,IterIssueComments,IterIssues,IterReadyWork,IterWisps,ListWisps,RemoveDependency,RemoveLabel,ReopenIssue,RunInTransaction,SearchIssues,SearchIssuesWithCounts,SetConfig,SetLocalMetadata,SetMetadata,UpdateIssue,UpdateIssueType,AddComment,ClearRepoMtime,CountDependentsByStatus,DeleteIssuesBySourceRepo,FindWispDependentsRecursive,GetAllDependencyRecords,GetAllEventsSince,GetMoleculeLastActivity,GetMoleculeProgress,GetRepoMtime,ImportIssueComment,IterAllDependencyRecords,IterAllEventsSince,PromoteFromEphemeral,SetRepoMtime,UpdateIssueID,CreateIssuesWithFullOptions,SlotClear,SlotGet,SlotSet,SearchIssueIDs,HeartbeatIssue,ReclaimExpiredLeases,UnclaimIssue - -// errUnsupported is the constructor every generated stub in unsupported_gen.go calls. -// It returns the backend-agnostic *storage.ErrUnsupported sentinel; Backend is "mysql". -func errUnsupported(op string) error { - return &storage.ErrUnsupported{Op: op, Backend: Backend} -} diff --git a/internal/storage/mysql/unsupported_gen.go b/internal/storage/mysql/unsupported_gen.go deleted file mode 100644 index 823cc4b8e..000000000 --- a/internal/storage/mysql/unsupported_gen.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by gen (mysql typed-unsupported shell); DO NOT EDIT. - -package mysql - -import ( - "context" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/types" -) - -// unsupportedDoltStorage is the generated typed-unsupported shell for storage.DoltStorage. -// Every method returns *storage.ErrUnsupported; embed it and override the -// real slice. DO NOT hand-edit — regenerate with `go generate ./...`. -type unsupportedDoltStorage struct{} - -func (unsupportedDoltStorage) MergeSlotCreate(_ context.Context, _ string) (_ *types.Issue, err error) { - err = errUnsupported("MergeSlotCreate") - return -} - -func (unsupportedDoltStorage) MergeSlotCheck(_ context.Context) (_ *storage.MergeSlotStatus, err error) { - err = errUnsupported("MergeSlotCheck") - return -} - -func (unsupportedDoltStorage) MergeSlotAcquire(_ context.Context, _ string, _ string, _ bool) (_ *storage.MergeSlotResult, err error) { - err = errUnsupported("MergeSlotAcquire") - return -} - -func (unsupportedDoltStorage) MergeSlotRelease(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("MergeSlotRelease") - return -} - -func (unsupportedDoltStorage) Branch(_ context.Context, _ string) (err error) { - err = errUnsupported("Branch") - return -} - -func (unsupportedDoltStorage) Checkout(_ context.Context, _ string) (err error) { - err = errUnsupported("Checkout") - return -} - -func (unsupportedDoltStorage) CurrentBranch(_ context.Context) (_ string, err error) { - err = errUnsupported("CurrentBranch") - return -} - -func (unsupportedDoltStorage) DeleteBranch(_ context.Context, _ string) (err error) { - err = errUnsupported("DeleteBranch") - return -} - -func (unsupportedDoltStorage) ListBranches(_ context.Context) (_ []string, err error) { - err = errUnsupported("ListBranches") - return -} - -func (unsupportedDoltStorage) CommitExists(_ context.Context, _ string) (_ bool, err error) { - err = errUnsupported("CommitExists") - return -} - -func (unsupportedDoltStorage) GetCurrentCommit(_ context.Context) (_ string, err error) { - err = errUnsupported("GetCurrentCommit") - return -} - -func (unsupportedDoltStorage) Status(_ context.Context) (_ *storage.Status, err error) { - err = errUnsupported("Status") - return -} - -func (unsupportedDoltStorage) Log(_ context.Context, _ int) (_ []storage.CommitInfo, err error) { - err = errUnsupported("Log") - return -} - -func (unsupportedDoltStorage) Merge(_ context.Context, _ string) (_ []storage.Conflict, err error) { - err = errUnsupported("Merge") - return -} - -func (unsupportedDoltStorage) GetConflicts(_ context.Context) (_ []storage.Conflict, err error) { - err = errUnsupported("GetConflicts") - return -} - -func (unsupportedDoltStorage) ResolveConflicts(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("ResolveConflicts") - return -} - -func (unsupportedDoltStorage) History(_ context.Context, _ string) (_ []*storage.HistoryEntry, err error) { - err = errUnsupported("History") - return -} - -func (unsupportedDoltStorage) AsOf(_ context.Context, _ string, _ string) (_ *types.Issue, err error) { - err = errUnsupported("AsOf") - return -} - -func (unsupportedDoltStorage) Diff(_ context.Context, _ string, _ string) (_ []*storage.DiffEntry, err error) { - err = errUnsupported("Diff") - return -} - -func (unsupportedDoltStorage) AddRemote(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("AddRemote") - return -} - -func (unsupportedDoltStorage) RemoveRemote(_ context.Context, _ string) (err error) { - err = errUnsupported("RemoveRemote") - return -} - -func (unsupportedDoltStorage) HasRemote(_ context.Context, _ string) (_ bool, err error) { - err = errUnsupported("HasRemote") - return -} - -func (unsupportedDoltStorage) ListRemotes(_ context.Context) (_ []storage.RemoteInfo, err error) { - err = errUnsupported("ListRemotes") - return -} - -func (unsupportedDoltStorage) Push(_ context.Context) (err error) { - err = errUnsupported("Push") - return -} - -func (unsupportedDoltStorage) Pull(_ context.Context) (err error) { - err = errUnsupported("Pull") - return -} - -func (unsupportedDoltStorage) ForcePush(_ context.Context) (err error) { - err = errUnsupported("ForcePush") - return -} - -func (unsupportedDoltStorage) PushRemote(_ context.Context, _ string, _ bool) (err error) { - err = errUnsupported("PushRemote") - return -} - -func (unsupportedDoltStorage) PullRemote(_ context.Context, _ string) (err error) { - err = errUnsupported("PullRemote") - return -} - -func (unsupportedDoltStorage) Fetch(_ context.Context, _ string) (err error) { - err = errUnsupported("Fetch") - return -} - -func (unsupportedDoltStorage) PushTo(_ context.Context, _ string) (err error) { - err = errUnsupported("PushTo") - return -} - -func (unsupportedDoltStorage) PullFrom(_ context.Context, _ string) (_ []storage.Conflict, err error) { - err = errUnsupported("PullFrom") - return -} - -func (unsupportedDoltStorage) Sync(_ context.Context, _ string, _ string) (_ *storage.SyncResult, err error) { - err = errUnsupported("Sync") - return -} - -func (unsupportedDoltStorage) SyncStatus(_ context.Context, _ string) (_ *storage.SyncStatus, err error) { - err = errUnsupported("SyncStatus") - return -} - -func (unsupportedDoltStorage) AddFederationPeer(_ context.Context, _ *storage.FederationPeer) (err error) { - err = errUnsupported("AddFederationPeer") - return -} - -func (unsupportedDoltStorage) GetFederationPeer(_ context.Context, _ string) (_ *storage.FederationPeer, err error) { - err = errUnsupported("GetFederationPeer") - return -} - -func (unsupportedDoltStorage) ListFederationPeers(_ context.Context) (_ []*storage.FederationPeer, err error) { - err = errUnsupported("ListFederationPeers") - return -} - -func (unsupportedDoltStorage) RemoveFederationPeer(_ context.Context, _ string) (err error) { - err = errUnsupported("RemoveFederationPeer") - return -} - -func (unsupportedDoltStorage) CheckEligibility(_ context.Context, _ string, _ int) (_ bool, _ string, err error) { - err = errUnsupported("CheckEligibility") - return -} - -func (unsupportedDoltStorage) ApplyCompaction(_ context.Context, _ string, _ int, _ int, _ int, _ string) (err error) { - err = errUnsupported("ApplyCompaction") - return -} - -func (unsupportedDoltStorage) GetTier1Candidates(_ context.Context) (_ []*types.CompactionCandidate, err error) { - err = errUnsupported("GetTier1Candidates") - return -} - -func (unsupportedDoltStorage) GetTier2Candidates(_ context.Context) (_ []*types.CompactionCandidate, err error) { - err = errUnsupported("GetTier2Candidates") - return -} - -func (unsupportedDoltStorage) SnapshotIssue(_ context.Context, _ string, _ int) (err error) { - err = errUnsupported("SnapshotIssue") - return -} - -func (unsupportedDoltStorage) GetCompactionSnapshot(_ context.Context, _ string) (_ *types.IssueSnapshot, err error) { - err = errUnsupported("GetCompactionSnapshot") - return -} - -func (unsupportedDoltStorage) RestoreFromSnapshot(_ context.Context, _ string) (_ *types.IssueSnapshot, err error) { - err = errUnsupported("RestoreFromSnapshot") - return -} - -// NOTE: partial shell (104 methods skipped); the embedding composite must assert storage.DoltStorage itself. diff --git a/internal/storage/mysqldialect/credential.go b/internal/storage/mysqldialect/credential.go deleted file mode 100644 index 1a034233b..000000000 --- a/internal/storage/mysqldialect/credential.go +++ /dev/null @@ -1,83 +0,0 @@ -package mysqldialect - -import ( - "fmt" - "net" - "strconv" - - "github.com/go-sql-driver/mysql" -) - -// HasPassword reports whether the DSN already carries a password. A DSN that already -// has one (a full BEADS_MYSQL_URL, or an explicit --mysql-url) wins outright: the -// credential ladder is not applied on top of it. -func HasPassword(dsn string) bool { - cfg, err := mysql.ParseDSN(dsn) - return err == nil && cfg.Passwd != "" -} - -// WithCredential returns dsn with the resolved credential placed: the password -// always, and the username only when non-empty (a Vault-style dynamic user/password -// pair) — an empty username leaves the DSN's user untouched. It uses go-sql-driver's -// own parser (never string surgery) and VERIFIES the round-trip. -// -// The grammar has one sharp edge pgdialect does not: it cannot carry a password -// without a username (FormatDSN emits the user:pass@ block only when a user is -// present), so a userless result is refused. But a provided username satisfies that -// requirement, making a bare tcp(host)/ base DSN plus a dynamic user/password pair a -// valid configuration. This is the counterpart to mysql.RedactPassword. -func WithCredential(dsn, username, password string) (string, error) { - cfg, err := mysql.ParseDSN(dsn) - if err != nil { - return "", fmt.Errorf("cannot place credential into the connection string (unparseable DSN): %w", err) - } - if username != "" { - cfg.User = username - } - if cfg.User == "" { - return "", fmt.Errorf("cannot place a password: the DSN has no username, and the MySQL DSN grammar cannot carry a password without one; add a user to the DSN") - } - cfg.Passwd = password - out := cfg.FormatDSN() - - again, err := mysql.ParseDSN(out) - if err != nil { - return "", fmt.Errorf("cannot place credential into the connection string (unparseable result): %w", err) - } - if again.Passwd != password { - return "", fmt.Errorf("password did not round-trip into the connection string; refusing to connect with a wrong or empty password") - } - if username != "" && again.User != username { - return "", fmt.Errorf("username did not round-trip into the connection string; refusing to connect as the wrong user") - } - return out, nil -} - -// WithPassword places only the password, preserving the DSN's user. It is -// WithCredential with no username override. -func WithPassword(dsn, password string) (string, error) { - return WithCredential(dsn, "", password) -} - -// HostPort returns the TCP endpoint go-sql-driver would dial for dsn, for keying the -// [host:port] credentials-file lookup. ok=false for non-TCP networks (a unix socket -// has no port) or an unparseable DSN; the caller degrades the file rung to -// not-configured rather than failing. -func HostPort(dsn string) (host string, port int, ok bool) { - cfg, err := mysql.ParseDSN(dsn) - if err != nil { - return "", 0, false - } - if cfg.Net != "tcp" { - return "", 0, false - } - h, p, err := net.SplitHostPort(cfg.Addr) - if err != nil { - return "", 0, false - } - port, err = strconv.Atoi(p) - if err != nil { - return "", 0, false - } - return h, port, true -} diff --git a/internal/storage/mysqldialect/credential_extra_test.go b/internal/storage/mysqldialect/credential_extra_test.go deleted file mode 100644 index f43019e24..000000000 --- a/internal/storage/mysqldialect/credential_extra_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package mysqldialect - -import ( - "testing" - - "github.com/go-sql-driver/mysql" -) - -func mustUser(t *testing.T, out string) string { - t.Helper() - cfg, err := mysql.ParseDSN(out) - if err != nil { - t.Fatalf("mysql.ParseDSN(%q): %v", out, err) - } - return cfg.User -} - -func TestWithCredentialOverridesUser(t *testing.T) { - out, err := WithCredential("old@tcp(h:3306)/db", "vu", "pw") - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "vu" { - t.Fatalf("user = %q, want vu", u) - } - if pw := mustPassword(t, out); pw != "pw" { - t.Fatalf("password = %q, want pw", pw) - } -} - -func TestWithCredentialEmptyUsernameKeepsUser(t *testing.T) { - out, err := WithCredential("old@tcp(h:3306)/db", "", "pw") - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "old" { - t.Fatalf("user = %q, want old (preserved)", u) - } -} - -// A provided username satisfies the grammar's user requirement, making a userless base -// DSN plus a dynamic user/password pair valid. -func TestWithCredentialUsernameSatisfiesUserlessDSN(t *testing.T) { - out, err := WithCredential("tcp(h:3306)/db", "vu", "pw") - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "vu" { - t.Fatalf("user = %q, want vu", u) - } - if pw := mustPassword(t, out); pw != "pw" { - t.Fatalf("password = %q, want pw", pw) - } -} - -// Password-only against a userless DSN still fails (the guard is intact). -func TestWithCredentialUserlessStillFails(t *testing.T) { - if _, err := WithCredential("tcp(h:3306)/db", "", "pw"); err == nil { - t.Fatal("expected error: a userless DSN cannot carry a password without a username") - } -} - -func TestHostPort(t *testing.T) { - cases := []struct { - dsn string - host string - port int - ok bool - }{ - {"u@tcp(10.0.0.5:55441)/", "10.0.0.5", 55441, true}, - {"u@/", "127.0.0.1", 3306, true}, // tcp Addr defaults to 127.0.0.1:3306 - {"u@tcp(dbhost)/", "dbhost", 3306, true}, // ensureHavePort appends :3306 - {"u@unix(/tmp/mysql.sock)/", "", 0, false}, // non-tcp -> not ok - } - for _, c := range cases { - h, p, ok := HostPort(c.dsn) - if ok != c.ok || (ok && (h != c.host || p != c.port)) { - t.Errorf("HostPort(%q) = (%q,%d,%v), want (%q,%d,%v)", c.dsn, h, p, ok, c.host, c.port, c.ok) - } - } -} diff --git a/internal/storage/mysqldialect/credential_test.go b/internal/storage/mysqldialect/credential_test.go deleted file mode 100644 index 49ef6affd..000000000 --- a/internal/storage/mysqldialect/credential_test.go +++ /dev/null @@ -1,82 +0,0 @@ -package mysqldialect - -import ( - "testing" - - "github.com/go-sql-driver/mysql" -) - -func TestHasPassword(t *testing.T) { - cases := []struct { - dsn string - want bool - }{ - {"bts:secret@tcp(127.0.0.1:3306)/db", true}, - {"bts@tcp(127.0.0.1:3306)/db", false}, - {"bts@/", false}, // no-tcp form parses, no password - {"", false}, // empty parses to a default config - {"bts:pw@tcp(127.0.0.1:3306)", false}, // missing trailing slash -> parse error - } - for _, c := range cases { - if got := HasPassword(c.dsn); got != c.want { - t.Errorf("HasPassword(%q) = %v, want %v", c.dsn, got, c.want) - } - } -} - -// mustPassword parses out and returns the password go-sql-driver sees. -func mustPassword(t *testing.T, out string) string { - t.Helper() - cfg, err := mysql.ParseDSN(out) - if err != nil { - t.Fatalf("mysql.ParseDSN(%q): %v", out, err) - } - return cfg.Passwd -} - -func TestWithPasswordBasic(t *testing.T) { - out, err := WithPassword("bts@tcp(127.0.0.1:55441)/", "s3cr3t") - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != "s3cr3t" { - t.Fatalf("password = %q, want s3cr3t", pw) - } - cfg, _ := mysql.ParseDSN(out) - if cfg.User != "bts" { - t.Fatalf("user = %q, want bts (must be preserved)", cfg.User) - } -} - -// go-sql-driver writes the password verbatim; a token full of DSN-significant -// characters (as an RDS-IAM token carries) must round-trip byte-for-byte. -func TestWithPasswordSpecialChars(t *testing.T) { - for _, tok := range []string{"p@ss:w/rd?x=1&y=2", "X-Amz=abc&Sig=d/e+f%20", `a'b\c d`} { - out, err := WithPassword("bts@tcp(h:3306)/db", tok) - if err != nil { - t.Fatalf("token %q: %v", tok, err) - } - if pw := mustPassword(t, out); pw != tok { - t.Fatalf("password = %q, want %q", pw, tok) - } - } -} - -func TestWithPasswordReplacesExisting(t *testing.T) { - out, err := WithPassword("bts:old@tcp(h:3306)/db", "new") - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != "new" { - t.Fatalf("password = %q, want new", pw) - } -} - -// The MySQL sharp edge: a userless DSN cannot carry a password (FormatDSN drops it), -// so WithPassword must refuse rather than silently connect without one. -func TestWithPasswordUserlessDSNFails(t *testing.T) { - _, err := WithPassword("tcp(127.0.0.1:55441)/", "orphan") - if err == nil { - t.Fatal("expected an error for a userless DSN (password would be silently dropped)") - } -} diff --git a/internal/storage/mysqldialect/driver.go b/internal/storage/mysqldialect/driver.go deleted file mode 100644 index 2b9c286db..000000000 --- a/internal/storage/mysqldialect/driver.go +++ /dev/null @@ -1,91 +0,0 @@ -// Package mysqldialect is the MySQL backend's thin driver wrapper. bd's canonical SQL -// is MySQL, so unlike pgdialect there is no translation — the ONE rewrite is the -// self-referential is_blocked recompute UPDATE, which MySQL 8 rejects (error 1093: a -// table may not be updated while referenced in its own subquery) but Dolt and Postgres -// permit. The rewrite is isolated here, so the shared issueops/sqlkit layers and the -// Dolt/Postgres backends are entirely untouched. -// -// A portable, perf-reviewed rewrite in shared issueops is tracked as a backlog item; -// this wrapper is the per-backend containment chosen to avoid touching Dolt's hot path. -package mysqldialect - -import ( - "context" - "database/sql" - "database/sql/driver" - - "github.com/go-sql-driver/mysql" -) - -// Open returns a *sql.DB over go-sql-driver whose Prepare rewrites the recompute -// UPDATE (see rewriteSelfRefUpdate); every other statement passes through verbatim. -// Like pgdialect, the wrapper exposes no Execer/Queryer fast path, so database/sql -// routes every statement through Prepare — the one place the rewrite happens. -func Open(dsn string) (*sql.DB, error) { - base, err := (mysql.MySQLDriver{}).OpenConnector(dsn) - if err != nil { - return nil, err - } - return sql.OpenDB(&connector{base: base}), nil -} - -type connector struct{ base driver.Connector } - -func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { - cn, err := c.base.Connect(ctx) - if err != nil { - return nil, err - } - return &conn{base: cn}, nil -} - -func (c *connector) Driver() driver.Driver { return c.base.Driver() } - -// conn wraps the mysql driver.Conn and rewrites the recompute UPDATE at prepare time. -// It deliberately implements no Execer/Queryer so database/sql prepares every stmt. -type conn struct{ base driver.Conn } - -func (c *conn) Prepare(query string) (driver.Stmt, error) { - return c.base.Prepare(rewriteSelfRefUpdate(query)) -} - -func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - q := rewriteSelfRefUpdate(query) - if p, ok := c.base.(driver.ConnPrepareContext); ok { - return p.PrepareContext(ctx, q) - } - return c.base.Prepare(q) -} - -func (c *conn) Close() error { return c.base.Close() } - -//nolint:staticcheck // SA1019: driver.Conn requires the deprecated Begin; BeginTx forwarded below. -func (c *conn) Begin() (driver.Tx, error) { return c.base.Begin() } - -func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if b, ok := c.base.(driver.ConnBeginTx); ok { - return b.BeginTx(ctx, opts) - } - return c.base.Begin() //nolint:staticcheck -} - -func (c *conn) ResetSession(ctx context.Context) error { - if rs, ok := c.base.(driver.SessionResetter); ok { - return rs.ResetSession(ctx) - } - return nil -} - -func (c *conn) IsValid() bool { - if v, ok := c.base.(driver.Validator); ok { - return v.IsValid() - } - return true -} - -func (c *conn) Ping(ctx context.Context) error { - if p, ok := c.base.(driver.Pinger); ok { - return p.Ping(ctx) - } - return nil -} diff --git a/internal/storage/mysqldialect/rewrite.go b/internal/storage/mysqldialect/rewrite.go deleted file mode 100644 index 500bced7c..000000000 --- a/internal/storage/mysqldialect/rewrite.go +++ /dev/null @@ -1,43 +0,0 @@ -package mysqldialect - -import ( - "fmt" - "regexp" - "strings" -) - -// selfRefUpdateRe matches bd's is_blocked recompute shape: -// -// UPDATE
SET <...> WHERE .id IN () -// -// The SET is non-greedy up to the first WHERE (SET clauses contain no WHERE); the -// placeholder list is the batched `?,?,…`. -var selfRefUpdateRe = regexp.MustCompile(`(?is)^(\s*UPDATE\s+(\w+)\s+(\w+)\s+SET\s+.+?)\s+WHERE\s+(\w+)\.id\s+IN\s+\(([^)]*)\)\s*(.*)$`) - -// rewriteSelfRefUpdate rewrites the is_blocked recompute UPDATE into a MySQL-8-safe -// double-nested form so the target table's self-reference is materialized (avoiding -// error 1093). Everything else is returned verbatim. The transform is semantics- -// preserving: the id set (batch ∩ conditions) is computed in a materialized derived -// table, and the outer UPDATE writes exactly those rows. Positional placeholders keep -// their order because the WHERE body is moved intact. -func rewriteSelfRefUpdate(q string) string { - // Fast reject: only the is_blocked recompute both sets is_blocked and self-joins. - if !strings.Contains(q, "is_blocked") { - return q - } - m := selfRefUpdateRe.FindStringSubmatch(q) - if m == nil { - return q - } - head, table, alias, whereAlias, placeholders, rest := m[1], m[2], m[3], m[4], m[5], m[6] - // Only the recompute has further conditions after the IN clause (the self-ref - // EXISTS block); a plain `UPDATE … WHERE id IN (…)` needs no rewrite. - if whereAlias != alias || strings.TrimSpace(rest) == "" { - return q - } - // Rebind the outer alias to the derived-table alias inside the moved conditions. - reb := regexp.MustCompile(`\b` + regexp.QuoteMeta(alias) + `\.`) - restRebound := reb.ReplaceAllString(rest, "_b.") - return fmt.Sprintf("%s WHERE %s.id IN (SELECT id FROM (SELECT _b.id FROM %s _b WHERE _b.id IN (%s) %s) AS _blk)", - head, alias, table, placeholders, restRebound) -} diff --git a/internal/storage/mysqldialect/rewrite_test.go b/internal/storage/mysqldialect/rewrite_test.go deleted file mode 100644 index 3e6357f29..000000000 --- a/internal/storage/mysqldialect/rewrite_test.go +++ /dev/null @@ -1,123 +0,0 @@ -package mysqldialect - -import ( - "regexp" - "strings" - "testing" - - "github.com/steveyegge/beads/internal/storage/issueops" -) - -func TestRewriteSelfRefUpdate(t *testing.T) { - recompute := `UPDATE issues i SET i.is_blocked = 1, i.updated_at = i.updated_at - WHERE i.id IN (?,?,?) - AND i.is_blocked = 0 - AND i.status <> 'closed' AND i.status <> 'pinned' - AND (EXISTS (SELECT 1 FROM dependencies d JOIN issues t ON t.id = d.depends_on_issue_id - WHERE d.issue_id = i.id AND d.type = 'blocks' AND t.status <> 'closed'))` - - got := rewriteSelfRefUpdate(recompute) - if got == recompute { - t.Fatal("recompute UPDATE was not rewritten") - } - // The outer target must no longer be referenced directly in a subquery: the - // materialized derived table carries the self-reference. - if !strings.Contains(got, "SELECT id FROM (SELECT _b.id FROM issues _b") { - t.Fatalf("missing double-nested derived table:\n%s", got) - } - // The correlation must be rebound to the derived-table alias. - if !strings.Contains(got, "d.issue_id = _b.id") { - t.Fatalf("alias not rebound to _b:\n%s", got) - } - // The outer SET still targets the real alias. - if !strings.HasPrefix(strings.TrimSpace(got), "UPDATE issues i SET i.is_blocked = 1") { - t.Fatalf("outer UPDATE target changed:\n%s", got) - } - // Placeholder count preserved (positional binding). - if a, b := strings.Count(recompute, "?"), strings.Count(got, "?"); a != b { - t.Fatalf("placeholder count changed: %d -> %d", a, b) - } -} - -// TestRewriteMatchesRealRecomputeTemplates drives the rewrite from the ACTUAL -// issueops is_blocked recompute templates, not a hand-copied fixture. The rewrite -// regex is coupled to the exact shape those templates emit (UPDATE SET -// … WHERE .id IN (…) ); if a template later grows a predicate -// before `id IN`, backticks the table, renames the alias, or changes whitespace, the -// regex would silently stop matching and MySQL 8 would raise error 1093 at runtime on -// a core write path. That failure would otherwise only surface under the env-gated -// MySQL conformance suite — this non-gated test makes template drift fail `go test`. -func TestRewriteMatchesRealRecomputeTemplates(t *testing.T) { - templates := issueops.SelfReferentialRecomputeTemplates() - if len(templates) == 0 { - t.Fatal("issueops.SelfReferentialRecomputeTemplates() returned no templates") - } - // Parse the UPDATE target table+alias so the assertions can target the OUTER - // self-reference specifically (the inner materialized `_b.id IN (?…)` is expected). - updateHead := regexp.MustCompile(`(?is)^\s*UPDATE\s+(\w+)\s+(\w+)\s+SET\b`) - for i, tmpl := range templates { - m := updateHead.FindStringSubmatch(tmpl) - if m == nil { - t.Errorf("template[%d] is not an `UPDATE
SET …` shape:\n%s", i, tmpl) - continue - } - table, alias := m[1], m[2] - - got := rewriteSelfRefUpdate(tmpl) - if got == tmpl { - t.Errorf("template[%d] was NOT rewritten — the rewrite regex no longer matches an is_blocked "+ - "recompute template; MySQL error 1093 would return at runtime:\n%s", i, tmpl) - continue - } - // The target table must be materialized in a derived table so the outer UPDATE - // no longer references it directly in a subquery (the 1093 avoidance). - if want := "SELECT id FROM (SELECT _b.id FROM " + table + " _b"; !strings.Contains(got, want) { - t.Errorf("template[%d] rewrite missing the double-nested derived table %q:\n%s", i, want, got) - } - // The OUTER target alias must now select from the materialized set, not a bare - // self-referential `.id IN (?…)`. - outerMaterialized := regexp.MustCompile(`(?i)\b` + alias + `\.id\s+IN\s+\(\s*SELECT`) - if !outerMaterialized.MatchString(got) { - t.Errorf("template[%d] outer %s.id IN (…) was not materialized into a subselect:\n%s", i, alias, got) - } - outerRaw := regexp.MustCompile(`(?i)\b` + alias + `\.id\s+IN\s+\(\s*\?`) - if outerRaw.MatchString(got) { - t.Errorf("template[%d] outer %s.id IN (?…) is still a raw self-reference after rewrite (MySQL 1093):\n%s", i, alias, got) - } - // Positional binding is preserved (placeholders unchanged). - if a, b := strings.Count(tmpl, "?"), strings.Count(got, "?"); a != b { - t.Errorf("template[%d] placeholder count changed: %d -> %d", i, a, b) - } - } -} - -func TestRewritePassThrough(t *testing.T) { - cases := []string{ - "SELECT * FROM issues WHERE id = ?", - "UPDATE issues SET title = ? WHERE id = ?", // no is_blocked, no IN - "UPDATE issues i SET i.is_blocked = 1 WHERE i.id IN (?,?)", // batch update, no self-ref conditions - "INSERT INTO issues (id) VALUES (?)", - "DELETE FROM issues WHERE id = ?", - } - for _, q := range cases { - if got := rewriteSelfRefUpdate(q); got != q { - t.Errorf("query was rewritten but should pass through:\n in: %s\nout: %s", q, got) - } - } -} - -// The rewrite must not leave the outer target table referenced in a subquery in a way -// that regex could double-apply; a second pass is a no-op on already-rewritten SQL. -func TestRewriteIdempotentShape(t *testing.T) { - q := `UPDATE wisps w SET w.is_blocked = 0, w.updated_at = w.updated_at - WHERE w.id IN (?) AND w.is_blocked = 1 AND (w.status = 'closed')` - once := rewriteSelfRefUpdate(q) - if once == q { - t.Fatal("expected rewrite") - } - // A plain "?,?" derived form should still parse-shape sanely (no target alias left - // as a bare self-join outside the derived table). - if regexp.MustCompile(`WHERE w\.id IN \(\?`).MatchString(once) { - t.Fatalf("outer WHERE still has a raw placeholder IN (self-ref not materialized):\n%s", once) - } -} diff --git a/internal/storage/pgdialect/corpus_test.go b/internal/storage/pgdialect/corpus_test.go deleted file mode 100644 index 4e95c7d35..000000000 --- a/internal/storage/pgdialect/corpus_test.go +++ /dev/null @@ -1,430 +0,0 @@ -package pgdialect_test - -// This file is the PREPARE gate the package doc promises. It enumerates every -// distinct statement family bd's shared layer (sqlbuild + issueops) emits on -// the read/search path, runs each through pgdialect.Translate, and — when a -// live Postgres is configured via BEADS_PG_TEST_URL — PREPAREs the translated -// text against a scratch schema. An untranslatable construct fails the test -// loudly (Translate error, surviving MySQL residue, or a PREPARE-time Postgres -// error) instead of silently mistranslating a row set. -// -// It is an external test package (pgdialect_test) so it can live alongside the -// white-box translate_test.go while only touching pgdialect's exported surface. -// -// The scratch schema is built here rather than via postgres.InitSchema on -// purpose: pgdialect is a lower layer than the postgres backend (postgres -// imports pgdialect), so importing postgres into pgdialect's tests would invert -// the dependency and couple this gate to that package's build state. The tables -// are generated from sqlbuild.IssueSelectColumns so they cannot drift out of -// sync with the column list the queries project. Only the shapes the corpus -// exercises are created; types are faithful where an operator depends on them -// (jsonb metadata, integer priority, smallint flags, timestamp columns) and -// text elsewhere. - -import ( - "context" - "database/sql" - "fmt" - "os" - "strings" - "testing" - "time" - - "github.com/steveyegge/beads/internal/storage/pgdialect" - "github.com/steveyegge/beads/internal/storage/sqlbuild" - "github.com/steveyegge/beads/internal/types" -) - -type corpusStmt struct { - name string - sql string -} - -func strp(s string) *string { return &s } -func intp(i int) *int { return &i } - -// searchSelectSQL mirrors issueops.searchTableInTx Pattern A: the full-column -// filtered scan for one table family (incl. the label-driven JOIN plan). -func searchSelectSQL(tables sqlbuild.FilterTables, query string, filter types.IssueFilter) (string, error) { - plan := sqlbuild.BuildLabelDrivenSearch(filter, tables) - where, _, err := sqlbuild.BuildIssueFilterClauses(query, plan.Filter, tables) - if err != nil { - return "", err - } - where, _ = plan.MergeInto(where, nil) - whereSQL := "" - if len(where) > 0 { - whereSQL = "WHERE " + strings.Join(where, " AND ") - } - selectKw := "SELECT " - if plan.Distinct { - selectKw = "SELECT DISTINCT " - } - return fmt.Sprintf("%s%s FROM %s %s %s %s", - selectKw, sqlbuild.IssueSelectColumns, plan.FromSQL, sqlbuild.LeaseJoin(tables.Main), whereSQL, - sqlbuild.OrderBy(filter.SortBy, filter.SortDesc, "")), nil -} - -// searchCountsSQL mirrors issueops.runFilterSearchQueryInTx: the counts -// mega-query (the DATE_FORMAT / JSON_OBJECT / CAST / JSON_ARRAYAGG surface). -func searchCountsSQL(tables sqlbuild.FilterTables, query string, filter types.IssueFilter, includeWispReverseDeps bool) (string, error) { - where, _, err := sqlbuild.BuildIssueFilterClauses(query, filter, tables) - if err != nil { - return "", err - } - whereSQL := "" - if len(where) > 0 { - whereSQL = "WHERE " + strings.Join(where, " AND ") - } - sql, _ := sqlbuild.SearchCountsSQL(tables, nil, whereSQL, sqlbuild.OrderBy(filter.SortBy, filter.SortDesc, "i"), "", includeWispReverseDeps, filter.SkipLabels) - return sql, nil -} - -// readySelectSQL mirrors issueops.GetReadyWorkInTx: SELECT id FROM
with -// the ready-work WHERE/ORDER. -func readySelectSQL(tables sqlbuild.FilterTables, filter types.WorkFilter) (string, error) { - whereSQL, _, err := sqlbuild.BuildReadyWorkWhere(filter, tables, sqlbuild.ReadyWorkWhereInputs{}) - if err != nil { - return "", err - } - order := sqlbuild.BuildReadyWorkOrder(filter.SortPolicy, "created_at", "priority") - return fmt.Sprintf("SELECT id FROM %s %s %s", tables.Main, whereSQL, order.SQL), nil -} - -// readyCountsSQL mirrors issueops.GetReadyWorkWithCountsInTx: the counts -// mega-query fed the ready-work predicates. -func readyCountsSQL(tables sqlbuild.FilterTables, filter types.WorkFilter, includeWispReverseDeps bool) (string, error) { - whereSQL, _, err := sqlbuild.BuildReadyWorkWhere(filter, tables, sqlbuild.ReadyWorkWhereInputs{}) - if err != nil { - return "", err - } - order := sqlbuild.BuildReadyWorkOrder(filter.SortPolicy, "created_at", "priority") - sql, _ := sqlbuild.SearchCountsSQL(tables, nil, whereSQL, order.SQL, "", includeWispReverseDeps, false) - return sql, nil -} - -// adaptiveIDInstrSQL is issueops.GetAdaptiveIDLengthTx's create-path query -// (CONCAT + INSTR + SUBSTRING). Reproduced verbatim so the corpus covers the -// non-search statement family the smoke test's explicit-ID creates never hit. -const adaptiveIDInstrSQL = `SELECT COUNT(*) - FROM issues - WHERE id LIKE CONCAT(?, '-%') - AND INSTR(SUBSTRING(id, LENGTH(?) + 2), '.') = 0` - -func buildCorpus(t *testing.T) []corpusStmt { - t.Helper() - - // Representative filters: priority, an AND label, metadata has-key + eq, - // and a parent filter (each drives a distinct clause shape). - richIssue := types.IssueFilter{ - Priority: intp(1), - Labels: []string{"backlog"}, - HasMetadataKey: "sprint", - MetadataFields: map[string]string{"team": "core"}, - ParentID: strp("bd-1"), - SortBy: "priority", - } - richWork := types.WorkFilter{ - Status: types.Status("open"), - Priority: intp(1), - Labels: []string{"backlog"}, - HasMetadataKey: "sprint", - MetadataFields: map[string]string{"team": "core"}, - ParentID: strp("bd-1"), - } - metaOnly := types.IssueFilter{HasMetadataKey: "sprint", MetadataFields: map[string]string{"team": "core"}} - - var corpus []corpusStmt - add := func(name, sqlText string, err error) { - if err != nil { - t.Fatalf("build corpus %q: %v", name, err) - } - corpus = append(corpus, corpusStmt{name: name, sql: sqlText}) - } - - s, err := searchSelectSQL(sqlbuild.IssuesFilterTables, "", types.IssueFilter{}) - add("search/issues/plain", s, err) - s, err = searchSelectSQL(sqlbuild.IssuesFilterTables, "bd-1", richIssue) - add("search/issues/rich", s, err) - s, err = searchSelectSQL(sqlbuild.WispsFilterTables, "", richIssue) - add("search/wisps/rich", s, err) - s, err = searchSelectSQL(sqlbuild.IssuesFilterTables, "", metaOnly) - add("search/issues/metadata-only", s, err) - - s, err = searchCountsSQL(sqlbuild.IssuesFilterTables, "", types.IssueFilter{}, false) - add("counts/issues/plain", s, err) - s, err = searchCountsSQL(sqlbuild.IssuesFilterTables, "", richIssue, true) - add("counts/issues/rich", s, err) - s, err = searchCountsSQL(sqlbuild.WispsFilterTables, "", richIssue, true) - add("counts/wisps/rich", s, err) - - s, err = readySelectSQL(sqlbuild.IssuesFilterTables, richWork) - add("ready/issues", s, err) - s, err = readySelectSQL(sqlbuild.WispsFilterTables, richWork) - add("ready/wisps", s, err) - s, err = readyCountsSQL(sqlbuild.IssuesFilterTables, richWork, true) - add("ready-counts/issues", s, err) - s, err = readyCountsSQL(sqlbuild.WispsFilterTables, richWork, true) - add("ready-counts/wisps", s, err) - - corpus = append(corpus, - corpusStmt{"adaptive-id/instr", adaptiveIDInstrSQL}, - // Literal-path gate check (issueops/blocked_state.go): keeps the literal - // JSON rule covered alongside the dynamic one. - corpusStmt{"metadata/literal-gate", `SELECT id FROM issues WHERE JSON_UNQUOTE(JSON_EXTRACT(metadata, '$.gate')) = ?`}, - // Dep JSON aggregation in isolation (DATE_FORMAT + JSON_OBJECT + CAST). - corpusStmt{"dep-json/arrayagg", fmt.Sprintf(`SELECT issue_id, JSON_ARRAYAGG(%s) AS deps_json FROM dependencies GROUP BY issue_id`, sqlbuild.DepJSONObject)}, - ) - return corpus -} - -// forbiddenResidue are lowercased markers of MySQL constructs that must never -// survive translation. JSON_ARRAYAGG is intentionally absent: Postgres 16 -// supports SQL-standard JSON_ARRAYAGG natively, so the wedge leaves it in place. -var forbiddenResidue = []string{ - "date_format(", "json_object(", "json_unquote(", "json_extract(", - " as char", "cast(", "insert ignore", "replace into", "on duplicate", - "utc_timestamp", "now()", "`", "?", -} - -func assertNoResidue(t *testing.T, name, translated string) { - t.Helper() - low := strings.ToLower(translated) - for _, marker := range forbiddenResidue { - if strings.Contains(low, marker) { - t.Errorf("%s: untranslated MySQL residue %q survived:\n%s", name, strings.TrimSpace(marker), translated) - } - } -} - -// TestCorpusTranslates runs with no database: it proves every statement family -// translates without error and leaves no MySQL residue. The fail-loud property -// is a build-time guarantee, so this half of the gate always runs. -func TestCorpusTranslates(t *testing.T) { - for _, c := range buildCorpus(t) { - translated, err := pgdialect.Translate(c.sql) - if err != nil { - t.Errorf("%s: Translate error: %v\n-- sql:\n%s", c.name, err, c.sql) - continue - } - assertNoResidue(t, c.name, translated) - } -} - -// TestCorpusPrepare is the live half: PREPARE every translated statement against -// a real Postgres so a construct that is syntactically valid but references a -// missing column/function/operator still fails loudly. Gated on BEADS_PG_TEST_URL. -func TestCorpusPrepare(t *testing.T) { - dsn := os.Getenv("BEADS_PG_TEST_URL") - if dsn == "" { - t.Skip("BEADS_PG_TEST_URL not set; skipping live Postgres PREPARE gate") - } - ctx := context.Background() - schema := fmt.Sprintf("corpus_%d", time.Now().UnixNano()) - - db, err := pgdialect.Open(dsn, schema) - if err != nil { - t.Fatalf("pgdialect.Open: %v", err) - } - t.Cleanup(func() { - _, _ = db.ExecContext(context.Background(), fmt.Sprintf(`DROP SCHEMA IF EXISTS %q CASCADE`, schema)) - _ = db.Close() - }) - if err := createScratchSchema(ctx, db, schema); err != nil { - t.Fatalf("create scratch schema: %v", err) - } - - for _, c := range buildCorpus(t) { - t.Run(c.name, func(t *testing.T) { - translated, err := pgdialect.Translate(c.sql) - if err != nil { - t.Fatalf("Translate error: %v\n-- sql:\n%s", err, c.sql) - } - assertNoResidue(t, c.name, translated) - // PREPARE the RAW statement through the translating driver — the exact - // production path (driver.Translate then server Parse). - stmt, err := db.PrepareContext(ctx, c.sql) - if err != nil { - t.Fatalf("PREPARE failed: %v\n-- translated:\n%s", err, translated) - } - _ = stmt.Close() - }) - } -} - -// createScratchSchema builds just enough of the wedge schema for the corpus to -// PREPARE against: the issues/wisps families (generated from IssueSelectColumns -// so they track the projected column list), their label/dependency/comment -// side tables, and the bd_mysql_jsonkey helper the dynamic-path rewrite calls -// (in production schema.go/InitSchema owns this function). -func createScratchSchema(ctx context.Context, db *sql.DB, schema string) error { - stmts := []string{ - fmt.Sprintf(`CREATE SCHEMA IF NOT EXISTS %q`, schema), - issueTableDDL("issues"), - issueTableDDL("wisps"), - `CREATE TABLE leases (issue_id text, holder text, granted_at timestamp(0), - lease_expires_at timestamp(0), heartbeat_at timestamp(0))`, - `CREATE TABLE labels (issue_id text, label text)`, - `CREATE TABLE wisp_labels (issue_id text, label text)`, - depTableDDL("dependencies"), - depTableDDL("wisp_dependencies"), - `CREATE TABLE comments (issue_id text)`, - `CREATE TABLE wisp_comments (issue_id text)`, - `CREATE OR REPLACE FUNCTION bd_mysql_jsonkey(p text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ - SELECT CASE WHEN p LIKE '$."%"' THEN substring(p from 4 for length(p)-4) ELSE substring(p from 3) END - $$`, - } - for _, s := range stmts { - if _, err := db.ExecContext(ctx, s); err != nil { - return fmt.Errorf("exec %q: %w", firstLine(s), err) - } - } - return nil -} - -// issueTableDDL renders a CREATE TABLE for the issues/wisps family from -// IssueBaseColumns plus the derived is_blocked column the ready-work WHERE -// reads. The lease overlay columns live in the separate leases table -// (bd-lrgn1), created explicitly in createScratchSchema. Column types are -// faithful where an operator depends on them. -func issueTableDDL(table string) string { - var defs []string - for _, name := range splitColumnList(sqlbuild.IssueBaseColumns) { - defs = append(defs, name+" "+pgColumnType(name)) - } - defs = append(defs, "is_blocked smallint NOT NULL DEFAULT 0") - return fmt.Sprintf("CREATE TABLE %s (%s)", table, strings.Join(defs, ", ")) -} - -func depTableDDL(table string) string { - return fmt.Sprintf(`CREATE TABLE %s ( - issue_id text, depends_on_issue_id text, depends_on_wisp_id text, - depends_on_external text, type text, created_by text, - created_at timestamp(0), thread_id text, metadata jsonb)`, table) -} - -func pgColumnType(name string) string { - switch name { - case "metadata": - return "jsonb" - case "created_at", "updated_at", "started_at", "closed_at", "compacted_at", "due_at", "defer_until": - return "timestamp(0)" - case "priority", "estimated_minutes", "compaction_level", "original_size", "timeout_ns": - return "integer" - case "pinned", "ephemeral", "is_template", "no_history": - return "smallint" - default: - return "text" - } -} - -// splitColumnList splits a select-column constant into bare column names. -func splitColumnList(cols string) []string { - raw := strings.NewReplacer("\n", " ", "\t", " ").Replace(cols) - var names []string - for _, p := range strings.Split(raw, ",") { - if n := strings.TrimSpace(p); n != "" { - names = append(names, n) - } - } - return names -} - -func firstLine(s string) string { - if i := strings.IndexByte(s, '\n'); i >= 0 { - return s[:i] - } - return s -} - -// TestTranslateNewRules pins the four red-team translator rules (DATE_FORMAT, -// JSON_OBJECT comma form, CAST AS CHAR, dynamic ?-path JSON metadata), including -// their fail-loud (left-untranslated) branches. -func TestTranslateNewRules(t *testing.T) { - cases := []struct { - name string - in string - want string - }{ - { - name: "DATE_FORMAT ISO8601 -> to_char", - in: `SELECT DATE_FORMAT(created_at, '%Y-%m-%dT%H:%i:%sZ') FROM issues`, - want: `SELECT to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS"Z"') FROM issues`, - }, - { - name: "DATE_FORMAT unknown format left loud", - in: `SELECT DATE_FORMAT(created_at, '%Y-%m-%d') FROM issues`, - want: `SELECT DATE_FORMAT(created_at, '%Y-%m-%d') FROM issues`, - }, - { - name: "JSON_OBJECT even -> jsonb_build_object", - in: `SELECT JSON_OBJECT('a', x, 'b', y) FROM t`, - want: `SELECT jsonb_build_object('a', x, 'b', y) FROM t`, - }, - { - name: "JSON_OBJECT odd arg count left loud", - in: `SELECT JSON_OBJECT('a', x, 'b') FROM t`, - want: `SELECT JSON_OBJECT('a', x, 'b') FROM t`, - }, - { - name: "CAST AS CHAR -> ::text", - in: `SELECT CAST(metadata AS CHAR) FROM t`, - want: `SELECT (metadata)::text FROM t`, - }, - { - name: "CAST AS CHAR(n) -> ::text", - in: `SELECT CAST(metadata AS CHAR(64)) FROM t`, - want: `SELECT (metadata)::text FROM t`, - }, - { - name: "CAST AS SIGNED left loud", - in: `SELECT CAST(x AS SIGNED) FROM t`, - want: `SELECT CAST(x AS SIGNED) FROM t`, - }, - { - name: "dynamic has-key JSON_EXTRACT -> -> bd_mysql_jsonkey", - in: `SELECT id FROM issues WHERE JSON_EXTRACT(metadata, ?) IS NOT NULL`, - want: `SELECT id FROM issues WHERE (metadata -> bd_mysql_jsonkey($1)) IS NOT NULL`, - }, - { - name: "dynamic eq JSON_UNQUOTE(JSON_EXTRACT) -> ->> bd_mysql_jsonkey", - in: `SELECT id FROM issues WHERE JSON_UNQUOTE(JSON_EXTRACT(metadata, ?)) = ?`, - want: `SELECT id FROM issues WHERE (metadata ->> bd_mysql_jsonkey($1)) = $2`, - }, - { - name: "literal path rule still applies (regression)", - in: `SELECT 1 WHERE JSON_UNQUOTE(JSON_EXTRACT(d.metadata, '$.gate')) = 'any-children'`, - want: `SELECT 1 WHERE (d.metadata #>> '{gate}') = 'any-children'`, - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := pgdialect.Translate(tc.in) - if err != nil { - t.Fatalf("Translate error: %v", err) - } - if got != tc.want { - t.Errorf("mismatch\n in: %s\n got: %s\n want: %s", tc.in, got, tc.want) - } - }) - } -} - -// TestTranslateDepJSONObject exercises the real counts.go DepJSONObject constant -// (DATE_FORMAT + JSON_OBJECT + CAST composed) end to end. -func TestTranslateDepJSONObject(t *testing.T) { - got, err := pgdialect.Translate(sqlbuild.DepJSONObject) - if err != nil { - t.Fatalf("Translate error: %v", err) - } - for _, want := range []string{ - "jsonb_build_object(", - `to_char(created_at, 'YYYY-MM-DD"T"HH24:MI:SS"Z"')`, - "(metadata)::text", - } { - if !strings.Contains(got, want) { - t.Errorf("DepJSONObject translation missing %q:\n%s", want, got) - } - } - assertNoResidue(t, "DepJSONObject", got) -} diff --git a/internal/storage/pgdialect/credential.go b/internal/storage/pgdialect/credential.go deleted file mode 100644 index d3b04c062..000000000 --- a/internal/storage/pgdialect/credential.go +++ /dev/null @@ -1,121 +0,0 @@ -package pgdialect - -import ( - "fmt" - "net/url" - "regexp" - "strings" - - "github.com/jackc/pgx/v5" -) - -// kvUserRe matches a libpq keyword/value user token, whose value is either -// single-quoted or a run of non-space chars. Like kvPasswordRe (redact.go) it is a -// token-level regex, not a full parser, so a ` user=` sequence inside another token's -// quoted value could be matched — an exotic case (a keyword-form DSN whose quoted -// value contains ` user=`, combined with a username-bearing credential). The -// round-trip verify in WithCredential catches the loud failures; the silent case is a -// documented sharp edge shared with kvPasswordRe. -var kvUserRe = regexp.MustCompile(`(?i)(^|\s)user\s*=\s*(?:'(?:[^'\\]|\\.)*'|\S*)`) - -// kvHasPasswordRe detects a libpq keyword/value connection password token (password=, -// not sslpassword=) for the DSN-embedded check in HasPassword. -var kvHasPasswordRe = regexp.MustCompile(`(?i)(^|\s)password\s*=`) - -// HasPassword reports whether the connection string itself EMBEDS a password — URL -// userinfo, a URL ?password= query param, or a libpq password= token. It deliberately -// does NOT report whether pgx would resolve a password from the ambient environment: -// pgx.ParseConfig folds PGPASSWORD and ~/.pgpass into cfg.Password, so parsing here -// would let a stale PGPASSWORD short-circuit the whole ladder and mask a configured -// command or credentials file. An embedded password is the only thing that wins -// outright; ambient PGPASSWORD/~/.pgpass remain the driver-native fallback, consulted -// at connect only when no ladder rung is configured. -func HasPassword(dsn string) bool { - if u, err := url.Parse(dsn); err == nil && u.Scheme != "" { - if u.User != nil { - if _, ok := u.User.Password(); ok { - return true - } - } - return u.Query().Get("password") != "" - } - return kvHasPasswordRe.MatchString(dsn) -} - -// WithCredential returns dsn with the resolved credential placed: the password -// always, and the username only when non-empty (a Vault-style dynamic user/password -// pair) — an empty username leaves the DSN's user untouched. It handles both grammars -// pgx accepts (URL userinfo for scheme:// DSNs, single-quoted keyword/value tokens -// otherwise) and VERIFIES with the same parser pgx uses that both fields round-tripped, -// failing loudly rather than emit a DSN that silently drops or mangles the secret. -func WithCredential(dsn, username, password string) (string, error) { - var out string - if u, err := url.Parse(dsn); err == nil && u.Scheme != "" { - // URL form: set the userinfo. url.String() percent-encodes special characters - // (an RDS-IAM token's '&'/'='/'/'), which pgx.ParseConfig decodes back — the - // verify below proves it. - user := username - if user == "" && u.User != nil { - user = u.User.Username() - } - u.User = url.UserPassword(user, password) - out = u.String() - } else { - // libpq keyword/value form: drop any existing password token (and, when we are - // overriding the user, the user token too), then append single-quoted tokens. - stripped := kvPasswordRe.ReplaceAllString(dsn, "$1") - if username != "" { - stripped = kvUserRe.ReplaceAllString(stripped, "$1") - } - stripped = strings.TrimSpace(strings.Join(strings.Fields(stripped), " ")) - if username != "" { - stripped += " user='" + escapeKeywordValue(username) + "'" - } - out = stripped + " password='" + escapeKeywordValue(password) + "'" - } - - cfg, err := pgx.ParseConfig(out) - if err != nil { - return "", fmt.Errorf("cannot place credential into the connection string (unparseable result): %w", err) - } - if cfg.Password != password { - return "", fmt.Errorf("password did not round-trip into the connection string; refusing to connect with a wrong or empty password") - } - if username != "" && cfg.User != username { - return "", fmt.Errorf("username did not round-trip into the connection string; refusing to connect as the wrong user") - } - return out, nil -} - -// WithPassword places only the password, preserving the DSN's user. It is -// WithCredential with no username override. This is the counterpart to -// RedactPassword: RedactPassword strips the password for persistence, WithPassword -// re-injects the resolved password at open time. -func WithPassword(dsn, password string) (string, error) { - return WithCredential(dsn, "", password) -} - -// HostPort returns the TCP endpoint pgx would connect to for dsn, for keying the -// [host:port] credentials-file lookup. ok=false when the DSN does not parse or -// resolves to a unix-socket directory (an absolute-path host) — a peer-auth socket -// has no place in a password file, and the caller degrades the file rung to -// not-configured. For a multi-host DSN this is the primary endpoint only. IPv6 hosts -// are returned bare (e.g. "::1"); the credentials-file key format does not bracket -// them, so an IPv6 endpoint effectively degrades to not-found in the file. -func HostPort(dsn string) (host string, port int, ok bool) { - cfg, err := pgx.ParseConfig(dsn) - if err != nil { - return "", 0, false - } - if cfg.Host == "" || strings.HasPrefix(cfg.Host, "/") { - return "", 0, false - } - return cfg.Host, int(cfg.Port), true -} - -// escapeKeywordValue escapes a value for a single-quoted libpq keyword/value token. -func escapeKeywordValue(s string) string { - s = strings.ReplaceAll(s, `\`, `\\`) - s = strings.ReplaceAll(s, `'`, `\'`) - return s -} diff --git a/internal/storage/pgdialect/credential_extra_test.go b/internal/storage/pgdialect/credential_extra_test.go deleted file mode 100644 index 20251cd12..000000000 --- a/internal/storage/pgdialect/credential_extra_test.go +++ /dev/null @@ -1,148 +0,0 @@ -package pgdialect - -import ( - "os" - "path/filepath" - "testing" - - "github.com/jackc/pgx/v5" -) - -// TestMain neutralizes ambient PGPASSWORD/~/.pgpass so redaction and HasPassword tests -// are hermetic (pgx.ParseConfig folds them into a connection). The ambient-immunity -// tests re-set PGPASSWORD locally via t.Setenv. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "beads-pgdialect-test") - if err != nil { - panic(err) - } - os.Unsetenv("PGPASSWORD") - os.Setenv("PGPASSFILE", filepath.Join(dir, "no-pgpass")) - code := m.Run() - _ = os.RemoveAll(dir) - os.Exit(code) -} - -func mustUser(t *testing.T, out string) string { - t.Helper() - cfg, err := pgx.ParseConfig(out) - if err != nil { - t.Fatalf("pgx.ParseConfig(%q): %v", out, err) - } - return cfg.User -} - -func TestWithCredentialURLForm(t *testing.T) { - out, err := WithCredential("postgres://old@h:5432/db", "vu", "pw") - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "vu" { - t.Fatalf("user = %q, want vu", u) - } - if pw := mustPassword(t, out); pw != "pw" { - t.Fatalf("password = %q, want pw", pw) - } -} - -func TestWithCredentialURLEmptyUsernameKeepsUser(t *testing.T) { - out, err := WithCredential("postgres://old@h:5432/db", "", "pw") - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "old" { - t.Fatalf("user = %q, want old (preserved)", u) - } -} - -func TestWithCredentialKeywordForm(t *testing.T) { - out, err := WithCredential("host=h user=old dbname=db", "vu", "pw") - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "vu" { - t.Fatalf("user = %q, want vu (old stripped)", u) - } - if pw := mustPassword(t, out); pw != "pw" { - t.Fatalf("password = %q, want pw", pw) - } -} - -// WithCredential's own round-trip verify guards escaping; a user and password full of -// quotes/backslashes must survive the keyword grammar. -func TestWithCredentialKeywordEscaping(t *testing.T) { - wantU, wantP := `v'u\x`, `p'w\y` - out, err := WithCredential("host=h dbname=db", wantU, wantP) - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != wantU { - t.Fatalf("user = %q, want %q", u, wantU) - } - if pw := mustPassword(t, out); pw != wantP { - t.Fatalf("password = %q, want %q", pw, wantP) - } -} - -func TestWithCredentialURLSpecialCharsPassword(t *testing.T) { - tok := "p@ss:w/rd&x=1" - out, err := WithCredential("postgres://h:5432/db", "dynuser", tok) - if err != nil { - t.Fatal(err) - } - if u := mustUser(t, out); u != "dynuser" { - t.Fatalf("user = %q, want dynuser", u) - } - if pw := mustPassword(t, out); pw != tok { - t.Fatalf("password = %q, want %q", pw, tok) - } -} - -func TestHostPort(t *testing.T) { - cases := []struct { - dsn string - host string - port int - ok bool - }{ - {"postgres://u@127.0.0.1:6543/db", "127.0.0.1", 6543, true}, - {"postgres://u@db.corp/db", "db.corp", 5432, true}, // pgx defaults the port to 5432 - {"host=db.corp user=u", "db.corp", 5432, true}, // keyword form - {"host=/var/run/postgresql user=u", "", 0, false}, // unix-socket dir -> not ok - } - for _, c := range cases { - h, p, ok := HostPort(c.dsn) - if ok != c.ok || (ok && (h != c.host || p != c.port)) { - t.Errorf("HostPort(%q) = (%q,%d,%v), want (%q,%d,%v)", c.dsn, h, p, ok, c.host, c.port, c.ok) - } - } -} - -// HasPassword must reflect only an embedded password, not one pgx would resolve from -// ambient PGPASSWORD/~/.pgpass — otherwise a stale PGPASSWORD would short-circuit the -// whole ladder. -func TestHasPasswordIgnoresAmbientPGPASSWORD(t *testing.T) { - t.Setenv("PGPASSWORD", "from-env") - if HasPassword("postgres://bts@127.0.0.1:5432/db") { - t.Fatal("HasPassword must not report a password from ambient PGPASSWORD") - } - if !HasPassword("postgres://bts:embedded@127.0.0.1:5432/db") { - t.Fatal("HasPassword must detect an embedded URL password") - } - if !HasPassword("postgres://bts@127.0.0.1:5432/db?password=q") { - t.Fatal("HasPassword must detect a ?password= query param") - } -} - -// RedactPassword must not be fooled by an ambient PGPASSWORD (which pgx would fold in -// but which is never persisted) into refusing a password-less --pg-url at init. -func TestRedactPasswordIgnoresAmbientPGPASSWORD(t *testing.T) { - t.Setenv("PGPASSWORD", "from-env") - got, err := RedactPassword("postgres://bts@127.0.0.1:5432/db") - if err != nil { - t.Fatalf("RedactPassword must not be fooled by ambient PGPASSWORD: %v", err) - } - if HasPassword(got) { - t.Fatalf("redacted DSN still carries an embedded password: %q", got) - } -} diff --git a/internal/storage/pgdialect/credential_test.go b/internal/storage/pgdialect/credential_test.go deleted file mode 100644 index 92f46f28c..000000000 --- a/internal/storage/pgdialect/credential_test.go +++ /dev/null @@ -1,96 +0,0 @@ -package pgdialect - -import ( - "testing" - - "github.com/jackc/pgx/v5" -) - -func TestHasPassword(t *testing.T) { - cases := []struct { - dsn string - want bool - }{ - {"postgres://bts:secret@127.0.0.1:5432/db", true}, - {"postgres://bts@127.0.0.1:5432/db", false}, - {"host=127.0.0.1 port=5432 user=bts password=secret dbname=db", true}, - {"host=127.0.0.1 port=5432 user=bts dbname=db", false}, - } - for _, c := range cases { - if got := HasPassword(c.dsn); got != c.want { - t.Errorf("HasPassword(%q) = %v, want %v", c.dsn, got, c.want) - } - } -} - -// mustPassword parses out and returns the password pgx sees. -func mustPassword(t *testing.T, out string) string { - t.Helper() - cfg, err := pgx.ParseConfig(out) - if err != nil { - t.Fatalf("pgx.ParseConfig(%q): %v", out, err) - } - return cfg.Password -} - -func TestWithPasswordURLForm(t *testing.T) { - out, err := WithPassword("postgres://bts@127.0.0.1:5432/db", "s3cr3t") - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != "s3cr3t" { - t.Fatalf("password = %q, want s3cr3t", pw) - } - // The username must be preserved. - cfg, _ := pgx.ParseConfig(out) - if cfg.User != "bts" { - t.Fatalf("user = %q, want bts", cfg.User) - } -} - -// A token with URL-reserved characters (as an RDS-IAM / GCP-IAM auth token carries) -// must round-trip through the URL grammar intact. -func TestWithPasswordURLSpecialChars(t *testing.T) { - tok := "X-Amz=abc&Signature=d/e+f%20g" - out, err := WithPassword("postgres://bts@host:5432/db", tok) - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != tok { - t.Fatalf("password = %q, want %q", pw, tok) - } -} - -// The keyword/value grammar is the case the old net/url merge silently dropped. -func TestWithPasswordKeywordForm(t *testing.T) { - out, err := WithPassword("host=127.0.0.1 port=5432 user=bts dbname=db", "s3 cr3t") // note the space - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != "s3 cr3t" { - t.Fatalf("password = %q, want %q", pw, "s3 cr3t") - } -} - -// An existing password in a keyword DSN is replaced, not duplicated. -func TestWithPasswordKeywordReplacesExisting(t *testing.T) { - out, err := WithPassword("host=h user=u password=old dbname=db", "new") - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != "new" { - t.Fatalf("password = %q, want new", pw) - } -} - -// A value with a single quote and a backslash survives keyword escaping. -func TestWithPasswordKeywordEscaping(t *testing.T) { - tok := `a'b\c` - out, err := WithPassword("host=h user=u dbname=db", tok) - if err != nil { - t.Fatal(err) - } - if pw := mustPassword(t, out); pw != tok { - t.Fatalf("password = %q, want %q", pw, tok) - } -} diff --git a/internal/storage/pgdialect/driver.go b/internal/storage/pgdialect/driver.go deleted file mode 100644 index 65ea6b06a..000000000 --- a/internal/storage/pgdialect/driver.go +++ /dev/null @@ -1,190 +0,0 @@ -package pgdialect - -import ( - "context" - "database/sql" - "database/sql/driver" - - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/stdlib" -) - -// Open returns a *sql.DB over pgx whose Prepare/PrepareContext translate bd's -// canonical (MySQL-dialect) SQL to Postgres via Translate. searchPath pins the -// workspace schema. -// -// This wrapper deliberately exposes no Queryer/Execer fast path, so database/sql -// routes every statement through Prepare — translation therefore happens in -// exactly one place, and an untranslatable construct fails loudly at PREPARE. -func Open(dsn, searchPath string) (*sql.DB, error) { - cfg, err := pgx.ParseConfig(dsn) - if err != nil { - // pgx's ParseConfigError leaves ?password= URL query params cleartext; scrub - // before the error can reach any log. - return nil, ScrubDSNError(dsn, err) - } - if searchPath != "" { - if cfg.RuntimeParams == nil { - cfg.RuntimeParams = map[string]string{} - } - cfg.RuntimeParams["search_path"] = searchPath - } - return sql.OpenDB(&connector{base: stdlib.GetConnector(*cfg)}), nil -} - -// OpenRaw returns a *sql.DB over pgx WITHOUT the translating connector wrapper, -// so SQL text reaches Postgres verbatim. It exists for schema DDL: the DDL is -// already native Postgres, and routing it through Translate mangles the -// $$-quoted function bodies and rewrites DDL constructs (e.g. now()). searchPath -// pins the workspace schema exactly as Open does. Callers must use native $n -// placeholders, not ?, since Translate is bypassed. -func OpenRaw(dsn, searchPath string) (*sql.DB, error) { - cfg, err := pgx.ParseConfig(dsn) - if err != nil { - // See Open: pgx does not redact query-param passwords in parse errors. - return nil, ScrubDSNError(dsn, err) - } - if searchPath != "" { - if cfg.RuntimeParams == nil { - cfg.RuntimeParams = map[string]string{} - } - cfg.RuntimeParams["search_path"] = searchPath - } - return sql.OpenDB(stdlib.GetConnector(*cfg)), nil -} - -type connector struct{ base driver.Connector } - -func (c *connector) Connect(ctx context.Context) (driver.Conn, error) { - cn, err := c.base.Connect(ctx) - if err != nil { - return nil, err - } - return &conn{base: cn}, nil -} - -func (c *connector) Driver() driver.Driver { return c.base.Driver() } - -// conn wraps a pgx driver.Conn and translates SQL text at prepare time. -type conn struct{ base driver.Conn } - -func (c *conn) Prepare(query string) (driver.Stmt, error) { - q, err := Translate(query) - if err != nil { - return nil, err - } - base, err := c.base.Prepare(q) - if err != nil { - return nil, err - } - return &stmt{base: base, conn: c.base}, nil -} - -func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - q, err := Translate(query) - if err != nil { - return nil, err - } - var base driver.Stmt - if p, ok := c.base.(driver.ConnPrepareContext); ok { - base, err = p.PrepareContext(ctx, q) - } else { - base, err = c.base.Prepare(q) - } - if err != nil { - return nil, err - } - return &stmt{base: base, conn: c.base}, nil -} - -func (c *conn) Close() error { return c.base.Close() } - -//nolint:staticcheck // SA1019: driver.Conn requires the deprecated Begin; BeginTx is preferred and forwarded below. -func (c *conn) Begin() (driver.Tx, error) { return c.base.Begin() } - -func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if b, ok := c.base.(driver.ConnBeginTx); ok { - return b.BeginTx(ctx, opts) - } - return c.base.Begin() //nolint:staticcheck -} - -func (c *conn) ResetSession(ctx context.Context) error { - if rs, ok := c.base.(driver.SessionResetter); ok { - return rs.ResetSession(ctx) - } - return nil -} - -func (c *conn) IsValid() bool { - if v, ok := c.base.(driver.Validator); ok { - return v.IsValid() - } - return true -} - -func (c *conn) Ping(ctx context.Context) error { - if p, ok := c.base.(driver.Pinger); ok { - return p.Ping(ctx) - } - return nil -} - -// stmt wraps a pgx driver.Stmt so bd's MySQL TINYINT(1) discipline survives on -// Postgres: bd binds Go bool arguments to columns that are smallint here (not -// boolean), so CheckNamedValue coerces bool -> 0/1 before binding. Every other -// argument type is forwarded to pgx's own NamedValueChecker so pgx's rich type -// handling (arrays, time, etc.) is preserved. -type stmt struct { - base driver.Stmt - conn driver.Conn -} - -func (s *stmt) CheckNamedValue(nv *driver.NamedValue) error { - if b, ok := nv.Value.(bool); ok { - nv.Value = boolToInt64(b) - return nil - } - if chk, ok := s.conn.(driver.NamedValueChecker); ok { - return chk.CheckNamedValue(nv) - } - return driver.ErrSkip // fall back to database/sql's default conversion -} - -func (s *stmt) Close() error { return s.base.Close() } -func (s *stmt) NumInput() int { return s.base.NumInput() } - -//nolint:staticcheck // driver.Stmt requires the deprecated Exec; ExecContext is preferred and forwarded below. -func (s *stmt) Exec(args []driver.Value) (driver.Result, error) { return s.base.Exec(args) } - -//nolint:staticcheck // driver.Stmt requires the deprecated Query; QueryContext is preferred and forwarded below. -func (s *stmt) Query(args []driver.Value) (driver.Rows, error) { return s.base.Query(args) } - -func (s *stmt) ExecContext(ctx context.Context, args []driver.NamedValue) (driver.Result, error) { - if e, ok := s.base.(driver.StmtExecContext); ok { - return e.ExecContext(ctx, args) - } - return s.base.Exec(namedToValues(args)) //nolint:staticcheck -} - -func (s *stmt) QueryContext(ctx context.Context, args []driver.NamedValue) (driver.Rows, error) { - if q, ok := s.base.(driver.StmtQueryContext); ok { - return q.QueryContext(ctx, args) - } - return s.base.Query(namedToValues(args)) //nolint:staticcheck -} - -func boolToInt64(b bool) int64 { - if b { - return 1 - } - return 0 -} - -func namedToValues(named []driver.NamedValue) []driver.Value { - vals := make([]driver.Value, len(named)) - for i, n := range named { - vals[i] = n.Value - } - return vals -} diff --git a/internal/storage/pgdialect/redact.go b/internal/storage/pgdialect/redact.go deleted file mode 100644 index c415b2f56..000000000 --- a/internal/storage/pgdialect/redact.go +++ /dev/null @@ -1,214 +0,0 @@ -package pgdialect - -import ( - "errors" - "fmt" - "net/url" - "regexp" - "sort" - "strings" - - "github.com/jackc/pgx/v5" -) - -// dsnWSClass is the regexp character class spelling out every byte pgx treats as -// whitespace between libpq keyword/value tokens. Go's regexp \s is [\t\n\f\r ] and -// does NOT include \v (vertical tab); pgx.ParseConfig DOES accept \v as a token -// separator (confirmed: "host=h\vpassword=x" parses host="h", password="x"). Relying -// on \s here would silently fail to match a \v-separated password token at all, -// leaking it in full — so the class is spelled out explicitly instead. -const dsnWSClass = `\t\n\f\r \v` - -// kvPasswordRe matches a libpq keyword/value password token (password= or -// sslpassword=), whose value is either single-quoted or an unquoted run of -// non-whitespace characters that may itself contain backslash-escaped whitespace -// (pgx accepts password=SUPER\ SECRET as the single value `SUPER\ SECRET`, backslash -// retained literally — confirmed against pgx.ParseConfig). -var kvPasswordRe = regexp.MustCompile(`(?i)(^|[` + dsnWSClass + `])(?:password|sslpassword)[` + dsnWSClass + `]*=[` + dsnWSClass + `]*(?:'(?:[^'\\]|\\.)*'|(?:[^` + dsnWSClass + `\\]|\\.)*)`) - -// pwValueRe captures the VALUE of a libpq keyword/value password token: group 1 is -// the single-quoted body, group 2 is an unquoted run of non-whitespace characters, -// including any backslash-escaped whitespace sequences (see kvPasswordRe). -var pwValueRe = regexp.MustCompile(`(?i)(?:^|[` + dsnWSClass + `])(?:password|sslpassword)[` + dsnWSClass + `]*=[` + dsnWSClass + `]*(?:'((?:[^'\\]|\\.)*)'|((?:[^` + dsnWSClass + `\\]|\\.)+))`) - -// RedactPassword returns dsn with the password removed, or an error if a password -// cannot be safely removed. It strips every known password location — URL userinfo, -// URL query params (password, sslpassword), and libpq keyword/value tokens — then -// VERIFIES that no EMBEDDED password survives, failing closed rather than persisting a -// secret in a DSN shape we did not anticipate. The check is embedded-only (HasPassword, -// not pgx.ParseConfig.Password) so an ambient PGPASSWORD/~/.pgpass — which pgx would -// fold in but which is never written to disk — does not falsely block init. -// -// Callers persist the returned string (e.g. to metadata.json) and re-supply the -// password at open time via the credential ladder (see the backend's resolveDSNCredential), -// so nothing operational is lost by never writing the password to disk. The hard -// invariant — a password must never be persisted — is enforced here, not assumed. -func RedactPassword(dsn string) (string, error) { - stripped := stripPasswordBestEffort(dsn) - // It must still parse, or we cannot reason about it — refuse a shape we mangled. - if _, err := pgx.ParseConfig(stripped); err != nil { - return "", fmt.Errorf("cannot verify the connection string is free of a password (unparseable after redaction): %w", err) - } - if HasPassword(stripped) { - return "", fmt.Errorf("refusing to persist a connection string that still carries a password; supply it via BEADS_PG_PASSWORD instead of embedding it in --pg-url") - } - return stripped, nil -} - -// stripPasswordBestEffort removes passwords from the two connection-string shapes -// pgx accepts. The authoritative guarantee is RedactPassword's post-parse check; this -// only has to handle the common forms well enough not to trip that check falsely. -func stripPasswordBestEffort(dsn string) string { - // URL form (scheme://...): strip userinfo password and query password/sslpassword. - if u, err := url.Parse(dsn); err == nil && u.Scheme != "" { - if u.User != nil { - if name := u.User.Username(); name == "" { - u.User = nil - } else { - u.User = url.User(name) - } - } - q := u.Query() - q.Del("password") - q.Del("sslpassword") - u.RawQuery = q.Encode() - return u.String() - } - // libpq keyword/value form (host=... password=... ...): drop the password tokens - // and collapse surrounding whitespace so the remainder still parses. - out := kvPasswordRe.ReplaceAllString(dsn, "$1") - return strings.TrimSpace(strings.Join(strings.Fields(out), " ")) -} - -// ScrubDSNString returns s with every cleartext password embedded in dsn replaced -// by "xxxxx". It is the string-level primitive behind ScrubDSNError, exposed so a -// caller that echoes a DSN somewhere other than an error — a telemetry span, a log -// line — can redact it through the SAME parser-backed extraction (URL userinfo, URL -// query password/sslpassword, and libpq keyword/value tokens) instead of a separate -// hand-rolled scan that misses a form. dsn and s are usually the same string (scrub a -// DSN in place); they differ only when the password leaked into surrounding text, as -// ScrubDSNError passes an error message as s. An empty dsn, or one with no password, -// returns s unchanged. -func ScrubDSNString(dsn, s string) string { - secrets := dsnPasswordValues(dsn) - // Replace the longest secrets first. dsnPasswordValues can return one secret that - // is a byte-for-byte prefix of another (e.g. a userinfo password "foo" and a query - // password "fooACTUAL"); replacing the short one first would turn "fooACTUAL" into - // "xxxxxACTUAL" before the long-secret pass ever runs, leaking the "ACTUAL" tail - // since ReplaceAll can no longer find the (now-mangled) longer substring. - sort.Slice(secrets, func(i, j int) bool { return len(secrets[i]) > len(secrets[j]) }) - for _, secret := range secrets { - s = strings.ReplaceAll(s, secret, "xxxxx") - } - return s -} - -// ScrubDSNError returns a new error whose message has every cleartext password -// embedded in dsn removed. pgx's ParseConfigError redacts only URL userinfo, so a -// `?password=`/`?sslpassword=` URL query param — the shape `bd init` connects with — -// otherwise survives verbatim in the error text and leaks the secret to logs on any -// parse or TLS-config failure. The returned error intentionally does NOT wrap err: -// the pgx error's own Error() still contains the secret, so exposing it through the -// unwrap chain would defeat the redaction. Non-nil in, non-nil out; nil passes through. -func ScrubDSNError(dsn string, err error) error { - if err == nil { - return nil - } - return errors.New(ScrubDSNString(dsn, err.Error())) -} - -// isPasswordKey reports whether k names one of the URL query password params -// (case-insensitively). -func isPasswordKey(k string) bool { - switch strings.ToLower(k) { - case "password", "sslpassword": - return true - } - return false -} - -// dsnPasswordValues returns every cleartext password embedded in dsn — URL userinfo, -// URL query params (password, sslpassword), and libpq keyword/value tokens — in both -// the raw (as-written) and percent-decoded forms, so a value matches however the -// connection string is echoed back. Empty values are skipped, and results are -// de-duplicated. -func dsnPasswordValues(dsn string) []string { - seen := map[string]bool{} - var vals []string - add := func(v string) { - if v == "" || seen[v] { - return - } - seen[v] = true - vals = append(vals, v) - } - if u, err := url.Parse(dsn); err == nil && u.Scheme != "" { - if u.User != nil { - if pw, ok := u.User.Password(); ok { - // url.Parse percent-decodes userinfo, so u.User.Password() is only - // the decoded value. pgx and telemetry sinks echo the DSN verbatim, - // so also scrub the raw as-written form — mirroring the query-param - // branch below, which adds both raw and decoded values. - add(pw) - add(rawURLUserinfoPassword(dsn)) - } - } - // pgx echoes the raw query string back verbatim, so match the raw value; - // also add the decoded value in case a caller logs the parsed form. - for _, pair := range strings.Split(u.RawQuery, "&") { - key, val, ok := strings.Cut(pair, "=") - if !ok { - continue - } - // url.Query() (which pgx.ParseConfig uses) percent-decodes query KEYS as - // well as values, so a query key of pass%77ord or %70assword is a live - // "password" param even though the raw key string doesn't say so. Compare - // both the raw (as-written) key and its unescaped form — ignoring an - // unescape error and falling back to the raw compare, which already ran. - matched := isPasswordKey(key) - if !matched { - if dk, err := url.QueryUnescape(key); err == nil { - matched = isPasswordKey(dk) - } - } - if matched { - add(val) - if dec, err := url.QueryUnescape(val); err == nil { - add(dec) - } - } - } - } - for _, m := range pwValueRe.FindAllStringSubmatch(dsn, -1) { - add(m[1]) // single-quoted body - add(m[2]) // unquoted token - } - return vals -} - -// rawURLUserinfoPassword returns the userinfo password of a URL-form DSN exactly -// as written — still percent-encoded — or "" when there is none. url.Parse decodes -// userinfo, so an encoded secret like SUPER%2ASECRET survives verbatim when a sink -// echoes the raw DSN; extracting it structurally here (rather than re-encoding the -// decoded value) captures the original bytes regardless of encoding form. Mirrors -// the authority split url.Parse performs: password is after the first ':' of the -// userinfo, which is everything before the last '@' of the authority. -func rawURLUserinfoPassword(dsn string) string { - i := strings.Index(dsn, "://") - if i < 0 { - return "" - } - authority := dsn[i+len("://"):] - if j := strings.IndexAny(authority, "/?#"); j >= 0 { - authority = authority[:j] - } - at := strings.LastIndex(authority, "@") - if at < 0 { - return "" - } - _, pw, ok := strings.Cut(authority[:at], ":") - if !ok { - return "" - } - return pw -} diff --git a/internal/storage/pgdialect/redact_error_test.go b/internal/storage/pgdialect/redact_error_test.go deleted file mode 100644 index 4260e6039..000000000 --- a/internal/storage/pgdialect/redact_error_test.go +++ /dev/null @@ -1,188 +0,0 @@ -package pgdialect - -import ( - "database/sql" - "errors" - "strings" - "testing" -) - -// TestScrubDSNError proves an error carrying a DSN can never echo the cleartext -// password back. pgx already redacts URL userinfo and libpq keyword passwords, so -// the URL query-param vectors are the ones that actually leak (see -// TestOpenRedactsPasswordInError); this drives every shape against a worst-case -// error that echoes the raw DSN verbatim. -func TestScrubDSNError(t *testing.T) { - const secret = "SUPERSECRET" - leakForms := []string{secret, "SUPER%2ASECRET", "SUPER*SECRET"} - cases := []struct { - name string - dsn string - }{ - {"url query param", "postgres://u@h:5432/db?password=" + secret}, - {"url query sslpassword", "postgres://u@h:5432/db?sslpassword=" + secret + "&sslmode=require"}, - {"url query param encoded", "postgres://u@h:5432/db?password=SUPER%2ASECRET"}, - {"url userinfo", "postgres://u:" + secret + "@h:5432/db"}, - {"url userinfo encoded", "postgres://u:SUPER%2ASECRET@h:5432/db"}, - {"libpq keyword", "host=h user=u password=" + secret + " dbname=db"}, - {"libpq keyword quoted", "host=h user=u password='" + secret + "' dbname=db"}, - {"libpq sslpassword", "host=h user=u sslpassword=" + secret + " dbname=db"}, - {"url query param percent-encoded key (pass%77ord)", "postgres://u@h:5432/db?pass%77ord=" + secret}, - {"url query sslpassword percent-encoded key (sslpass%77ord)", "postgres://u@h:5432/db?sslpass%77ord=" + secret + "&sslmode=require"}, - {"url query param fully percent-encoded key (%70assword)", "postgres://u@h:5432/db?%70assword=" + secret}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - raw := errors.New("cannot parse `" + tc.dsn + "`: boom") - got := ScrubDSNError(tc.dsn, raw).Error() - for _, form := range leakForms { - if strings.Contains(got, form) { - t.Errorf("scrubbed error still leaks password (%q): %q", form, got) - } - } - // The non-secret failure reason must survive so the error stays useful. - if !strings.Contains(got, "boom") { - t.Errorf("scrubbed error dropped the failure reason: %q", got) - } - }) - } - if ScrubDSNError("postgres://u@h/db?password=x", nil) != nil { - t.Error("ScrubDSNError(dsn, nil) must return nil") - } -} - -// TestScrubDSNString proves the string-level primitive removes every password form -// when a DSN is echoed as plain text (a telemetry span, a log line) rather than an -// error — the same shapes TestScrubDSNError covers, but exercised directly since the -// telemetry scrubber depends on this function, not on ScrubDSNError. -func TestScrubDSNString(t *testing.T) { - const secret = "SUPERSECRET" - leakForms := []string{secret, "SUPER%2ASECRET", "SUPER*SECRET"} - cases := []struct { - name string - dsn string - }{ - {"url userinfo", "postgres://u:" + secret + "@h:5432/db"}, - {"url userinfo encoded", "postgres://u:SUPER%2ASECRET@h:5432/db"}, - {"url query param", "postgres://u@h:5432/db?password=" + secret}, - {"url sslpassword", "postgres://u@h:5432/db?sslpassword=" + secret + "&sslmode=require"}, - {"libpq keyword", "host=h user=u password=" + secret + " dbname=db"}, - {"libpq sslpassword", "host=h user=u sslpassword=" + secret + " dbname=db"}, - {"url query param percent-encoded key (pass%77ord)", "postgres://u@h:5432/db?pass%77ord=" + secret}, - {"url query sslpassword percent-encoded key (sslpass%77ord)", "postgres://u@h:5432/db?sslpass%77ord=" + secret + "&sslmode=require"}, - {"url query param fully percent-encoded key (%70assword)", "postgres://u@h:5432/db?%70assword=" + secret}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := ScrubDSNString(tc.dsn, tc.dsn) - for _, form := range leakForms { - if strings.Contains(got, form) { - t.Errorf("ScrubDSNString(%q) still leaks password (%q): %q", tc.dsn, form, got) - } - } - if !strings.Contains(got, "xxxxx") { - t.Errorf("ScrubDSNString(%q) did not redact: %q", tc.dsn, got) - } - }) - } - // A DSN with no password, and an empty DSN, must pass the target string through. - if got := ScrubDSNString("postgres://u@h:5432/db", "postgres://u@h:5432/db"); got != "postgres://u@h:5432/db" { - t.Errorf("passwordless DSN altered: %q", got) - } - if got := ScrubDSNString("", "no dsn here"); got != "no dsn here" { - t.Errorf("empty dsn altered s: %q", got) - } -} - -// TestOpenRedactsPasswordInError drives the real pgx parser: a DSN that fails to -// parse while carrying a ?password=/?sslpassword= query param must not leak the -// secret through Open or OpenRaw. connect_timeout=x is what makes ParseConfig fail; -// the query-param password is exactly the vector pgx's own redaction misses. -func TestOpenRedactsPasswordInError(t *testing.T) { - const secret = "SUPERSECRET" - dsns := []string{ - "postgres://u@h:5432/db?password=" + secret + "&connect_timeout=x", - "postgres://u@h:5432/db?sslpassword=" + secret + "&connect_timeout=x", - } - opens := []struct { - name string - open func(string, string) (*sql.DB, error) - }{ - {"Open", Open}, - {"OpenRaw", OpenRaw}, - } - for _, dsn := range dsns { - for _, o := range opens { - t.Run(o.name+" "+dsn, func(t *testing.T) { - db, err := o.open(dsn, "public") - if err == nil { - _ = db.Close() - t.Fatal("expected a parse error, got nil") - } - if strings.Contains(err.Error(), secret) { - t.Errorf("%s leaked password in error: %q", o.name, err.Error()) - } - }) - } - } -} - -// TestScrubDSNStringEscapedWhitespaceValue proves an unquoted libpq keyword/value -// password containing a backslash-escaped space is redacted in full. pgx accepts -// password=SUPER\ SECRET as the single password `SUPER\ SECRET` (the backslash is -// retained literally, the escaped space is part of the value — confirmed against -// pgx.ParseConfig); the pre-fix value regex (a \S+-shaped run) stopped at the -// unescaped whitespace boundary and left the tail " SECRET" behind in plaintext. -func TestScrubDSNStringEscapedWhitespaceValue(t *testing.T) { - dsn := `host=h user=u password=SUPER\ SECRET dbname=db` - got := ScrubDSNString(dsn, dsn) - if strings.Contains(got, "SECRET") { - t.Errorf("ScrubDSNString(%q) leaked escaped-whitespace password tail: %q", dsn, got) - } - if strings.Contains(got, `SUPER\`) { - t.Errorf("ScrubDSNString(%q) leaked escaped-whitespace password head: %q", dsn, got) - } - if !strings.Contains(got, "xxxxx") { - t.Errorf("ScrubDSNString(%q) did not redact: %q", dsn, got) - } - if !strings.Contains(got, "host=h") || !strings.Contains(got, "dbname=db") { - t.Errorf("ScrubDSNString(%q) mangled non-secret structure: %q", dsn, got) - } -} - -// TestScrubDSNStringVerticalTabSeparator proves a password separated from the -// preceding keyword/value token by a vertical tab (\v) is still found and redacted. -// pgx treats \v as inter-token whitespace in libpq keyword/value DSNs (confirmed -// against pgx.ParseConfig: "host=h\vpassword=x" parses host="h", password="x"), but -// Go's regexp \s class is [\t\n\f\r ] and does NOT include \v, so the pre-fix -// password regex — anchored on (^|\s) — never matched at a \v boundary and the -// password leaked entirely. -func TestScrubDSNStringVerticalTabSeparator(t *testing.T) { - const secret = "SUPERSECRET" - dsn := "host=h user=u" + "\v" + "password=" + secret + " dbname=db" - got := ScrubDSNString(dsn, dsn) - if strings.Contains(got, secret) { - t.Errorf("ScrubDSNString(%q) leaked password separated by a vertical tab: %q", dsn, got) - } - if !strings.Contains(got, "xxxxx") { - t.Errorf("ScrubDSNString(%q) did not redact vertical-tab-separated password: %q", dsn, got) - } -} - -// TestScrubDSNStringOverlappingSecretsPrefix proves that when one collected secret is -// a byte-for-byte prefix of another (userinfo password "foo", query password -// "fooACTUAL"), redaction does not leak the longer secret's non-overlapping tail. -// ScrubDSNString applies strings.ReplaceAll sequentially per collected secret; doing -// the short secret ("foo") first turns "fooACTUAL" into "xxxxxACTUAL" before the -// long-secret pass ever runs, so the second pass finds no "fooACTUAL" substring left -// to replace and "ACTUAL" survives in plaintext. -func TestScrubDSNStringOverlappingSecretsPrefix(t *testing.T) { - dsn := "postgres://u:foo@h:5432/db?password=fooACTUAL" - got := ScrubDSNString(dsn, dsn) - if strings.Contains(got, "ACTUAL") { - t.Errorf("ScrubDSNString(%q) leaked the tail of a secret that is a prefix of another secret: %q", dsn, got) - } - if strings.Contains(got, ":foo@") { - t.Errorf("ScrubDSNString(%q) did not redact the shorter overlapping secret: %q", dsn, got) - } -} diff --git a/internal/storage/pgdialect/redact_matrix_test.go b/internal/storage/pgdialect/redact_matrix_test.go deleted file mode 100644 index 22fce592e..000000000 --- a/internal/storage/pgdialect/redact_matrix_test.go +++ /dev/null @@ -1,179 +0,0 @@ -package pgdialect - -import ( - "testing" - - "github.com/jackc/pgx/v5" -) - -// placeholderPW is an obvious non-secret stand-in used wherever a password appears in -// these tests, so nothing here can be mistaken for a leaked real credential. -const placeholderPW = "s3cr3t-PLACEHOLDER" - -// tlsExpect encodes what the redacted DSN's TLS state must be: pgx folds sslmode into -// TLSConfig (sslmode=disable -> nil, sslmode=require -> non-nil), so this is how we -// prove sslmode survived redaction. -type tlsExpect int - -const ( - tlsSkip tlsExpect = iota // don't assert (case sets no sslmode) - tlsMustNil // sslmode=disable -> TLSConfig must be nil - tlsMustSet // sslmode=require -> TLSConfig must be non-nil -) - -// TestRedactPasswordMatrix locks the security invariant across every secret-bearing DSN -// shape pgx accepts. For each case it asserts BOTH: -// -// (a) the persisted string, re-parsed by pgx — the SAME parser that opens the -// connection — carries NO password (prove the secret is gone, not just absent -// from the raw string); and -// (b) every non-secret component (host, port, database, user, sslmode, other query -// params) survives redaction. -// -// A no-password DSN must additionally round-trip byte-for-byte unchanged. -func TestRedactPasswordMatrix(t *testing.T) { - cases := []struct { - name string - dsn string - wantHost string - wantPort uint16 - wantDB string - wantUser string - wantTLS tlsExpect - wantParams map[string]string // RuntimeParams that must be preserved - roundTripSame bool // no-password input must come back unchanged - // skipUser: when the input has no user, pgx defaults cfg.User to the OS user, so - // the parsed user is environment-dependent and not something redaction controls. - skipUser bool - }{ - { - name: "url userinfo password", - dsn: "postgres://bts:" + placeholderPW + "@127.0.0.1:5432/db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - }, - { - // The special characters are percent-encoded in userinfo per RFC 3986: - // '@'=%40, ':'=%3A, '/'=%2F. The redactor must still strip it cleanly. - name: "url userinfo password with special chars (url-encoded)", - dsn: "postgres://bts:p%40ss%3Aw%2Frd-" + placeholderPW + "@127.0.0.1:5432/db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - }, - { - name: "url query param password + sslmode preserved", - dsn: "postgres://bts@127.0.0.1:5432/db?password=" + placeholderPW + "&sslmode=disable", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - wantTLS: tlsMustNil, - }, - { - name: "url sslpassword query param + sslmode preserved", - dsn: "postgres://bts@127.0.0.1:5432/db?sslpassword=" + placeholderPW + "&sslmode=require", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - wantTLS: tlsMustSet, - }, - { - name: "url userinfo password with sslmode and application_name preserved", - dsn: "postgres://bts:" + placeholderPW + "@127.0.0.1:5432/db?sslmode=require&application_name=beads", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - wantTLS: tlsMustSet, wantParams: map[string]string{"application_name": "beads"}, - }, - { - name: "url password but no user", - dsn: "postgres://:" + placeholderPW + "@127.0.0.1:5432/db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", skipUser: true, - }, - { - name: "keyword/value password", - dsn: "host=127.0.0.1 port=5432 user=bts password=" + placeholderPW + " dbname=db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - }, - { - name: "keyword/value single-quoted password containing spaces", - dsn: "host=127.0.0.1 port=5432 user=bts password='se cret " + placeholderPW + "' dbname=db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - }, - { - name: "keyword/value sslpassword + sslmode preserved", - dsn: "host=127.0.0.1 port=5432 user=bts sslpassword=" + placeholderPW + " sslmode=require dbname=db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - wantTLS: tlsMustSet, - }, - { - name: "keyword/value password but no user", - dsn: "host=127.0.0.1 port=5432 password=" + placeholderPW + " dbname=db", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", skipUser: true, - }, - { - // Params are in sorted key order because stripPasswordBestEffort re-encodes - // the query via url.Values.Encode(), which sorts keys; the byte-for-byte - // round-trip invariant is asserted against a DSN already in that canonical - // order (application_name < sslmode). - name: "no password (url) round-trips unchanged", - dsn: "postgres://bts@127.0.0.1:5432/db?application_name=beads&sslmode=require", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - wantTLS: tlsMustSet, wantParams: map[string]string{"application_name": "beads"}, - roundTripSame: true, - }, - { - name: "no password (keyword/value) round-trips unchanged", - dsn: "host=127.0.0.1 port=5432 user=bts dbname=db sslmode=require", - wantHost: "127.0.0.1", wantPort: 5432, wantDB: "db", wantUser: "bts", - wantTLS: tlsMustSet, roundTripSame: true, - }, - } - - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := RedactPassword(tc.dsn) - if err != nil { - t.Fatalf("RedactPassword(%q) errored: %v", tc.dsn, err) - } - - // (a) The authoritative security check: the same parser pgx uses to open the - // connection must find no password in the persisted string. - cfg, perr := pgx.ParseConfig(got) - if perr != nil { - t.Fatalf("redacted DSN no longer parses: %q: %v", got, perr) - } - if cfg.Password != "" { - t.Fatalf("PASSWORD LEAK: RedactPassword(%q) = %q still carries password %q", tc.dsn, got, cfg.Password) - } - // Belt and suspenders: the embedded-only detector must also agree. - if HasPassword(got) { - t.Fatalf("PASSWORD LEAK: HasPassword still true for redacted %q", got) - } - - // (b) Non-secret components must survive. - if cfg.Host != tc.wantHost { - t.Errorf("host = %q, want %q", cfg.Host, tc.wantHost) - } - if cfg.Port != tc.wantPort { - t.Errorf("port = %d, want %d", cfg.Port, tc.wantPort) - } - if cfg.Database != tc.wantDB { - t.Errorf("database = %q, want %q", cfg.Database, tc.wantDB) - } - if !tc.skipUser && cfg.User != tc.wantUser { - t.Errorf("user = %q, want %q", cfg.User, tc.wantUser) - } - switch tc.wantTLS { - case tlsMustNil: - if cfg.TLSConfig != nil { - t.Errorf("sslmode not preserved: TLSConfig = %v, want nil (sslmode=disable)", cfg.TLSConfig) - } - case tlsMustSet: - if cfg.TLSConfig == nil { - t.Errorf("sslmode not preserved: TLSConfig = nil, want non-nil (sslmode=require)") - } - } - for k, want := range tc.wantParams { - if got := cfg.RuntimeParams[k]; got != want { - t.Errorf("param %q = %q, want %q (must be preserved)", k, got, want) - } - } - - if tc.roundTripSame && got != tc.dsn { - t.Errorf("no-password DSN must round-trip unchanged:\n in = %q\n out = %q", tc.dsn, got) - } - }) - } -} diff --git a/internal/storage/pgdialect/redact_test.go b/internal/storage/pgdialect/redact_test.go deleted file mode 100644 index bc07f6a05..000000000 --- a/internal/storage/pgdialect/redact_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package pgdialect - -import ( - "testing" - - "github.com/jackc/pgx/v5" -) - -// TestRedactPassword encodes the hard invariant: for every DSN shape pgx accepts, -// RedactPassword's output must carry NO password (verified by re-parsing with pgx), -// while the rest of the connection string survives. These cases include the two -// vectors the red-team confirmed leaked: a query-param password and a libpq -// keyword/value password. -func TestRedactPassword(t *testing.T) { - cases := []struct { - name string - dsn string - }{ - {"url userinfo", "postgres://bts:secret@127.0.0.1:5432/db"}, - {"url query param", "postgres://bts@127.0.0.1:5432/db?password=secret"}, - {"url query param + other", "postgres://bts@127.0.0.1:5432/db?password=secret&sslmode=disable"}, - {"url sslpassword", "postgres://bts@127.0.0.1:5432/db?sslpassword=secret&sslmode=require"}, - {"libpq kv", "host=127.0.0.1 port=5432 user=bts password=secret dbname=db"}, - {"libpq kv quoted", "host=127.0.0.1 user=bts password='se cret' dbname=db"}, - {"libpq kv sslpassword", "host=127.0.0.1 user=bts sslpassword=secret dbname=db"}, - {"no password (url)", "postgres://bts@127.0.0.1:5432/db"}, - {"no password (kv)", "host=127.0.0.1 user=bts dbname=db"}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := RedactPassword(tc.dsn) - if err != nil { - t.Fatalf("RedactPassword(%q) errored: %v", tc.dsn, err) - } - // The authoritative check: pgx — the same parser that opens the - // connection — must see no password in the persisted string. - cfg, perr := pgx.ParseConfig(got) - if perr != nil { - t.Fatalf("redacted DSN no longer parses: %q: %v", got, perr) - } - if cfg.Password != "" { - t.Fatalf("PASSWORD LEAK: RedactPassword(%q) = %q still carries password %q", tc.dsn, got, cfg.Password) - } - }) - } -} - -// TestRedactPasswordFailsClosed: if the input still has a password that the -// best-effort strip missed, RedactPassword must ERROR rather than return a leaky -// string. We simulate an "unanticipated shape" by asserting the post-parse guard is -// what enforces this — a KV password with an exotic separator that the regex could -// miss must never silently pass through with a password. -func TestRedactPasswordNeverReturnsASecret(t *testing.T) { - // Sanity: a plain non-DSN string must not be returned as a "clean" DSN. - if _, err := RedactPassword("::::not a url"); err == nil { - t.Fatal("expected error for an unparseable connection string, got nil") - } -} diff --git a/internal/storage/pgdialect/translate.go b/internal/storage/pgdialect/translate.go deleted file mode 100644 index fa462bdc3..000000000 --- a/internal/storage/pgdialect/translate.go +++ /dev/null @@ -1,778 +0,0 @@ -// Package pgdialect translates the MySQL-dialect SQL that bd's shared storage -// layer (internal/storage/sqlbuild and internal/storage/issueops) emits into -// PostgreSQL, so that same layer can run unchanged over a pgx-backed -// database/sql connection. -// -// It deliberately handles only the constructs bd actually emits on the storage -// path — a finite, enumerable set (see corpus_test.go). Anything it does not -// recognize passes through untouched and surfaces as a loud Postgres syntax -// error at PREPARE time, never a silent mistranslation. That "fail loud" -// property is the whole safety argument: a divergence is a build failure, not a -// subtly wrong row set. -package pgdialect - -import ( - "fmt" - "strings" -) - -// Translate rewrites a single MySQL statement into its Postgres equivalent. -// -// Pass order is deliberate. Function-shaped rewrites (IF, VALUES, CONCAT, -// LOCATE, JSON) run first so the ON DUPLICATE KEY body is already Postgres by -// the time it is wrapped into ON CONFLICT. Placeholder numbering runs last, so -// every earlier pass can move text freely; none of them introduce a literal -// `?`, so left-to-right numbering stays correct. -func Translate(sql string) (string, error) { - out := sql - // CONCAT/LOCATE are unambiguous functions anywhere they appear. IF() and - // VALUES() are NOT translated globally: VALUES is also the INSERT keyword, - // and both only appear as functions inside an ON DUPLICATE KEY UPDATE body, - // so they are translated there (rewriteOnDuplicateKey). - out = rewriteFuncCalls(out, "CONCAT", concatArgs) // CONCAT(a,b) -> (a || b) - out = rewriteFuncCalls(out, "LOCATE", locateArgs) // LOCATE(n,h) -> POSITION(n IN h) - out = rewriteFuncCalls(out, "INSTR", instrArgs) // INSTR(h,n) -> POSITION(n IN h) (args reversed vs LOCATE) - out = rewriteFuncCalls(out, "DATE_FORMAT", dateFormatArgs) // DATE_FORMAT(t,'%Y-%m-%dT%H:%i:%sZ') -> to_char(t,'YYYY-MM-DD"T"HH24:MI:SS"Z"') - out = rewriteFuncCalls(out, "JSON_OBJECT", jsonObjectArgs) // JSON_OBJECT(k,v,...) -> jsonb_build_object(k,v,...) - out = rewriteCastChar(out) // CAST(x AS CHAR[(n)]) -> (x)::text - // CURRENT_TIMESTAMP (not now()) so the replacement contains no token that a - // later pass would re-match. AT TIME ZONE 'utc' yields naive-UTC to match - // bd's Dolt storage discipline. - out = replaceIdentAll(out, "UTC_TIMESTAMP()", "(CURRENT_TIMESTAMP AT TIME ZONE 'utc')") - out = replaceIdentAll(out, "NOW()", "(CURRENT_TIMESTAMP AT TIME ZONE 'utc')") - out = rewriteLiteralJSONUnquote(out) - out = rewriteDynamicJSONPath(out) - out = rewriteLabelOrderBy(out) - out = rewriteInsertIgnore(out) - out = rewriteReplaceInto(out) - out = rewriteOnDuplicateKey(out) - out = rewriteUpdateSetTargets(out) - out = rewriteBackticks(out) - out = numberPlaceholders(out) - return out, nil -} - -// codeMask returns a per-byte bitmap: mask[i] is true iff byte i lies outside -// any string literal or comment. bd uses single-quoted strings (” escapes a -// quote), `--` line comments, and `/* */` blocks; it never double-quotes -// strings (those are identifiers in Postgres/ANSI mode), so a double quote is -// always code. Every text rewrite consults this so it never touches quoted data -// or commented-out SQL. -func codeMask(sql string) []bool { - b := []byte(sql) - m := make([]bool, len(b)) - var inStr, inLine, inBlock bool - for i := 0; i < len(b); i++ { - c := b[i] - switch { - case inLine: - if c == '\n' { - inLine = false - } - case inBlock: - if c == '*' && i+1 < len(b) && b[i+1] == '/' { - i++ // consume '/' - inBlock = false - } - case inStr: - if c == '\'' { - if i+1 < len(b) && b[i+1] == '\'' { - i++ // escaped quote: consume both - } else { - inStr = false - } - } - default: - switch { - case c == '\'': - inStr = true - case c == '-' && i+1 < len(b) && b[i+1] == '-': - i++ - inLine = true - case c == '/' && i+1 < len(b) && b[i+1] == '*': - i++ - inBlock = true - default: - m[i] = true - } - } - } - return m -} - -func isIdentByte(c byte) bool { - return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') -} - -// numberPlaceholders replaces each code-region `?` with $1, $2, … in order. -func numberPlaceholders(sql string) string { - m := codeMask(sql) - var b strings.Builder - n := 0 - for i := 0; i < len(sql); i++ { - if m[i] && sql[i] == '?' { - n++ - fmt.Fprintf(&b, "$%d", n) - continue - } - b.WriteByte(sql[i]) - } - return b.String() -} - -// rewriteBackticks turns `ident` into "ident" in code regions. bd only uses -// backticks around reserved-word column names (e.g. `key`). -func rewriteBackticks(sql string) string { - m := codeMask(sql) - out := []byte(sql) - for i := range out { - if m[i] && out[i] == '`' { - out[i] = '"' - } - } - return string(out) -} - -// replaceIdentAll replaces every code-region occurrence of a literal token -// (case-insensitive) with repl. Used for parameterless functions like -// UTC_TIMESTAMP() and NOW(). -func replaceIdentAll(sql, token, repl string) string { - lower := strings.ToLower(token) - m := codeMask(sql) - var b strings.Builder - // Single forward pass: never re-scans the inserted replacement, so a repl - // that contains the token (NOW() -> "(now() …)") can't loop. - for i := 0; i < len(sql); { - if m[i] && i+len(token) <= len(sql) && strings.ToLower(sql[i:i+len(token)]) == lower { - b.WriteString(repl) - i += len(token) - continue - } - b.WriteByte(sql[i]) - i++ - } - return b.String() -} - -// rewriteFuncCalls finds NAME(args…) in code regions (balanced parens, -// string-aware) and replaces each with rebuild(args). It recurses on each -// argument first, so nested calls (LOCATE(CONCAT(…), x)) translate correctly. -func rewriteFuncCalls(sql, name string, rebuild func(args []string) string) string { - lower := strings.ToLower(name) - searchFrom := 0 - for { - idx := findCallStart(sql, lower, searchFrom) - if idx < 0 { - return sql - } - args, end, ok := splitCallArgs(sql, idx+len(name)) - if !ok { - searchFrom = idx + len(name) // not a call; skip past this token - continue - } - for i := range args { - args[i] = rewriteFuncCalls(strings.TrimSpace(args[i]), name, rebuild) - } - rebuilt := rebuild(args) - sql = sql[:idx] + rebuilt + sql[end:] - // Advance past the rebuilt region — nested same-name calls were already - // handled by the recursion on args, so we never need to revisit it. This - // guarantees forward progress (termination) even if a rebuild happened to - // contain the function name. - searchFrom = idx + len(rebuilt) - } -} - -// findCallStart returns the index of the next code-region, word-boundaried -// occurrence of name (case-insensitive) that is immediately followed by `(` -// (optionally after spaces), at or after `from`; or -1. -func findCallStart(sql, lowerName string, from int) int { - m := codeMask(sql) - for i := from; i+len(lowerName) <= len(sql); i++ { - if !m[i] { - continue - } - if strings.ToLower(sql[i:i+len(lowerName)]) != lowerName { - continue - } - if i > 0 && isIdentByte(sql[i-1]) { - continue // not a word boundary - } - j := i + len(lowerName) - for j < len(sql) && (sql[j] == ' ' || sql[j] == '\t' || sql[j] == '\n') { - j++ - } - if j < len(sql) && sql[j] == '(' { - return i - } - } - return -1 -} - -// splitCallArgs, given the index just after a function name, finds the opening -// paren, walks to the matching close (string-aware), and returns the top-level -// comma-separated arguments plus the index just past the close paren. -func splitCallArgs(sql string, afterName int) (args []string, end int, ok bool) { - m := codeMask(sql) - i := afterName - for i < len(sql) && sql[i] != '(' { - if sql[i] != ' ' && sql[i] != '\t' && sql[i] != '\n' { - return nil, 0, false - } - i++ - } - if i >= len(sql) || sql[i] != '(' { - return nil, 0, false - } - depth := 0 - start := i + 1 - for ; i < len(sql); i++ { - if !m[i] { - continue - } - switch sql[i] { - case '(': - depth++ - case ')': - depth-- - if depth == 0 { - args = append(args, sql[start:i]) - return args, i + 1, true - } - case ',': - if depth == 1 { - args = append(args, sql[start:i]) - start = i + 1 - } - } - } - return nil, 0, false -} - -func ifArgs(args []string) string { - if len(args) != 3 { - return "IF(" + strings.Join(args, ", ") + ")" // leave loud - } - return "CASE WHEN " + strings.TrimSpace(args[0]) + " THEN " + strings.TrimSpace(args[1]) + - " ELSE " + strings.TrimSpace(args[2]) + " END" -} - -func valuesArgs(args []string) string { - if len(args) != 1 { - return "VALUES(" + strings.Join(args, ", ") + ")" - } - return "EXCLUDED." + strings.TrimSpace(args[0]) -} - -func concatArgs(args []string) string { - for i := range args { - args[i] = strings.TrimSpace(args[i]) - } - return "(" + strings.Join(args, " || ") + ")" -} - -func locateArgs(args []string) string { - if len(args) != 2 { - return "LOCATE(" + strings.Join(args, ", ") + ")" // 3-arg form not on bd's path; leave loud - } - return "POSITION(" + strings.TrimSpace(args[0]) + " IN " + strings.TrimSpace(args[1]) + ")" -} - -func instrArgs(args []string) string { - if len(args) != 2 { - return "INSTR(" + strings.Join(args, ", ") + ")" // leave loud - } - // POSITION reverses INSTR's arg order. Placeholder numbering runs later and - // left-to-right, so reordering two args that BOTH carry a `?` would swap their - // $-numbers relative to the caller's bound-arg order — a silent wrong-parameter - // mistranslation. bd only ever emits INSTR(col, ?), so guard the ambiguous case - // by leaving it loud to fail at PREPARE rather than swap bindings. - if strings.Contains(args[0], "?") && strings.Contains(args[1], "?") { - return "INSTR(" + strings.Join(args, ", ") + ")" - } - // MySQL INSTR(haystack, needle) — note the reversed order vs LOCATE. - return "POSITION(" + strings.TrimSpace(args[1]) + " IN " + strings.TrimSpace(args[0]) + ")" -} - -// mysqlDateFormatISO8601 is the ONLY DATE_FORMAT pattern bd emits (counts.go's -// DepJSONObject renders created_at as RFC3339). Any other format literal is -// left untranslated so it fails loudly at PREPARE rather than silently -// producing a differently-shaped timestamp. -const ( - mysqlDateFormatISO8601 = `'%Y-%m-%dT%H:%i:%sZ'` - pgDateFormatISO8601 = `'YYYY-MM-DD"T"HH24:MI:SS"Z"'` -) - -func dateFormatArgs(args []string) string { - if len(args) != 2 || strings.TrimSpace(args[1]) != mysqlDateFormatISO8601 { - return "DATE_FORMAT(" + strings.Join(args, ", ") + ")" // unknown format: leave loud - } - return "to_char(" + strings.TrimSpace(args[0]) + ", " + pgDateFormatISO8601 + ")" -} - -// jsonObjectArgs maps MySQL's comma-form JSON_OBJECT(k1, v1, k2, v2, …) to -// Postgres jsonb_build_object with the same alternating key/value args. An odd -// (or empty) arg count is not a valid object literal, so it is left loud. -func jsonObjectArgs(args []string) string { - if len(args) == 0 || len(args)%2 != 0 { - return "JSON_OBJECT(" + strings.Join(args, ", ") + ")" // leave loud - } - for i := range args { - args[i] = strings.TrimSpace(args[i]) - } - return "jsonb_build_object(" + strings.Join(args, ", ") + ")" -} - -// rewriteInsertIgnore turns `INSERT IGNORE INTO …` into `INSERT INTO … ON -// CONFLICT DO NOTHING`. bd uses it only for idempotent child-table inserts -// (labels, deps, events, comments) with no trailing clause after VALUES/SELECT. -func rewriteInsertIgnore(sql string) string { - const ins = "insert ignore" // bd emits a single space between the keywords - idx := indexCodeFold(sql, ins) - if idx < 0 { - return sql - } - out := sql[:idx] + "INSERT" + sql[idx+len(ins):] - if !containsCodeFold(out, "ON CONFLICT") { - out = strings.TrimRight(out, " \n\t") + " ON CONFLICT DO NOTHING" - } - return out -} - -// rewriteLabelOrderBy makes label sorting explicit on Postgres. The shared -// query text stays raw (`ORDER BY label` / `ORDER BY issue_id, label`) so the -// Dolt reference path remains unchanged; the SQL backends translate it to a -// code-point collation here. -func rewriteLabelOrderBy(sql string) string { - sql = replaceIdentAll(sql, "ORDER BY issue_id, label", `ORDER BY issue_id, label COLLATE "C"`) - return replaceIdentAll(sql, "ORDER BY label", `ORDER BY label COLLATE "C"`) -} - -// rewriteReplaceInto converts MySQL `REPLACE INTO t (c1, c2, …) VALUES …` into -// `INSERT INTO t (c1, c2, …) VALUES … ON CONFLICT (c1) DO UPDATE SET c2 = -// EXCLUDED.c2, …`. bd only uses REPLACE on key/value tables (config, metadata, -// local_metadata) where the first column is the primary key, so treating column -// 1 as the conflict target and overwriting the rest is faithful. The column -// tokens keep their backticks here; the later rewriteBackticks pass quotes them. -func rewriteReplaceInto(sql string) string { - const rep = "replace into" - idx := indexCodeFold(sql, rep) - if idx < 0 { - return sql - } - out := sql[:idx] + "INSERT INTO" + sql[idx+len(rep):] - paren := strings.Index(out[idx:], "(") - if paren < 0 { - return out // no column list — leave loud - } - cols, _, ok := splitCallArgs(out, idx+paren) - if !ok || len(cols) == 0 { - return out - } - target := strings.TrimSpace(cols[0]) - sets := make([]string, 0, len(cols)-1) - for _, c := range cols[1:] { - c = strings.TrimSpace(c) - sets = append(sets, c+" = EXCLUDED."+c) - } - tail := " ON CONFLICT (" + target + ") DO NOTHING" - if len(sets) > 0 { - tail = " ON CONFLICT (" + target + ") DO UPDATE SET " + strings.Join(sets, ", ") - } - return strings.TrimRight(out, " \n\t") + tail -} - -func skipWS(sql string, i int) int { - for i < len(sql) && (sql[i] == ' ' || sql[i] == '\t' || sql[i] == '\n' || sql[i] == '\r') { - i++ - } - return i -} - -// wordAtFold is wordAt with case-insensitive matching (for SQL keywords). -func wordAtFold(sql string, i int, word string) bool { - if i+len(word) > len(sql) || !strings.EqualFold(sql[i:i+len(word)], word) { - return false - } - if i > 0 && isIdentByte(sql[i-1]) { - return false - } - if i+len(word) < len(sql) && isIdentByte(sql[i+len(word)]) { - return false - } - return true -} - -func isIdentWord(s string) bool { - if s == "" { - return false - } - for i := 0; i < len(s); i++ { - if !isIdentByte(s[i]) { - return false - } - } - return true -} - -// rewriteUpdateSetTargets strips the table-alias qualifier from UPDATE SET -// targets: MySQL accepts `UPDATE t a SET a.col = …`, but Postgres requires the -// SET target to be unqualified (`SET col = …`) — it reads `a` as a column -// otherwise. Only the assignment target (left of the top-level `=`) is -// unqualified; alias references on the right-hand side are left intact. -func rewriteUpdateSetTargets(sql string) string { - m := codeMask(sql) - start := skipWS(sql, 0) - if !wordAtFold(sql, start, "update") { - return sql - } - setPos := scanKeyword(sql, m, start, "set") - if setPos < 0 { - return sql - } - clauseStart := setPos + len("set") - clauseEnd := scanKeyword(sql, m, clauseStart, "where") - if clauseEnd < 0 { - if r := scanKeyword(sql, m, clauseStart, "returning"); r >= 0 { - clauseEnd = r - } else { - clauseEnd = len(sql) - } - } - clause := sql[clauseStart:clauseEnd] - cm := codeMask(clause) - var out strings.Builder - depth, segStart := 0, 0 - for j := 0; j < len(clause); j++ { - if cm[j] { - switch clause[j] { - case '(': - depth++ - case ')': - depth-- - case ',': - if depth == 0 { - out.WriteString(unqualifySetTarget(clause[segStart:j])) - out.WriteByte(',') - segStart = j + 1 - } - } - } - } - out.WriteString(unqualifySetTarget(clause[segStart:])) - return sql[:clauseStart] + out.String() + sql[clauseEnd:] -} - -// scanKeyword returns the index of the next depth-0, code-region occurrence of -// keyword (word-boundaried, case-insensitive) at or after from, or -1. -func scanKeyword(sql string, m []bool, from int, keyword string) int { - depth := 0 - for j := from; j < len(sql); j++ { - if !m[j] { - continue - } - switch sql[j] { - case '(': - depth++ - case ')': - depth-- - } - if depth == 0 && wordAtFold(sql, j, keyword) { - return j - } - } - return -1 -} - -func unqualifySetTarget(seg string) string { - cm := codeMask(seg) - depth, eq := 0, -1 - for j := 0; j < len(seg) && eq < 0; j++ { - if !cm[j] { - continue - } - switch seg[j] { - case '(': - depth++ - case ')': - depth-- - case '=': - if depth == 0 { - eq = j - } - } - } - if eq < 0 { - return seg - } - lhs := seg[:eq] - trimmed := strings.TrimSpace(lhs) - dot := strings.IndexByte(trimmed, '.') - if dot <= 0 || !isIdentWord(trimmed[:dot]) || !isIdentWord(trimmed[dot+1:]) { - return seg - } - lead := lhs[:len(lhs)-len(strings.TrimLeft(lhs, " \t\r\n"))] - return lead + trimmed[dot+1:] + " " + seg[eq:] -} - -// onConflictTargets maps a table to the columns Postgres needs as the ON -// CONFLICT arbiter (the primary/unique key MySQL's ON DUPLICATE KEY infers). -// Only tables that use a DO UPDATE upsert need an entry; DO NOTHING needs none. -var onConflictTargets = map[string]string{ - "issues": "id", - "wisps": "id", - "issue_counter": "prefix", - "child_counters": "parent_id", - "wisp_child_counters": "parent_id", - "repo_mtimes": "repo_path", - "federation_peers": "name", - "leases": "issue_id", -} - -// rewriteOnDuplicateKey converts `… ON DUPLICATE KEY UPDATE ` into -// Postgres `… ON CONFLICT () DO UPDATE SET `, or `ON CONFLICT DO -// NOTHING` when the body is an idempotent self-assignment (`col = col`). The ON -// DUPLICATE clause is always last in the statement, so the body runs to the end. -func rewriteOnDuplicateKey(sql string) string { - const odk = "on duplicate key update" - i := indexCodeFold(sql, odk) - if i < 0 { - return sql - } - head := strings.TrimRight(sql[:i], " \n\t") - body := strings.TrimSpace(sql[i+len(odk):]) - if isSelfAssign(body) { - return head + " ON CONFLICT DO NOTHING" - } - // Inside the upsert body, VALUES(col) means the proposed row value - // (Postgres EXCLUDED.col) and IF(c,a,b) is the ternary (CASE). Translate them - // here, where they can't be confused with the INSERT ... VALUES keyword. - body = rewriteFuncCalls(body, "IF", ifArgs) - body = rewriteFuncCalls(body, "VALUES", valuesArgs) - target := onConflictTargets[insertTable(sql)] - if target == "" { - // Unknown upsert target: emit a form that fails PREPARE loudly rather - // than guessing an arbiter (surfaced by the corpus gate). - return head + " ON CONFLICT () DO UPDATE SET " + body - } - return head + " ON CONFLICT (" + target + ") DO UPDATE SET " + body -} - -// isSelfAssign reports whether body is a single `x = x` assignment. -func isSelfAssign(body string) bool { - parts := strings.SplitN(body, "=", 2) - if len(parts) != 2 { - return false - } - l := strings.TrimSpace(parts[0]) - r := strings.TrimSpace(strings.TrimRight(parts[1], " \n\t")) - return l != "" && l == r && !strings.ContainsAny(l, " (),") -} - -// insertTable extracts the target table from a leading `INSERT [IGNORE] INTO -//
`. The table is concrete at runtime (fmt.Sprintf filled it in). -func insertTable(sql string) string { - toks := strings.Fields(sql) - for i := 0; i+1 < len(toks); i++ { - if strings.EqualFold(toks[i], "INTO") { - t := strings.Trim(toks[i+1], "`\"") - if p := strings.IndexAny(t, "("); p >= 0 { - t = t[:p] - } - return t - } - } - return "" -} - -// rewriteLiteralJSONUnquote handles the fixed-path form -// JSON_UNQUOTE(JSON_EXTRACT(, '$.')) (the waits-for gate check), -// rewriting it to ( #>> '{}'). Only the single-level literal-path -// variant is handled; dynamic ?-path metadata filters translate separately. -func rewriteLiteralJSONUnquote(sql string) string { - const marker = "json_unquote(json_extract(" - for { - i := indexCodeFold(sql, marker) - if i < 0 { - return sql - } - open := i + len("JSON_UNQUOTE(") + len("JSON_EXTRACT") - args, extractEnd, ok := splitCallArgs(sql, open) - if !ok || len(args) != 2 || extractEnd >= len(sql) || sql[extractEnd] != ')' { - return sql // malformed / not the literal form: leave loud - } - key := jsonPathToKey(strings.TrimSpace(args[1])) - if key == "" { - return sql // dynamic path: leave for the param translator - } - repl := "(" + strings.TrimSpace(args[0]) + " #>> '{" + key + "}')" - sql = sql[:i] + repl + sql[extractEnd+1:] - } -} - -// rewriteDynamicJSONPath translates the dynamic ?-path metadata filters -// sqlbuild emits (filter.go): the has-key form JSON_EXTRACT(metadata, ?) IS NOT -// NULL and the equality form JSON_UNQUOTE(JSON_EXTRACT(metadata, ?)) = ?. The -// MySQL path argument (e.g. '$.sprint' or '$."gc.routed_to"') is a bound -// parameter, so the bare-key conversion happens at runtime via the -// bd_mysql_jsonkey SQL function (defined in the Postgres schema): -// -// JSON_UNQUOTE(JSON_EXTRACT(, ?)) -> ( ->> bd_mysql_jsonkey(?)) -// JSON_EXTRACT(, ?) -> ( -> bd_mysql_jsonkey(?)) -// -// The unquote form is rewritten first so its inner JSON_EXTRACT is consumed -// before the bare-extract pass runs. Literal-path forms (a quoted '$.key' -// argument) are left untouched here; rewriteLiteralJSONUnquote already handled -// them and any bare literal JSON_EXTRACT is left loud. -func rewriteDynamicJSONPath(sql string) string { - sql = rewriteDynamicJSONUnquote(sql) - sql = rewriteDynamicJSONExtract(sql) - return sql -} - -func rewriteDynamicJSONUnquote(sql string) string { - const marker = "json_unquote(json_extract(" - searchFrom := 0 - for { - i := indexCodeFoldFrom(sql, marker, searchFrom) - if i < 0 { - return sql - } - open := i + len("JSON_UNQUOTE(") + len("JSON_EXTRACT") - args, extractEnd, ok := splitCallArgs(sql, open) - if !ok || len(args) != 2 || extractEnd >= len(sql) || sql[extractEnd] != ')' { - searchFrom = i + len(marker) // malformed / not this form: skip - continue - } - if strings.TrimSpace(args[1]) != "?" { - searchFrom = i + len(marker) // literal path: leave for the literal pass - continue - } - repl := "(" + strings.TrimSpace(args[0]) + " ->> bd_mysql_jsonkey(?))" - sql = sql[:i] + repl + sql[extractEnd+1:] // +1 consumes the outer JSON_UNQUOTE ')' - searchFrom = i + len(repl) - } -} - -func rewriteDynamicJSONExtract(sql string) string { - searchFrom := 0 - for { - idx := findCallStart(sql, "json_extract", searchFrom) - if idx < 0 { - return sql - } - args, end, ok := splitCallArgs(sql, idx+len("JSON_EXTRACT")) - if !ok || len(args) != 2 || strings.TrimSpace(args[1]) != "?" { - searchFrom = idx + len("JSON_EXTRACT") // literal / malformed path: leave loud - continue - } - repl := "(" + strings.TrimSpace(args[0]) + " -> bd_mysql_jsonkey(?))" - sql = sql[:idx] + repl + sql[end:] - searchFrom = idx + len(repl) - } -} - -// rewriteCastChar rewrites CAST( AS CHAR) and CAST( AS CHAR(n)) into -// ()::text. bd emits CAST(metadata AS CHAR) to serialize a JSON column to -// its text form (counts.go DepJSONObject). This rewrite is MANDATORY, not -// cosmetic: Postgres reads a bare CHAR as char(1), so CAST(jsonb AS CHAR) -// prepares silently and truncates the value to a single character. -func rewriteCastChar(sql string) string { - searchFrom := 0 - for { - idx := findCallStart(sql, "cast", searchFrom) - if idx < 0 { - return sql - } - args, end, ok := splitCallArgs(sql, idx+len("CAST")) - if !ok || len(args) != 1 { - searchFrom = idx + len("CAST") - continue - } - expr, isChar := splitCastAsChar(args[0]) - if !isChar { - searchFrom = idx + len("CAST") // not AS CHAR (e.g. AS SIGNED): leave loud - continue - } - repl := "(" + strings.TrimSpace(expr) + ")::text" - sql = sql[:idx] + repl + sql[end:] - searchFrom = idx + len(repl) - } -} - -// splitCastAsChar reports whether inner has the shape " AS CHAR" or -// " AS CHAR(n)" and, if so, returns . The AS is matched at paren -// depth 0 in a code region, so an AS nested inside (e.g. a nested CAST) -// is ignored. -func splitCastAsChar(inner string) (expr string, ok bool) { - m := codeMask(inner) - depth := 0 - for i := 0; i < len(inner); i++ { - if !m[i] { - continue - } - switch inner[i] { - case '(': - depth++ - case ')': - depth-- - } - if depth == 0 && wordAtFold(inner, i, "as") { - if isCharType(strings.TrimSpace(inner[i+len("as"):])) { - return inner[:i], true - } - return "", false - } - } - return "", false -} - -// isCharType reports whether tail is a CHAR type token: "CHAR" or "CHAR(n)". -func isCharType(tail string) bool { - if !wordAtFold(tail, 0, "char") { - return false - } - rest := strings.TrimSpace(tail[len("char"):]) - if rest == "" { - return true // CHAR - } - return rest[0] == '(' && rest[len(rest)-1] == ')' // CHAR(n) -} - -// jsonPathToKey converts a simple literal MySQL JSON path '$.key' into the bare -// key, or "" if it is not a simple single-level literal. -func jsonPathToKey(lit string) string { - if len(lit) < 4 || lit[0] != '\'' || lit[len(lit)-1] != '\'' { - return "" - } - p := lit[1 : len(lit)-1] - if !strings.HasPrefix(p, "$.") { - return "" - } - k := strings.Trim(p[2:], `"`) - if k == "" || strings.ContainsAny(k, ".[]*") { - return "" - } - return k -} - -func indexCodeFold(sql, sub string) int { return indexCodeFoldFrom(sql, sub, 0) } - -// indexCodeFoldFrom is indexCodeFold starting the scan at `from`. Rewrites that -// may legitimately leave a match in place (a literal path they must skip) use -// this to advance past it instead of looping forever. -func indexCodeFoldFrom(sql, sub string, from int) int { - if from < 0 { - from = 0 - } - m := codeMask(sql) - lower := strings.ToLower(sub) - for i := from; i+len(sub) <= len(sql); i++ { - if m[i] && strings.ToLower(sql[i:i+len(sub)]) == lower { - return i - } - } - return -1 -} - -func containsCodeFold(sql, sub string) bool { return indexCodeFold(sql, sub) >= 0 } diff --git a/internal/storage/pgdialect/translate_test.go b/internal/storage/pgdialect/translate_test.go deleted file mode 100644 index d201ac0af..000000000 --- a/internal/storage/pgdialect/translate_test.go +++ /dev/null @@ -1,108 +0,0 @@ -package pgdialect - -import "testing" - -func TestTranslate(t *testing.T) { - cases := []struct { - name string - in string - want string - }{ - { - name: "placeholders numbered", - in: `SELECT * FROM issues WHERE status = ? AND priority = ?`, - want: `SELECT * FROM issues WHERE status = $1 AND priority = $2`, - }, - { - name: "placeholder inside string is left alone", - in: `SELECT '?', assignee FROM issues WHERE id = ?`, - want: `SELECT '?', assignee FROM issues WHERE id = $1`, - }, - { - name: "backtick reserved-word identifier", - in: "SELECT value FROM config WHERE `key` = ?", - want: `SELECT value FROM config WHERE "key" = $1`, - }, - { - name: "INSERT IGNORE -> ON CONFLICT DO NOTHING", - in: `INSERT IGNORE INTO labels (issue_id, label) VALUES (?, ?)`, - want: `INSERT INTO labels (issue_id, label) VALUES ($1, $2) ON CONFLICT DO NOTHING`, - }, - { - name: "ON DUPLICATE KEY type=type -> ON CONFLICT DO NOTHING", - in: `INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_by, created_at) VALUES (?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE type = type`, - want: `INSERT INTO dependencies (id, issue_id, depends_on_issue_id, type, created_by, created_at) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT DO NOTHING`, - }, - { - name: "issue upsert VALUES(col) -> EXCLUDED.col with (id) target", - in: `INSERT INTO issues (id, title) VALUES (?, ?) ON DUPLICATE KEY UPDATE title = VALUES(title)`, - want: `INSERT INTO issues (id, title) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET title = EXCLUDED.title`, - }, - { - name: "stale-guard IF(VALUES...)-> CASE WHEN EXCLUDED", - in: `INSERT INTO issues (id, title, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE title = IF(VALUES(updated_at) > updated_at, VALUES(title), title)`, - want: `INSERT INTO issues (id, title, updated_at) VALUES ($1, $2, $3) ON CONFLICT (id) DO UPDATE SET title = CASE WHEN EXCLUDED.updated_at > updated_at THEN EXCLUDED.title ELSE title END`, - }, - { - name: "lease upsert with (issue_id) target (bd-lrgn1)", - in: `INSERT INTO leases (issue_id, holder, granted_at, lease_expires_at, heartbeat_at) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE holder = VALUES(holder), lease_expires_at = VALUES(lease_expires_at)`, - want: `INSERT INTO leases (issue_id, holder, granted_at, lease_expires_at, heartbeat_at) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (issue_id) DO UPDATE SET holder = EXCLUDED.holder, lease_expires_at = EXCLUDED.lease_expires_at`, - }, - { - name: "lease import-restore never-clobber-live guard (bd-lrgn1)", - in: `INSERT INTO leases (issue_id, holder) VALUES (?, ?) ON DUPLICATE KEY UPDATE holder = IF(leases.lease_expires_at >= ?, leases.holder, VALUES(holder))`, - want: `INSERT INTO leases (issue_id, holder) VALUES ($1, $2) ON CONFLICT (issue_id) DO UPDATE SET holder = CASE WHEN leases.lease_expires_at >= $3 THEN leases.holder ELSE EXCLUDED.holder END`, - }, - { - name: "child counter GREATEST upsert with (parent_id) target", - in: `INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?) ON DUPLICATE KEY UPDATE last_child = GREATEST(last_child, ?)`, - want: `INSERT INTO child_counters (parent_id, last_child) VALUES ($1, $2) ON CONFLICT (parent_id) DO UPDATE SET last_child = GREATEST(last_child, $3)`, - }, - { - name: "UPDATE SET unqualifies target, keeps RHS alias reference", - in: `UPDATE issues i SET i.is_blocked = 1, i.updated_at = i.updated_at WHERE i.id = ?`, - want: `UPDATE issues i SET is_blocked = 1, updated_at = i.updated_at WHERE i.id = $1`, - }, - { - name: "REPLACE INTO -> INSERT ON CONFLICT DO UPDATE", - in: "REPLACE INTO config (`key`, value) VALUES (?, ?)", - want: `INSERT INTO config ("key", value) VALUES ($1, $2) ON CONFLICT ("key") DO UPDATE SET value = EXCLUDED.value`, - }, - { - name: "CONCAT -> || (with LIKE and escaped percent)", - in: `SELECT id FROM issues WHERE id LIKE CONCAT(?, '.%')`, - want: `SELECT id FROM issues WHERE id LIKE ($1 || '.%')`, - }, - { - name: "LOCATE(CONCAT(...)) nested -> POSITION(... IN ...)", - in: `SELECT 1 WHERE LOCATE(CONCAT(',', e.issue_id, ','), d.path) = 0`, - want: `SELECT 1 WHERE POSITION((',' || e.issue_id || ',') IN d.path) = 0`, - }, - { - name: "UTC_TIMESTAMP()", - in: `SELECT 1 WHERE defer_until IS NULL OR defer_until <= UTC_TIMESTAMP()`, - want: `SELECT 1 WHERE defer_until IS NULL OR defer_until <= (CURRENT_TIMESTAMP AT TIME ZONE 'utc')`, - }, - { - name: "literal JSON gate path", - in: `SELECT 1 WHERE JSON_UNQUOTE(JSON_EXTRACT(d.metadata, '$.gate')) = 'any-children'`, - want: `SELECT 1 WHERE (d.metadata #>> '{gate}') = 'any-children'`, - }, - { - name: "binary label collation", - in: `SELECT label FROM labels WHERE issue_id = ? ORDER BY label`, - want: `SELECT label FROM labels WHERE issue_id = $1 ORDER BY label COLLATE "C"`, - }, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got, err := Translate(tc.in) - if err != nil { - t.Fatalf("Translate error: %v", err) - } - if got != tc.want { - t.Errorf("Translate mismatch\n in: %s\n got: %s\n want: %s", tc.in, got, tc.want) - } - }) - } -} diff --git a/internal/storage/postgres/collation.go b/internal/storage/postgres/collation.go deleted file mode 100644 index d3f8ee205..000000000 --- a/internal/storage/postgres/collation.go +++ /dev/null @@ -1,49 +0,0 @@ -package postgres - -import ( - "context" - "database/sql" - "fmt" - "os" - "strings" -) - -// collationParityOK reports whether a Postgres database-level collation orders text -// by byte / Unicode code point — the ordering the shared SQL layer needs to match -// Dolt's utf8mb4_0900_bin oracle. C and POSIX are exact code-point order, and the -// C.* family (e.g. C.UTF-8) also sorts by code point. glibc/ICU locales such as -// en_US.UTF-8 sort linguistically and silently diverge from Dolt. -func collationParityOK(collation string) bool { - c := strings.ToUpper(strings.TrimSpace(collation)) - return c == "C" || c == "POSIX" || strings.HasPrefix(c, "C.") -} - -// databaseCollation returns the connected database's lc_collate. -func databaseCollation(ctx context.Context, db *sql.DB) (string, error) { - var collation string - if err := db.QueryRowContext(ctx, "SHOW lc_collate").Scan(&collation); err != nil { - return "", err - } - return collation, nil -} - -// warnOnCollationDivergence prints a prominent stderr warning when the connected -// database is not code-point ordered. Text columns use the database default -// collation — per-column COLLATE "C" was dropped because it breaks the shared -// recursive CTEs (see schema.go) — so a non-C/POSIX database makes every text -// ORDER BY the shared layer emits (bd list, bd ready, label ordering) sort -// linguistically and diverge from Dolt with no error and no other signal. -// -// It is best-effort: a query failure is swallowed so the check can never block -// opening the store. Running from Provision means `bd init --backend=postgres` -// surfaces the requirement at setup and every later open re-warns until the -// operator recreates the database with a code-point collation. This mirrors the -// Dolt backend's open-time stderr warnings. -func warnOnCollationDivergence(ctx context.Context, db *sql.DB) { - collation, err := databaseCollation(ctx, db) - if err != nil || collationParityOK(collation) { - return - } - fmt.Fprintf(os.Stderr, "Warning: Postgres database collation is %q, not C/POSIX. Text ORDER BY (bd list, bd ready, labels) sorts linguistically and diverges from Dolt's code-point order.\n", collation) - fmt.Fprintln(os.Stderr, " Recreate the database with a code-point collation, e.g. CREATE DATABASE ... TEMPLATE template0 LC_COLLATE 'C' LC_CTYPE 'C';") -} diff --git a/internal/storage/postgres/collation_test.go b/internal/storage/postgres/collation_test.go deleted file mode 100644 index 472100fae..000000000 --- a/internal/storage/postgres/collation_test.go +++ /dev/null @@ -1,29 +0,0 @@ -package postgres - -import "testing" - -func TestCollationParityOK(t *testing.T) { - cases := []struct { - collation string - want bool - }{ - {"C", true}, - {"POSIX", true}, - {"c", true}, // case-insensitive - {"posix", true}, // case-insensitive - {" C ", true}, // trimmed - {"C.UTF-8", true}, // C.* family sorts by code point - {"C.utf8", true}, - {"en_US.UTF-8", false}, - {"en_US.utf8", false}, - {"en_GB.UTF-8", false}, - {"und-x-icu", false}, // ICU root - {"de_DE.UTF-8", false}, - {"", false}, - } - for _, tc := range cases { - if got := collationParityOK(tc.collation); got != tc.want { - t.Errorf("collationParityOK(%q) = %v, want %v", tc.collation, got, tc.want) - } - } -} diff --git a/internal/storage/postgres/completeness_test.go b/internal/storage/postgres/completeness_test.go deleted file mode 100644 index e95bc0182..000000000 --- a/internal/storage/postgres/completeness_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package postgres - -import ( - "os" - "regexp" - "sort" - "testing" - - "github.com/steveyegge/beads/internal/storage/conformance" -) - -// legitimatelyUnsupported is the EXPLICIT denominator of every storage.DoltStorage -// method the Postgres wedge deliberately does not implement, each with a reason. -// -// The interface-completeness gate (TestInterfaceCompleteness) asserts the -// generated capability shell (unsupported_gen.go) contains EXACTLY these methods -// — no more, no less. This is the guard the red-team had to stand in for: a -// method that silently resolves to the typed-unsupported shell (the class that -// bit us: DeleteIssues, GetCustomStatuses, the batch reads, …) fails this test -// at build time instead of failing a user at runtime. Adding a method to the -// shell without an entry here is a hard error that forces the triage question: -// "implement it in sqlkit, or record here why the wedge legitimately omits it." -var legitimatelyUnsupported = map[string]string{ - // VersionControl — the Dolt commit graph. The wedge's whole premise is - // "bd on Postgres, history/version-control simply absent". - "Branch": "VC: Dolt branch", "Checkout": "VC: Dolt checkout", - "CurrentBranch": "VC", "DeleteBranch": "VC", "ListBranches": "VC", - // Commit/CommitWithConfig/CommitMergeResolution are NO-OPS on Postgres (data - // is already durable per-tx), not unsupported — implemented on postgres.Store. - "CommitExists": "VC", "GetCurrentCommit": "VC: Dolt hash", "Status": "VC", - "Log": "VC: dolt_log", "Merge": "VC", "GetConflicts": "VC", "ResolveConflicts": "VC", - - // HistoryViewer — Dolt time-travel. - "History": "history: dolt_log", "AsOf": "history: as-of ref", "Diff": "history: dolt_diff", - - // RemoteStore — Dolt remotes. - "AddRemote": "remote", "RemoveRemote": "remote", "HasRemote": "remote", "ListRemotes": "remote", - "Push": "remote", "Pull": "remote", "ForcePush": "remote", "PushRemote": "remote", - "PullRemote": "remote", "Fetch": "remote", "PushTo": "remote", "PullFrom": "remote", - - // SyncStore — Dolt peer sync. - "Sync": "sync", "SyncStatus": "sync", - - // FederationStore — Dolt-remote-backed peer table. - "AddFederationPeer": "federation", "GetFederationPeer": "federation", - "ListFederationPeers": "federation", "RemoveFederationPeer": "federation", - - // CompactionStore — bound to Dolt commit hashes. - "CheckEligibility": "compaction", "ApplyCompaction": "compaction", - "GetTier1Candidates": "compaction", "GetTier2Candidates": "compaction", - "SnapshotIssue": "compaction", "GetCompactionSnapshot": "compaction", "RestoreFromSnapshot": "compaction", - - // MergeSlot — the Dolt merge-serialization primitive. - "MergeSlotCreate": "merge-slot", "MergeSlotCheck": "merge-slot", - "MergeSlotAcquire": "merge-slot", "MergeSlotRelease": "merge-slot", -} - -var shellMethodRe = regexp.MustCompile(`func \(unsupportedDoltStorage\) ([A-Za-z0-9]+)\(`) - -// TestInterfaceCompleteness is the interface-completeness gate: the generated -// shell must equal the audited legitimatelyUnsupported set, both directions. -func TestInterfaceCompleteness(t *testing.T) { - src, err := os.ReadFile("unsupported_gen.go") - if err != nil { - t.Fatalf("read unsupported_gen.go: %v", err) - } - shell := map[string]bool{} - for _, m := range shellMethodRe.FindAllStringSubmatch(string(src), -1) { - shell[m[1]] = true - } - if len(shell) == 0 { - t.Fatal("parsed 0 shell methods — regex or file drift") - } - - // (1) No SILENT gap: every shell method must be explicitly justified. - var unjustified []string - for m := range shell { - if _, ok := legitimatelyUnsupported[m]; !ok { - unjustified = append(unjustified, m) - } - } - sort.Strings(unjustified) - for _, m := range unjustified { - t.Errorf("method %q resolves to the typed-unsupported shell but is NOT in legitimatelyUnsupported: implement it on *sqlkit.Store, or add it here with a reason", m) - } - - // (2) No STALE allowlist: every justified method must still be in the shell - // (else it was implemented and the entry should be removed). - var stale []string - for m := range legitimatelyUnsupported { - if !shell[m] { - stale = append(stale, m) - } - } - sort.Strings(stale) - for _, m := range stale { - t.Errorf("method %q is in legitimatelyUnsupported but no longer in the shell (implemented?): remove the allowlist entry", m) - } -} - -// TestUnsupportedContract is the behavioral complement to TestInterfaceCompleteness: -// every allowlisted method must actually return a typed storage.ErrUnsupported when -// called, not panic or return a different error. DB-free — the generated stubs ignore -// their receiver, so a zero-value store answers them. -func TestUnsupportedContract(t *testing.T) { - conformance.RunUnsupportedContract(t, &Store{}, legitimatelyUnsupported) -} diff --git a/internal/storage/postgres/conformance_test.go b/internal/storage/postgres/conformance_test.go deleted file mode 100644 index d7eb19446..000000000 --- a/internal/storage/postgres/conformance_test.go +++ /dev/null @@ -1,89 +0,0 @@ -package postgres - -import ( - "context" - "fmt" - "os" - "sync/atomic" - "testing" - "time" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/conformance" - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -// TestConformance runs bd's backend-agnostic storage conformance suite -// (internal/storage/conformance, ~40 encoded behavior tests) against the -// Postgres wedge. This is the real conformance measurement — far broader than -// the smoke. Every failure is a PG gap: either an allowlisted-unsupported method -// (expected — see completeness_test.go) or a latent divergence nothing else -// caught (the interesting ones). Gated on BEADS_PG_TEST_URL. -func TestConformance(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set") - } - conformance.RunAll(t, pgConformanceFactory(url)) -} - -// TestDeferredReads runs the shared deferred non-version-control reads (statistics, -// external-ref, stale) that the wedge now implements through issueops, as a GREEN -// gate. RunAll stays the fail-loud measurement (red on genuinely Dolt-only methods -// like slots), so this focused gate is what conformance.sh runs for the wedge. -// Gated on BEADS_PG_TEST_URL. -func TestDeferredReads(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set") - } - conformance.RunDeferredReads(t, pgConformanceFactory(url)) -} - -// TestPortableMethods runs the full portable-method behavior contract (molecule/ -// repo-mtime/streams/counts/comment/rekey/batch). Red until the methods are wired into -// sqlkit; green after. Gated on BEADS_PG_TEST_URL. -func TestPortableMethods(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set") - } - conformance.RunPortableMethods(t, pgConformanceFactory(url)) -} - -// pgConformanceFactory provisions a fresh, isolated schema per sub-test against the -// Postgres server at url, seeded with issue_prefix as `bd init` leaves it. -func pgConformanceFactory(url string) conformance.Factory { - base := time.Now().UnixNano() - var seq int64 - return func(t *testing.T) storage.DoltStorage { - ctx := context.Background() - schema := fmt.Sprintf("conf_%d_%d", base, atomic.AddInt64(&seq, 1)) - - raw, err := pgdialect.OpenRaw(url, schema) - if err != nil { - t.Fatalf("OpenRaw: %v", err) - } - if err := InitSchema(ctx, raw, schema); err != nil { - _ = raw.Close() - t.Fatalf("InitSchema: %v", err) - } - _ = raw.Close() - - st, err := New(ctx, Config{DSN: url, Schema: schema}) - if err != nil { - t.Fatalf("New: %v", err) - } - // The conformance factory contract wants an init'd store (issue_prefix - // set), as `bd init` leaves it. No Commit — PG has no commit graph. - if err := st.SetConfig(ctx, "issue_prefix", "test"); err != nil { - t.Fatalf("SetConfig(issue_prefix): %v", err) - } - t.Cleanup(func() { - _, _ = st.DB().ExecContext(context.Background(), - fmt.Sprintf(`DROP SCHEMA IF EXISTS %q CASCADE`, schema)) - _ = st.Close() - }) - return st - } -} diff --git a/internal/storage/postgres/credential.go b/internal/storage/postgres/credential.go deleted file mode 100644 index f5eb12cf9..000000000 --- a/internal/storage/postgres/credential.go +++ /dev/null @@ -1,67 +0,0 @@ -package postgres - -import ( - "context" - "fmt" - "os" - - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/creds" - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -// resolveDSNCredential returns baseDSN with a credential resolved and placed, ready to -// connect. The precedence, high to low: -// -// - BEADS_PG_CREDENTIAL_COMMAND set is a hard error: an identity credential is -// presented as a username to a gateway, and this backend connects directly; -// - the DSN already carries a password (a full BEADS_POSTGRES_URL, or an explicit -// --pg-url) — it wins outright, no ladder is applied; -// - BEADS_PG_PASSWORD_COMMAND — a credential command (e.g. Vault / RDS-IAM / GCP-IAM); -// run at open time, cached until near expiry; -// - BEADS_PG_PASSWORD — a static password; -// - the credentials file [host:port] ($BEADS_CREDENTIALS_FILE or -// ~/.config/beads/credentials); -// - nothing configured — baseDSN is returned untouched so pgx's own libpq -// fallbacks (PGPASSWORD, ~/.pgpass, PGPASSFILE) still apply. -// -// It fails closed: if a configured credential command errors, the open aborts — it -// never silently downgrades to a lower rung. -func resolveDSNCredential(ctx context.Context, cfg *configfile.Config, baseDSN string) (string, error) { - if os.Getenv("BEADS_PG_CREDENTIAL_COMMAND") != "" { - return "", fmt.Errorf("postgres: BEADS_PG_CREDENTIAL_COMMAND is reserved: an identity credential is presented as a username to a gateway, and the postgres backend connects directly to the database with no gateway to present it to; use BEADS_PG_PASSWORD_COMMAND for a helper that produces a password") - } - // host:port keys the credentials-file lookup; ok=false (unix socket / unparseable) - // leaves the file rung not-configured (zero Host/Port), never failing. - host, port, _ := pgdialect.HostPort(baseDSN) - return resolveDSNWithSources(ctx, baseDSN, - creds.CommandSource{Command: cfg.GetPostgresPasswordCommand(), Kind: creds.KindSecret, Label: "BEADS_PG_PASSWORD_COMMAND"}, - creds.EnvSource{Var: "BEADS_PG_PASSWORD"}, - creds.FileSource{Host: host, Port: port, Lookup: configfile.LookupCredentialsPassword, Label: "credentials-file"}, - ) -} - -// resolveDSNWithSources is the testable core of resolveDSNCredential: it applies the -// given credential ladder to baseDSN. A DSN that already carries a password wins -// outright; otherwise the first configured source supplies the credential, and -// nothing-configured leaves the DSN untouched for pgx's libpq fallbacks. -func resolveDSNWithSources(ctx context.Context, baseDSN string, sources ...creds.Source) (string, error) { - if pgdialect.HasPassword(baseDSN) { - return baseDSN, nil - } - cred, ok, err := creds.ResolveLadder(ctx, sources...) - if err != nil { - return "", err - } - if !ok { - return baseDSN, nil - } - // The SQL backends take a secret in the password slot; an identity credential - // (presented as a username to a gateway) has no home on a direct connection, so - // refuse it loudly rather than land a token where a password belongs. Defense in - // depth behind the BEADS_PG_CREDENTIAL_COMMAND reject above. - if cred.Kind != creds.KindSecret { - return "", fmt.Errorf("postgres: credential from %s is an identity, not a password; the postgres backend connects directly and has no gateway to present it to", cred.Source) - } - return pgdialect.WithCredential(baseDSN, cred.Username, cred.Value) -} diff --git a/internal/storage/postgres/credential_test.go b/internal/storage/postgres/credential_test.go deleted file mode 100644 index b2c87572b..000000000 --- a/internal/storage/postgres/credential_test.go +++ /dev/null @@ -1,260 +0,0 @@ -package postgres - -import ( - "context" - "os" - "path/filepath" - "strings" - "testing" - - "github.com/jackc/pgx/v5" - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/creds" -) - -const baseDSN = "postgres://bts@127.0.0.1:5432/db" - -// TestMain neutralizes every ambient credential source the rungs could read, so tests -// are hermetic: the beads credentials file, plus pgx's own PGPASSWORD/~/.pgpass (which -// pgx.ParseConfig folds into a connection at parse/connect time). Tests that exercise -// the file rung override BEADS_CREDENTIALS_FILE per-test with t.Setenv. -func TestMain(m *testing.M) { - dir, err := os.MkdirTemp("", "beads-pg-cred-test") - if err != nil { - panic(err) - } - os.Setenv("BEADS_CREDENTIALS_FILE", filepath.Join(dir, "none")) - os.Unsetenv("PGPASSWORD") - os.Setenv("PGPASSFILE", filepath.Join(dir, "no-pgpass")) - code := m.Run() - _ = os.RemoveAll(dir) - os.Exit(code) -} - -// password parses out and returns the password pgx sees, failing the test on a parse error. -func password(t *testing.T, dsn string) string { - t.Helper() - cfg, err := pgx.ParseConfig(dsn) - if err != nil { - t.Fatalf("pgx.ParseConfig(%q): %v", dsn, err) - } - return cfg.Password -} - -// user parses out and returns the username pgx sees. -func user(t *testing.T, dsn string) string { - t.Helper() - cfg, err := pgx.ParseConfig(dsn) - if err != nil { - t.Fatalf("pgx.ParseConfig(%q): %v", dsn, err) - } - return cfg.User -} - -// writeCredsFile writes an INI credentials file and returns its path. -func writeCredsFile(t *testing.T, body string) string { - t.Helper() - p := filepath.Join(t.TempDir(), "credentials") - if err := os.WriteFile(p, []byte(body), 0o600); err != nil { - t.Fatal(err) - } - return p -} - -func TestResolveDSNCredentialCommand(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "printf cmd-pw") - t.Setenv("BEADS_PG_PASSWORD", "") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "cmd-pw" { - t.Fatalf("password = %q, want cmd-pw", pw) - } -} - -func TestResolveDSNCredentialEnv(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "") - t.Setenv("BEADS_PG_PASSWORD", "env-pw") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "env-pw" { - t.Fatalf("password = %q, want env-pw", pw) - } -} - -// The command out-ranks the static env password. -func TestResolveDSNCredentialCommandBeatsEnv(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "printf cmd-wins") - t.Setenv("BEADS_PG_PASSWORD", "env-loses") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "cmd-wins" { - t.Fatalf("password = %q, want cmd-wins", pw) - } -} - -// A failing command aborts the open and does NOT fall through to the env password. -func TestResolveDSNCredentialFailsClosed(t *testing.T) { - // A bare token with whitespace is rejected by parseCredential — a configured error. - t.Setenv("BEADS_PG_PASSWORD_COMMAND", `printf 'access denied'`) - t.Setenv("BEADS_PG_PASSWORD", "env-would-be-wrong") - _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err == nil { - t.Fatal("expected an error (fail-closed); a broken command must not fall through to BEADS_PG_PASSWORD") - } -} - -// Nothing configured: the base DSN comes back untouched (pgx's own PGPASSWORD/.pgpass -// fallbacks then apply at connect). -func TestResolveDSNCredentialNothingConfigured(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "") - t.Setenv("BEADS_PG_PASSWORD", "") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if got != baseDSN { - t.Fatalf("dsn = %q, want it unchanged (%q)", got, baseDSN) - } -} - -// A DSN that already carries a password wins outright — the ladder is not applied. -func TestResolveDSNCredentialExistingPasswordWins(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "printf should-not-run") - t.Setenv("BEADS_PG_PASSWORD", "should-not-run") - withPw := "postgres://bts:already-here@127.0.0.1:5432/db" - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, withPw) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "already-here" { - t.Fatalf("password = %q, want already-here (existing password must win)", pw) - } -} - -// The credentials file resolves the password when no command or env is set. -func TestResolveDSNCredentialFile(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "") - t.Setenv("BEADS_PG_PASSWORD", "") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:5432]\npassword=file-pw\n")) - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "file-pw" { - t.Fatalf("password = %q, want file-pw", pw) - } -} - -// The env password out-ranks the credentials file. -func TestResolveDSNCredentialEnvBeatsFile(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "") - t.Setenv("BEADS_PG_PASSWORD", "env-pw") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:5432]\npassword=file-pw\n")) - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if pw := password(t, got); pw != "env-pw" { - t.Fatalf("password = %q, want env-pw (env out-ranks file)", pw) - } -} - -// A file section for a different endpoint does not match: the DSN is untouched. -func TestResolveDSNCredentialFileWrongSectionMisses(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "") - t.Setenv("BEADS_PG_PASSWORD", "") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:9999]\npassword=file-pw\n")) - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if got != baseDSN { - t.Fatalf("dsn = %q, want it unchanged (wrong section must not match)", got) - } -} - -// A broken command fails closed even when the file could supply a valid password. -func TestResolveDSNCredentialBrokenCommandNotRescuedByFile(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", "false") - t.Setenv("BEADS_PG_PASSWORD", "") - t.Setenv("BEADS_CREDENTIALS_FILE", writeCredsFile(t, "[127.0.0.1:5432]\npassword=file-pw\n")) - if _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN); err == nil { - t.Fatal("expected fail-closed; the credentials file must not rescue a broken command") - } -} - -// A set BEADS_PG_CREDENTIAL_COMMAND is a hard error, pre-empting even a -// password-bearing DSN and any lower rung. -func TestResolveDSNCredentialRejectsReservedIdentityVar(t *testing.T) { - t.Setenv("BEADS_PG_CREDENTIAL_COMMAND", "get-credential") - t.Setenv("BEADS_PG_PASSWORD", "would-otherwise-work") - _, err := resolveDSNCredential(context.Background(), &configfile.Config{}, "postgres://bts:has-pw@127.0.0.1:5432/db") - if err == nil || !strings.Contains(err.Error(), "BEADS_PG_CREDENTIAL_COMMAND") { - t.Fatalf("expected a reserved-var rejection naming BEADS_PG_CREDENTIAL_COMMAND, got %v", err) - } -} - -// staticSource is a test Source with a fixed credential, used to exercise placement -// and the identity-refusal guard directly. -type staticSource struct{ cred creds.Credential } - -func (s staticSource) Name() string { return "test" } -func (s staticSource) Resolve(context.Context) (creds.Credential, bool, error) { - return s.cred, true, nil -} - -// An identity credential (KindIdentity) has no home on a direct SQL connection and -// must be refused, never landed in the password slot. -func TestResolveDSNCredentialRefusesIdentity(t *testing.T) { - src := staticSource{cred: creds.Credential{Value: "an-identity-token", Kind: creds.KindIdentity, Source: "test"}} - _, err := resolveDSNWithSources(context.Background(), baseDSN, src) - if err == nil || !strings.Contains(err.Error(), "identity") { - t.Fatalf("expected an identity-refusal error, got %v", err) - } -} - -// A credential carrying a username (a Vault dynamic user/password pair) places both. -func TestResolveDSNCredentialPlacesUsername(t *testing.T) { - src := staticSource{cred: creds.Credential{Value: "pw", Username: "dyn", Kind: creds.KindSecret}} - got, err := resolveDSNWithSources(context.Background(), baseDSN, src) - if err != nil { - t.Fatal(err) - } - if u := user(t, got); u != "dyn" { - t.Fatalf("user = %q, want dyn", u) - } - if pw := password(t, got); pw != "pw" { - t.Fatalf("password = %q, want pw", pw) - } -} - -// An empty username leaves the DSN's user untouched. -func TestResolveDSNCredentialEmptyUsernameKeepsDSNUser(t *testing.T) { - src := staticSource{cred: creds.Credential{Value: "pw", Username: "", Kind: creds.KindSecret}} - got, err := resolveDSNWithSources(context.Background(), baseDSN, src) - if err != nil { - t.Fatal(err) - } - if u := user(t, got); u != "bts" { - t.Fatalf("user = %q, want bts (DSN user preserved)", u) - } -} - -// End-to-end: a JSON envelope carrying a username places both user and password. -func TestResolveDSNCredentialEnvelopeUsernameEndToEnd(t *testing.T) { - t.Setenv("BEADS_PG_PASSWORD_COMMAND", `printf '{"token":"pw","username":"dyn"}'`) - t.Setenv("BEADS_PG_PASSWORD", "") - got, err := resolveDSNCredential(context.Background(), &configfile.Config{}, baseDSN) - if err != nil { - t.Fatal(err) - } - if u, pw := user(t, got), password(t, got); u != "dyn" || pw != "pw" { - t.Fatalf("(user,password) = (%q,%q), want (dyn,pw)", u, pw) - } -} diff --git a/internal/storage/postgres/dialect.go b/internal/storage/postgres/dialect.go deleted file mode 100644 index 1a5707f13..000000000 --- a/internal/storage/postgres/dialect.go +++ /dev/null @@ -1,22 +0,0 @@ -package postgres - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -// pgDialect is the Postgres SQL flavor: it opens a *sql.DB whose driver -// translates bd's canonical (MySQL-dialect) SQL to Postgres, and pins the -// workspace schema via search_path. -type pgDialect struct { - dsn string - searchPath string -} - -func (d pgDialect) Name() string { return "postgres" } - -func (d pgDialect) Open(_ context.Context) (*sql.DB, error) { - return pgdialect.Open(d.dsn, d.searchPath) -} diff --git a/internal/storage/postgres/fromconfig.go b/internal/storage/postgres/fromconfig.go deleted file mode 100644 index d43f224cf..000000000 --- a/internal/storage/postgres/fromconfig.go +++ /dev/null @@ -1,68 +0,0 @@ -package postgres - -import ( - "context" - "fmt" - - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -// NewFromConfig opens the Postgres backend for a workspace. It reads the base DSN -// and per-workspace schema from .beads/metadata.json, resolves the password through -// the credential ladder (command > env > credentials file, fail-closed) and places -// it into the DSN — never persisting it — then applies the schema over a raw -// non-translating connection and returns the store. This is the factory arm cmd/bd -// dispatches to when metadata.json has backend="postgres". -func NewFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { - cfg, err := configfile.Load(beadsDir) - if err != nil { - return nil, fmt.Errorf("postgres: load config: %w", err) - } - dsn := cfg.GetPostgresDSN() - if dsn == "" { - return nil, fmt.Errorf("postgres: no DSN (set postgres_dsn in metadata.json, or BEADS_POSTGRES_URL)") - } - dsn, err = resolveDSNCredential(ctx, cfg, dsn) - if err != nil { - return nil, fmt.Errorf("postgres: resolve credential: %w", err) - } - schema := cfg.GetPostgresSchema() - if schema == "" { - return nil, fmt.Errorf("postgres: no schema (set postgres_schema in metadata.json)") - } - return Provision(ctx, dsn, schema) -} - -// Provision opens the Postgres backend from an explicit DSN and schema: it applies -// the schema (InitSchema — create-schema, DDL, config seeds, version stamp; all -// idempotent) over a raw non-translating connection, then returns the store over the -// translating driver. dsn may carry a password; it is used only to connect and is -// never persisted. `bd init` calls this directly (before metadata.json exists, using -// the flag-provided DSN); NewFromConfig calls it after resolving DSN/schema from -// metadata. DDL runs raw because the translating driver would mangle the $$-quoted -// function bodies and treat DDL as workload SQL. -func Provision(ctx context.Context, dsn, schema string) (storage.DoltStorage, error) { - if dsn == "" { - return nil, fmt.Errorf("postgres: empty DSN") - } - if schema == "" { - return nil, fmt.Errorf("postgres: empty schema") - } - raw, err := pgdialect.OpenRaw(dsn, schema) - if err != nil { - return nil, fmt.Errorf("postgres: open (raw): %w", err) - } - if err := InitSchema(ctx, raw, schema); err != nil { - _ = raw.Close() - return nil, fmt.Errorf("postgres: init schema: %w", err) - } - // Byte-order parity with Dolt depends on the database collation (text columns - // use the DB default; per-column COLLATE "C" breaks the shared recursive CTEs). - // Warn loudly when it is not code-point ordered, at init and on every open. - warnOnCollationDivergence(ctx, raw) - _ = raw.Close() - - return New(ctx, Config{DSN: dsn, Schema: schema}) -} diff --git a/internal/storage/postgres/repro_instr_test.go b/internal/storage/postgres/repro_instr_test.go deleted file mode 100644 index 6b1478c2e..000000000 --- a/internal/storage/postgres/repro_instr_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package postgres - -import ( - "context" - "fmt" - "os" - "testing" - "time" - - "github.com/steveyegge/beads/internal/types" -) - -// Temporary red-team repro: create with NO explicit ID (default hash-ID path) -// which exercises GetAdaptiveIDLengthTx's INSTR() query. -func TestPGReproHashIDCreate(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set") - } - schema := fmt.Sprintf("repro_%d", time.Now().UnixNano()) - ctx := context.Background() - - st, err := New(ctx, Config{DSN: url, Schema: schema}) - if err != nil { - t.Fatalf("New: %v", err) - } - defer st.Close() - if err := InitSchema(ctx, st.DB(), schema); err != nil { - t.Fatalf("InitSchema: %v", err) - } - t.Cleanup(func() { - _, _ = st.DB().ExecContext(context.Background(), fmt.Sprintf(`DROP SCHEMA IF EXISTS %q CASCADE`, schema)) - }) - if err := st.SetConfig(ctx, "issue_prefix", "repro"); err != nil { - t.Fatalf("SetConfig: %v", err) - } - - iss := &types.Issue{ - Title: "no explicit id", IssueType: types.IssueType("task"), - Status: types.Status("open"), Priority: 2, CreatedBy: "tester", - } - if err := st.CreateIssue(ctx, iss, "tester"); err != nil { - t.Fatalf("CreateIssue(hash-id): %v", err) - } - t.Logf("created id=%s", iss.ID) -} diff --git a/internal/storage/postgres/schema.go b/internal/storage/postgres/schema.go deleted file mode 100644 index 152cfa09a..000000000 --- a/internal/storage/postgres/schema.go +++ /dev/null @@ -1,685 +0,0 @@ -package postgres - -import ( - "context" - "database/sql" - "errors" - "fmt" - "hash/fnv" - "regexp" - "strings" -) - -// schemaAdvisoryLockKey derives a stable Postgres advisory-lock key from a -// workspace schema name. Distinct schemas map to distinct keys so per-workspace -// InitSchema calls serialize against themselves but never against each other. -func schemaAdvisoryLockKey(schema string) int64 { - h := fnv.New64a() - _, _ = h.Write([]byte("bd.initschema:" + schema)) - return int64(h.Sum64()) -} - -// ddl is the Postgres backend schema, embedded verbatim from -// internal/storage/postgres/schema.sql. It is applied statement-by-statement by -// InitSchema because the pgx extended protocol forbids multiple statements per -// Exec. -const ddl = `-- bd Postgres backend schema. --- Machine-translated from Dolt ` + "`" + `SHOW CREATE TABLE` + "`" + ` output at HEAD (all --- migrations applied), using the conformance type map documented in --- docs/architecture/storage-backends.md: --- varchar/char/text/longtext -> text (see collation note below) --- datetime -> timestamp(0) (naive whole-second UTC) --- tinyint(1) -> smallint --- json DEFAULT (json_object()) -> jsonb DEFAULT '{}' --- int -> integer, bigint -> bigint --- ON UPDATE CURRENT_TIMESTAMP -> (no trigger; the shared layer always assigns --- updated_at explicitly on every UPDATE) --- inline KEY / UNIQUE KEY -> CREATE [UNIQUE] INDEX after each table --- All statements are idempotent (IF NOT EXISTS / OR REPLACE); run with --- search_path pinned to the per-workspace schema. --- Views ready_issues / blocked_issues intentionally omitted (unused). --- --- Collation note: Dolt's text columns are utf8mb4_0900_bin (byte / code-point --- order). Per-column COLLATE "C" was dropped from this DDL because it breaks the --- shared layer's parameter-seeded recursive CTEs (ERROR: recursive query column --- has collation "default" in non-recursive term but collation "C" overall). Text --- columns therefore use the database's default collation, so byte-order parity --- with Dolt is a documented wedge gap that must be guaranteed at DEPLOYMENT time --- by creating the database with LC_COLLATE 'C' (CREATE DATABASE ... TEMPLATE --- template0 LC_COLLATE 'C' LC_CTYPE 'C'), NOT per-column. Under any glibc/ICU --- en_US.* collation, every text ORDER BY the shared layer emits diverges from --- Dolt's code-point order. - --- ============================================================ issues - -CREATE TABLE IF NOT EXISTS issues ( - id text NOT NULL, - content_hash text, - title text NOT NULL, - description text NOT NULL, - design text NOT NULL, - acceptance_criteria text NOT NULL, - notes text NOT NULL, - status text NOT NULL DEFAULT 'open', - priority integer NOT NULL DEFAULT 2, - issue_type text NOT NULL DEFAULT 'task', - assignee text, - estimated_minutes integer, - created_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - created_by text DEFAULT '', - owner text DEFAULT '', - updated_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - closed_at timestamp(0), - closed_by_session text DEFAULT '', - external_ref text, - spec_id text, - compaction_level integer DEFAULT 0, - compacted_at timestamp(0), - compacted_at_commit text, - original_size integer, - sender text DEFAULT '', - ephemeral smallint DEFAULT 0, - wisp_type text DEFAULT '', - pinned smallint DEFAULT 0, - is_template smallint DEFAULT 0, - mol_type text DEFAULT '', - work_type text DEFAULT 'mutex', - source_system text DEFAULT '', - metadata jsonb DEFAULT '{}', - source_repo text DEFAULT '', - close_reason text DEFAULT '', - event_kind text DEFAULT '', - actor text DEFAULT '', - target text DEFAULT '', - payload text DEFAULT '', - await_type text DEFAULT '', - await_id text DEFAULT '', - timeout_ns bigint DEFAULT 0, - waiters text DEFAULT '', - hook_bead text DEFAULT '', - role_bead text DEFAULT '', - agent_state text DEFAULT '', - last_activity timestamp(0), - role_type text DEFAULT '', - rig text DEFAULT '', - due_at timestamp(0), - defer_until timestamp(0), - no_history smallint DEFAULT 0, - started_at timestamp(0), - is_blocked smallint NOT NULL DEFAULT 0, - row_lock bigint NOT NULL DEFAULT 0, - PRIMARY KEY (id) -); - -CREATE INDEX IF NOT EXISTS idx_issues_assignee ON issues (assignee); -CREATE INDEX IF NOT EXISTS idx_issues_created_at ON issues (created_at); -CREATE INDEX IF NOT EXISTS idx_issues_defer_until ON issues (defer_until); -CREATE INDEX IF NOT EXISTS idx_issues_external_ref ON issues (external_ref); -CREATE INDEX IF NOT EXISTS idx_issues_is_blocked ON issues (is_blocked, status); -CREATE INDEX IF NOT EXISTS idx_issues_issue_type ON issues (issue_type); -CREATE INDEX IF NOT EXISTS idx_issues_priority ON issues (priority); -CREATE INDEX IF NOT EXISTS idx_issues_spec_id ON issues (spec_id); -CREATE INDEX IF NOT EXISTS idx_issues_status_updated_at ON issues (status, updated_at); - --- ============================================================ leases --- Ephemeral claim leases (bd-lrgn1): node-local, never exported by backup. --- One row per live claim; see issueops.UpsertLeaseInTx for the invariant. - -CREATE TABLE IF NOT EXISTS leases ( - issue_id text NOT NULL, - holder text NOT NULL, - granted_at timestamp(0) NOT NULL, - lease_expires_at timestamp(0) NOT NULL, - heartbeat_at timestamp(0) NOT NULL, - PRIMARY KEY (issue_id) -); - -CREATE INDEX IF NOT EXISTS idx_leases_expires ON leases (lease_expires_at); - --- ============================================================ wisps - -CREATE TABLE IF NOT EXISTS wisps ( - id text NOT NULL, - content_hash text, - title text NOT NULL, - description text NOT NULL DEFAULT '', - design text NOT NULL DEFAULT '', - acceptance_criteria text NOT NULL DEFAULT '', - notes text NOT NULL DEFAULT '', - status text NOT NULL DEFAULT 'open', - priority integer NOT NULL DEFAULT 2, - issue_type text NOT NULL DEFAULT 'task', - assignee text, - estimated_minutes integer, - created_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - created_by text DEFAULT '', - owner text DEFAULT '', - updated_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - closed_at timestamp(0), - closed_by_session text DEFAULT '', - external_ref text, - spec_id text, - compaction_level integer DEFAULT 0, - compacted_at timestamp(0), - compacted_at_commit text, - original_size integer, - sender text DEFAULT '', - ephemeral smallint DEFAULT 0, - wisp_type text DEFAULT '', - pinned smallint DEFAULT 0, - is_template smallint DEFAULT 0, - mol_type text DEFAULT '', - work_type text DEFAULT 'mutex', - source_system text DEFAULT '', - metadata jsonb DEFAULT '{}', - source_repo text DEFAULT '', - close_reason text DEFAULT '', - event_kind text DEFAULT '', - actor text DEFAULT '', - target text DEFAULT '', - payload text DEFAULT '', - await_type text DEFAULT '', - await_id text DEFAULT '', - timeout_ns bigint DEFAULT 0, - waiters text DEFAULT '', - hook_bead text DEFAULT '', - role_bead text DEFAULT '', - agent_state text DEFAULT '', - last_activity timestamp(0), - role_type text DEFAULT '', - rig text DEFAULT '', - due_at timestamp(0), - defer_until timestamp(0), - no_history smallint DEFAULT 0, - started_at timestamp(0), - is_blocked smallint NOT NULL DEFAULT 0, - row_lock bigint NOT NULL DEFAULT 0, - PRIMARY KEY (id) -); - -CREATE INDEX IF NOT EXISTS idx_wisps_assignee ON wisps (assignee); -CREATE INDEX IF NOT EXISTS idx_wisps_created_at ON wisps (created_at); -CREATE INDEX IF NOT EXISTS idx_wisps_external_ref ON wisps (external_ref); -CREATE INDEX IF NOT EXISTS idx_wisps_is_blocked ON wisps (is_blocked, status); -CREATE INDEX IF NOT EXISTS idx_wisps_issue_type ON wisps (issue_type); -CREATE INDEX IF NOT EXISTS idx_wisps_priority ON wisps (priority); -CREATE INDEX IF NOT EXISTS idx_wisps_spec_id ON wisps (spec_id); -CREATE INDEX IF NOT EXISTS idx_wisps_status ON wisps (status); - --- ============================================================ helper functions --- No updated_at trigger: MySQL's ON UPDATE CURRENT_TIMESTAMP is intentionally --- NOT reproduced. The shared layer assigns updated_at explicitly on every issues --- / wisps UPDATE, including the is_blocked mark/unmark idiom that self-assigns --- (SET updated_at = updated_at) precisely to SUPPRESS the auto-bump. A BEFORE --- UPDATE trigger cannot see the statement's SET list, so it would stomp those --- deliberately-suppressed writes to now() and corrupt synced timestamps on the --- hottest dependency-state path; omitting it keeps PG identical to Dolt. - --- bd_mysql_jsonkey normalizes a MySQL JSON path to the bare top-level key the --- translator binds for dynamic metadata filters: '$.sprint' -> sprint, --- '$."gc.routed_to"' -> gc.routed_to. The translator rewrites --- JSON_EXTRACT(metadata, ?) -> metadata -> bd_mysql_jsonkey(?) and --- JSON_UNQUOTE(JSON_EXTRACT(metadata, ?)) -> metadata ->> bd_mysql_jsonkey(?). --- storage.JSONMetadataPath always quotes dotted keys into one top-level segment, --- so a single-key ->/->> lookup is exactly conformant with Dolt. -CREATE OR REPLACE FUNCTION bd_mysql_jsonkey(p text) RETURNS text LANGUAGE sql IMMUTABLE AS $$ SELECT CASE WHEN p LIKE '$."%"' THEN substring(p from 4 for length(p)-4) ELSE substring(p from 3) END $$; - --- ============================================================ labels - -CREATE TABLE IF NOT EXISTS labels ( - issue_id text NOT NULL, - label text NOT NULL, - PRIMARY KEY (issue_id, label), - CONSTRAINT fk_labels_issue FOREIGN KEY (issue_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_labels_label ON labels (label); - --- ============================================================ wisp_labels - -CREATE TABLE IF NOT EXISTS wisp_labels ( - issue_id text NOT NULL, - label text NOT NULL, - PRIMARY KEY (issue_id, label), - CONSTRAINT fk_wisp_labels_issue FOREIGN KEY (issue_id) REFERENCES wisps (id) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_wisp_labels_label ON wisp_labels (label); - --- ============================================================ dependencies - -CREATE TABLE IF NOT EXISTS dependencies ( - id text NOT NULL, - issue_id text NOT NULL, - type text NOT NULL DEFAULT 'blocks', - created_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - created_by text NOT NULL, - metadata jsonb DEFAULT '{}', - thread_id text DEFAULT '', - depends_on_issue_id text, - depends_on_wisp_id text, - depends_on_external text, - PRIMARY KEY (id), - CONSTRAINT fk_dep_issue FOREIGN KEY (issue_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT fk_dep_issue_target FOREIGN KEY (depends_on_issue_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT ck_dep_one_target CHECK ( - ((depends_on_issue_id IS NOT NULL)::integer - + (depends_on_wisp_id IS NOT NULL)::integer - + (depends_on_external IS NOT NULL)::integer) = 1 - ) -); - -CREATE INDEX IF NOT EXISTS idx_dep_external_target ON dependencies (depends_on_external); -CREATE INDEX IF NOT EXISTS idx_dep_issue_target ON dependencies (depends_on_issue_id); -CREATE INDEX IF NOT EXISTS idx_dep_type_external ON dependencies (type, depends_on_external); -CREATE INDEX IF NOT EXISTS idx_dep_type_issue ON dependencies (type, depends_on_issue_id); -CREATE INDEX IF NOT EXISTS idx_dep_type_wisp ON dependencies (type, depends_on_wisp_id); -CREATE INDEX IF NOT EXISTS idx_dep_wisp_target ON dependencies (depends_on_wisp_id); -CREATE INDEX IF NOT EXISTS idx_dependencies_issue ON dependencies (issue_id); -CREATE INDEX IF NOT EXISTS idx_dependencies_thread ON dependencies (thread_id); --- MySQL unique keys treat NULLs as distinct; PG's default (NULLS DISTINCT) matches. -CREATE UNIQUE INDEX IF NOT EXISTS uk_dep_external_target ON dependencies (issue_id, depends_on_external); -CREATE UNIQUE INDEX IF NOT EXISTS uk_dep_issue_target ON dependencies (issue_id, depends_on_issue_id); -CREATE UNIQUE INDEX IF NOT EXISTS uk_dep_wisp_target ON dependencies (issue_id, depends_on_wisp_id); - --- ============================================================ wisp_dependencies - -CREATE TABLE IF NOT EXISTS wisp_dependencies ( - id text NOT NULL, - issue_id text NOT NULL, - depends_on_issue_id text, - depends_on_wisp_id text, - depends_on_external text, - type text NOT NULL DEFAULT 'blocks', - created_at timestamp(0) DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - created_by text DEFAULT '', - metadata jsonb DEFAULT '{}', - thread_id text DEFAULT '', - PRIMARY KEY (id), - CONSTRAINT fk_wisp_dep_issue FOREIGN KEY (issue_id) REFERENCES wisps (id) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT fk_wisp_dep_issue_target FOREIGN KEY (depends_on_issue_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT fk_wisp_dep_wisp_target FOREIGN KEY (depends_on_wisp_id) REFERENCES wisps (id) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT ck_wisp_dep_one_target CHECK ( - ((depends_on_issue_id IS NOT NULL)::integer - + (depends_on_wisp_id IS NOT NULL)::integer - + (depends_on_external IS NOT NULL)::integer) = 1 - ) -); - -CREATE INDEX IF NOT EXISTS fk_wisp_dep_issue_target ON wisp_dependencies (depends_on_issue_id); -CREATE INDEX IF NOT EXISTS fk_wisp_dep_wisp_target ON wisp_dependencies (depends_on_wisp_id); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type ON wisp_dependencies (type); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type_external ON wisp_dependencies (type, depends_on_external); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type_issue ON wisp_dependencies (type, depends_on_issue_id); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type_wisp ON wisp_dependencies (type, depends_on_wisp_id); -CREATE UNIQUE INDEX IF NOT EXISTS uk_wisp_dep_external_target ON wisp_dependencies (issue_id, depends_on_external); -CREATE UNIQUE INDEX IF NOT EXISTS uk_wisp_dep_issue_target ON wisp_dependencies (issue_id, depends_on_issue_id); -CREATE UNIQUE INDEX IF NOT EXISTS uk_wisp_dep_wisp_target ON wisp_dependencies (issue_id, depends_on_wisp_id); - --- ============================================================ comments - -CREATE TABLE IF NOT EXISTS comments ( - id text NOT NULL, - issue_id text NOT NULL, - author text NOT NULL, - text text NOT NULL, - created_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - PRIMARY KEY (id), - CONSTRAINT fk_comments_issue FOREIGN KEY (issue_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_comments_created_at ON comments (created_at); -CREATE INDEX IF NOT EXISTS idx_comments_issue ON comments (issue_id); - --- ============================================================ wisp_comments - -CREATE TABLE IF NOT EXISTS wisp_comments ( - id text NOT NULL, - issue_id text NOT NULL, - author text DEFAULT '', - text text NOT NULL, - created_at timestamp(0) DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - PRIMARY KEY (id), - CONSTRAINT fk_wisp_comments_issue FOREIGN KEY (issue_id) REFERENCES wisps (id) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_wisp_comments_issue ON wisp_comments (issue_id); - --- ============================================================ events - -CREATE TABLE IF NOT EXISTS events ( - id text NOT NULL, - issue_id text NOT NULL, - event_type text NOT NULL, - actor text NOT NULL, - old_value text, - new_value text, - comment text, - created_at timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - PRIMARY KEY (id), - CONSTRAINT fk_events_issue FOREIGN KEY (issue_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_events_created_at ON events (created_at); -CREATE INDEX IF NOT EXISTS idx_events_issue ON events (issue_id); - --- ============================================================ wisp_events - -CREATE TABLE IF NOT EXISTS wisp_events ( - id text NOT NULL, - issue_id text NOT NULL, - event_type text NOT NULL, - actor text DEFAULT '', - old_value text DEFAULT '', - new_value text DEFAULT '', - comment text DEFAULT '', - created_at timestamp(0) DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - PRIMARY KEY (id), - CONSTRAINT fk_wisp_events_issue FOREIGN KEY (issue_id) REFERENCES wisps (id) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE INDEX IF NOT EXISTS idx_wisp_events_created_at ON wisp_events (created_at); -CREATE INDEX IF NOT EXISTS idx_wisp_events_issue ON wisp_events (issue_id); - --- ============================================================ config - -CREATE TABLE IF NOT EXISTS config ( - key text NOT NULL, - value text NOT NULL, - PRIMARY KEY (key) -); - --- ============================================================ metadata - -CREATE TABLE IF NOT EXISTS metadata ( - key text NOT NULL, - value text NOT NULL, - PRIMARY KEY (key) -); - --- ============================================================ local_metadata - -CREATE TABLE IF NOT EXISTS local_metadata ( - key text NOT NULL, - value text NOT NULL DEFAULT '', - PRIMARY KEY (key) -); - --- ============================================================ issue_counter - -CREATE TABLE IF NOT EXISTS issue_counter ( - prefix text NOT NULL, - last_id integer NOT NULL DEFAULT 0, - PRIMARY KEY (prefix) -); - --- ============================================================ child_counters - -CREATE TABLE IF NOT EXISTS child_counters ( - parent_id text NOT NULL, - last_child integer NOT NULL DEFAULT 0, - PRIMARY KEY (parent_id), - CONSTRAINT fk_counter_parent FOREIGN KEY (parent_id) REFERENCES issues (id) ON DELETE CASCADE ON UPDATE CASCADE -); - --- ============================================================ wisp_child_counters - -CREATE TABLE IF NOT EXISTS wisp_child_counters ( - parent_id text NOT NULL, - last_child integer NOT NULL DEFAULT 0, - PRIMARY KEY (parent_id), - CONSTRAINT fk_wisp_child_counters_parent FOREIGN KEY (parent_id) REFERENCES wisps (id) ON DELETE CASCADE ON UPDATE CASCADE -); - --- ============================================================ custom_statuses - -CREATE TABLE IF NOT EXISTS custom_statuses ( - name text NOT NULL, - category text NOT NULL DEFAULT 'unspecified', - PRIMARY KEY (name) -); - --- ============================================================ custom_types - -CREATE TABLE IF NOT EXISTS custom_types ( - name text NOT NULL, - PRIMARY KEY (name) -); - --- ============================================================ repo_mtimes - -CREATE TABLE IF NOT EXISTS repo_mtimes ( - repo_path text NOT NULL, - jsonl_path text NOT NULL, - mtime_ns bigint NOT NULL, - last_checked timestamp(0) NOT NULL DEFAULT (date_trunc('second', now() AT TIME ZONE 'utc')), - PRIMARY KEY (repo_path) -); - -CREATE INDEX IF NOT EXISTS idx_repo_mtimes_checked ON repo_mtimes (last_checked); -` - -// schemaVersion is stamped into the metadata table by InitSchema. A workspace -// carrying a different stamp is rejected: this proof-wedge ships no migrator. -const schemaVersion = "1" - -// schemaVersionKey lives in the metadata table (NOT config): config rows are -// surfaced by issueops.GetAllConfig / `bd config list`, so a version key there -// would leak a permanent diff against the Dolt oracle in differential runs. The -// metadata table is where the shared layer already keeps backend-internal keys. -const schemaVersionKey = "pg_schema_version" - -// schemaNameRe restricts schema names to a plain SQL identifier so they can be -// safely interpolated into CREATE SCHEMA (which cannot take a placeholder). -var schemaNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`) - -// InitSchema creates the per-workspace schema if absent, then applies the -// embedded DDL one statement at a time and stamps the schema version. -// -// db must be a RAW *sql.DB (pgdialect.OpenRaw), not the translating one: the DDL -// is already native Postgres and routing it through Translate mangles the -// $$-quoted function bodies and rewrites now(). Version-stamp queries below use -// native $n placeholders for the same reason. -// -// All work runs on a single connection whose search_path is pinned to the target -// schema, so DDL never silently lands in public when db is handed unpinned. The -// schema name is validated (not parameterizable in DDL) and every DDL statement -// is executed on its own, since pgx's extended protocol rejects multiple -// statements in a single Exec. -func InitSchema(ctx context.Context, db *sql.DB, schema string) error { - if !schemaNameRe.MatchString(schema) { - return fmt.Errorf("postgres: invalid schema name %q", schema) - } - conn, err := db.Conn(ctx) - if err != nil { - return fmt.Errorf("postgres: acquire connection: %w", err) - } - defer conn.Close() - - // InitSchema runs on EVERY open and re-applies idempotent DDL (CREATE OR - // REPLACE FUNCTION, CREATE INDEX IF NOT EXISTS, ...). Idempotent is not the - // same as concurrency-safe: concurrent opens rewriting the same pg catalog - // tuples collide with "tuple concurrently updated" (SQLSTATE XX000). When a - // gc controller drives this store, the dispatcher, session reconciler, and - // agent subprocesses open bd concurrently, so the race is routine and it - // surfaces as spurious bd failures (e.g. the reconciler's assigned-work probe - // failing and orphan-draining live sessions). Serialize DDL application per - // schema with a session advisory lock so only one initializer touches the - // catalog at a time; distinct schemas hash to distinct keys and never block - // each other. Held on this connection and released before it returns to the - // pool. - lockKey := schemaAdvisoryLockKey(schema) - if _, err := conn.ExecContext(ctx, `SELECT pg_advisory_lock($1)`, lockKey); err != nil { - return fmt.Errorf("postgres: acquire schema-init advisory lock: %w", err) - } - // The unlock must run even when ctx is already canceled: with a done ctx, - // database/sql returns before touching the driver, the connection goes back - // to the pool healthy, and its backend session keeps holding the advisory - // lock — wedging every later open of this schema. WithoutCancel guarantees - // the unlock is attempted; if it fails on the wire instead, the driver marks - // the connection bad, the backend session dies with it, and Postgres releases - // the lock anyway, so the error is safe to drop. - defer func() { - _, _ = conn.ExecContext(context.WithoutCancel(ctx), `SELECT pg_advisory_unlock($1)`, lockKey) - }() - - if _, err := conn.ExecContext(ctx, `CREATE SCHEMA IF NOT EXISTS "`+schema+`"`); err != nil { - return fmt.Errorf("postgres: create schema %q: %w", schema, err) - } - if _, err := conn.ExecContext(ctx, `SET search_path TO "`+schema+`"`); err != nil { - return fmt.Errorf("postgres: set search_path %q: %w", schema, err) - } - for _, stmt := range splitStatements(ddl) { - if _, err := conn.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("postgres: exec DDL statement: %w\n-- statement:\n%s", err, stmt) - } - } - fresh, err := stampSchemaVersion(ctx, conn) - if err != nil { - return err - } - // Seed the default config rows ONLY on first provision — exactly like Dolt's - // migration 0016, which runs once. InitSchema runs on EVERY open (NewFromConfig → - // Provision → InitSchema) for idempotency, so seeding unconditionally would - // resurrect any config key a user has `config unset`, diverging from Dolt. - if fresh { - if err := seedDefaultConfig(ctx, conn); err != nil { - return err - } - } - return nil -} - -// defaultConfigSeeds mirrors internal/storage/schema/migrations/0016_default_config.up.sql -// exactly — the config rows a fresh Dolt workspace materializes on init. Seeding the -// identical set (and no more) keeps `bd config list` byte-identical to the Dolt oracle; -// on Dolt these land via a migration, which the wedge does not run, so InitSchema seeds -// them directly. issue_prefix is intentionally absent: it is workspace-specific and the -// caller (bd init) seeds it via store.SetConfig, matching the Dolt path. -var defaultConfigSeeds = [][2]string{ - {"compaction_enabled", "false"}, - {"compact_tier1_days", "30"}, - {"compact_tier1_dep_levels", "2"}, - {"compact_tier2_days", "90"}, - {"compact_tier2_dep_levels", "5"}, - {"compact_tier2_commits", "100"}, - {"compact_batch_size", "50"}, - {"compact_parallel_workers", "5"}, - {"auto_compact_enabled", "false"}, -} - -// seedDefaultConfig inserts the migration-0016 default config rows using -// ON CONFLICT DO NOTHING (the Postgres equivalent of the migration's INSERT IGNORE). -// InitSchema calls it only on first provision; the ON CONFLICT guard additionally -// makes it safe against a concurrent first init. Runs on the search_path-pinned -// connection so it targets the workspace config table. -func seedDefaultConfig(ctx context.Context, conn *sql.Conn) error { - for _, kv := range defaultConfigSeeds { - if _, err := conn.ExecContext(ctx, - `INSERT INTO config (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`, - kv[0], kv[1]); err != nil { - return fmt.Errorf("postgres: seed default config %q: %w", kv[0], err) - } - } - return nil -} - -// stampSchemaVersion records schemaVersion in the metadata table on first init -// and refuses to open a workspace written by a binary with a different schema -// version (the proof-wedge has no migrator). It returns fresh=true only when it -// stamped a brand-new schema (no version row yet) — the signal InitSchema uses to -// seed one-time data exactly once. Runs on the search_path-pinned connection so it -// resolves the workspace metadata table. -func stampSchemaVersion(ctx context.Context, conn *sql.Conn) (fresh bool, err error) { - var stored string - err = conn.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key = $1`, schemaVersionKey).Scan(&stored) - switch { - case errors.Is(err, sql.ErrNoRows): - // Provision runs on every open, so concurrent first opens of the same - // workspace (e.g. the hosted server from two goroutines) can both land - // here. ON CONFLICT DO NOTHING lets both succeed; only the opener that - // actually inserted the row (RowsAffected==1) is fresh and seeds defaults. - res, ierr := conn.ExecContext(ctx, `INSERT INTO metadata (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`, schemaVersionKey, schemaVersion) - if ierr != nil { - return false, fmt.Errorf("postgres: stamp schema version: %w", ierr) - } - if n, _ := res.RowsAffected(); n == 1 { - return true, nil - } - // Lost the race: re-read what the winner stored and version-check it. - if rerr := conn.QueryRowContext(ctx, `SELECT value FROM metadata WHERE key = $1`, schemaVersionKey).Scan(&stored); rerr != nil { - return false, fmt.Errorf("postgres: read schema version after conflict: %w", rerr) - } - if stored != schemaVersion { - return false, fmt.Errorf("postgres: workspace schema version %s, this binary requires %s — no migrator in the proof-wedge, recreate the workspace or use a matching binary", stored, schemaVersion) - } - return false, nil - case err != nil: - return false, fmt.Errorf("postgres: read schema version: %w", err) - case stored != schemaVersion: - return false, fmt.Errorf("postgres: workspace schema version %s, this binary requires %s — no migrator in the proof-wedge, recreate the workspace or use a matching binary", stored, schemaVersion) - default: - return false, nil - } -} - -// splitStatements splits the DDL into individual statements on top-level ';' -// boundaries. It ignores ';' that appears inside a $$-delimited body (the -// trigger function), inside a single-quoted string literal, or inside a '--' -// line comment; line comments are dropped so a ';' in prose never terminates a -// statement. Blank fragments are omitted. -func splitStatements(ddl string) []string { - var stmts []string - var buf strings.Builder - var inString, inDollar bool - n := len(ddl) - for i := 0; i < n; i++ { - c := ddl[i] - switch { - case inString: - buf.WriteByte(c) - if c == '\'' { - if i+1 < n && ddl[i+1] == '\'' { - buf.WriteByte(ddl[i+1]) - i++ - continue - } - inString = false - } - case inDollar: - if c == '$' && i+1 < n && ddl[i+1] == '$' { - buf.WriteString("$$") - inDollar = false - i++ - continue - } - buf.WriteByte(c) - default: - switch { - case c == '-' && i+1 < n && ddl[i+1] == '-': - for i < n && ddl[i] != '\n' { - i++ - } - // Leave i at the newline (or end); the loop's i++ advances past it. - case c == '$' && i+1 < n && ddl[i+1] == '$': - buf.WriteString("$$") - inDollar = true - i++ - case c == '\'': - inString = true - buf.WriteByte(c) - case c == ';': - if s := strings.TrimSpace(buf.String()); s != "" { - stmts = append(stmts, s) - } - buf.Reset() - default: - buf.WriteByte(c) - } - } - } - if s := strings.TrimSpace(buf.String()); s != "" { - stmts = append(stmts, s) - } - return stmts -} diff --git a/internal/storage/postgres/schema_test.go b/internal/storage/postgres/schema_test.go deleted file mode 100644 index 20f1abc34..000000000 --- a/internal/storage/postgres/schema_test.go +++ /dev/null @@ -1,155 +0,0 @@ -package postgres - -import ( - "context" - "database/sql" - "fmt" - "os" - "sync" - "testing" - "time" - - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -// TestInitSchema applies the embedded DDL into a throwaway schema on a live -// Postgres and asserts the core tables materialize. It is gated on -// BEADS_PG_TEST_URL (a pgx-parseable DSN) and skips otherwise. -func TestInitSchema(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set; skipping Postgres schema test") - } - - schema := fmt.Sprintf("bd_schema_test_%d", time.Now().UnixNano()) - - // DDL runs over a RAW (non-translating) DB; assertions below use ? bindings - // and so need the translating DB. - raw, err := pgdialect.OpenRaw(url, schema) - if err != nil { - t.Fatalf("openraw: %v", err) - } - db, err := pgdialect.Open(url, schema) - if err != nil { - t.Fatalf("open: %v", err) - } - // Registered first so they run last (cleanups are LIFO): the schema drop - // below still has open connections when it runs. - t.Cleanup(func() { _ = raw.Close() }) - t.Cleanup(func() { _ = db.Close() }) - - ctx := context.Background() - - if err := InitSchema(ctx, raw, schema); err != nil { - t.Fatalf("InitSchema: %v", err) - } - t.Cleanup(func() { - if _, err := db.ExecContext(ctx, `DROP SCHEMA IF EXISTS "`+schema+`" CASCADE`); err != nil { - t.Errorf("drop schema %q: %v", schema, err) - } - }) - - for _, table := range []string{"issues", "dependencies"} { - if !tableExists(ctx, t, db, schema, table) { - t.Errorf("expected table %q to exist in schema %q", table, schema) - } - } -} - -func tableExists(ctx context.Context, t *testing.T, db *sql.DB, schema, table string) bool { - t.Helper() - var count int - err := db.QueryRowContext(ctx, - `SELECT count(*) FROM information_schema.tables WHERE table_schema = ? AND table_name = ?`, - schema, table).Scan(&count) - if err != nil { - t.Fatalf("query information_schema.tables for %q: %v", table, err) - } - return count > 0 -} - -// TestSchemaAdvisoryLockKey pins the advisory-lock key derivation. The key is a -// cross-process contract: every bd binary that opens the same workspace schema -// must derive the same key, or their InitSchema calls stop serializing against -// each other. The golden values fail loudly if the hash, prefix, or truncation -// ever changes — such a change would silently break lock interop with -// already-deployed binaries during a rolling upgrade. -func TestSchemaAdvisoryLockKey(t *testing.T) { - golden := map[string]int64{ - "beads": -7207352757236036547, - "public": -3420031902527778135, - } - for schema, want := range golden { - if got := schemaAdvisoryLockKey(schema); got != want { - t.Errorf("schemaAdvisoryLockKey(%q) = %d, want %d — changing the derivation breaks locking against deployed binaries", schema, got, want) - } - } - if a, b := schemaAdvisoryLockKey("workspace_a"), schemaAdvisoryLockKey("workspace_b"); a == b { - t.Errorf("distinct schemas derived the same advisory-lock key %d; per-workspace inits must not serialize against each other", a) - } -} - -// TestInitSchemaConcurrentOpens is the regression test for the catalog race the -// advisory lock fixes: InitSchema runs on EVERY open and re-applies idempotent -// DDL, and bd is a short-lived CLI, so a busy deployment runs many concurrent -// opens. Without per-schema serialization those opens rewrite the same pg -// catalog tuples and fail with "tuple concurrently updated" (SQLSTATE XX000). -// Each worker gets its own *sql.DB pool — its own backend session — to mimic -// separate bd processes, and all hammer InitSchema on the same fresh schema. -// Gated on BEADS_PG_TEST_URL like TestInitSchema. -func TestInitSchemaConcurrentOpens(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set; skipping Postgres schema test") - } - - schema := fmt.Sprintf("bd_schema_race_%d", time.Now().UnixNano()) - ctx := context.Background() - - const workers = 8 - const opensPerWorker = 3 - - dbs := make([]*sql.DB, workers) - for i := range dbs { - raw, err := pgdialect.OpenRaw(url, schema) - if err != nil { - t.Fatalf("openraw %d: %v", i, err) - } - dbs[i] = raw - } - // Registered first so it runs last (cleanups are LIFO): the schema drop - // below still has open pools when it runs. - t.Cleanup(func() { - for _, db := range dbs { - _ = db.Close() - } - }) - t.Cleanup(func() { - if _, err := dbs[0].ExecContext(ctx, `DROP SCHEMA IF EXISTS "`+schema+`" CASCADE`); err != nil { - t.Errorf("drop schema %q: %v", schema, err) - } - }) - - start := make(chan struct{}) - errs := make(chan error, workers) - var wg sync.WaitGroup - for i := 0; i < workers; i++ { - wg.Add(1) - go func(db *sql.DB) { - defer wg.Done() - <-start - for j := 0; j < opensPerWorker; j++ { - if err := InitSchema(ctx, db, schema); err != nil { - errs <- err - return - } - } - }(dbs[i]) - } - close(start) - wg.Wait() - close(errs) - for err := range errs { - t.Errorf("concurrent InitSchema: %v", err) - } -} diff --git a/internal/storage/postgres/seed_test.go b/internal/storage/postgres/seed_test.go deleted file mode 100644 index a82fe1bc6..000000000 --- a/internal/storage/postgres/seed_test.go +++ /dev/null @@ -1,57 +0,0 @@ -package postgres - -import ( - "context" - "fmt" - "os" - "testing" - "time" - - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -// TestSeedOnlyOnFirstProvision is the config_unset_seeded_roundtrip regression: the -// bts-rs differential oracle caught that seeding default config on EVERY open (InitSchema -// runs per NewFromConfig/Provision) resurrected any key a user had `config unset`. Seeding -// must happen only on the first provision, like Dolt's one-shot migration 0016. -func TestSeedOnlyOnFirstProvision(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set; skipping live Postgres seed test") - } - schema := fmt.Sprintf("seedonce_%d", time.Now().UnixNano()) - ctx := context.Background() - t.Cleanup(func() { - if raw, err := pgdialect.OpenRaw(url, "public"); err == nil { - _, _ = raw.ExecContext(context.Background(), fmt.Sprintf(`DROP SCHEMA IF EXISTS %q CASCADE`, schema)) - _ = raw.Close() - } - }) - - st, err := Provision(ctx, url, schema) - if err != nil { - t.Fatalf("Provision: %v", err) - } - // First provision seeds the default config rows. - if v, _ := st.GetConfig(ctx, "auto_compact_enabled"); v != "false" { - t.Fatalf("first provision: want seeded auto_compact_enabled=false, got %q", v) - } - // User unsets a seeded key. - if err := st.DeleteConfig(ctx, "auto_compact_enabled"); err != nil { - t.Fatalf("DeleteConfig: %v", err) - } - if v, _ := st.GetConfig(ctx, "auto_compact_enabled"); v != "" { - t.Fatalf("after unset: want empty, got %q", v) - } - _ = st.Close() - - // Re-open the SAME schema — InitSchema runs again. The unset key must STAY unset. - st2, err := Provision(ctx, url, schema) - if err != nil { - t.Fatalf("re-Provision: %v", err) - } - defer st2.Close() - if v, _ := st2.GetConfig(ctx, "auto_compact_enabled"); v != "" { - t.Fatalf("REGRESSION: re-provision resurrected an unset key: auto_compact_enabled=%q (want empty)", v) - } -} diff --git a/internal/storage/postgres/smoke_test.go b/internal/storage/postgres/smoke_test.go deleted file mode 100644 index 065c1eb5c..000000000 --- a/internal/storage/postgres/smoke_test.go +++ /dev/null @@ -1,104 +0,0 @@ -package postgres - -import ( - "context" - "fmt" - "os" - "testing" - "time" - - "github.com/steveyegge/beads/internal/storage/pgdialect" - "github.com/steveyegge/beads/internal/types" -) - -// TestPGSmoke drives the full stack — dialect translation + issueops delegation -// + the synchronous readiness strategy — against a live Postgres. It proves the -// wedge actually runs, not just compiles. Gated on BEADS_PG_TEST_URL. -func TestPGSmoke(t *testing.T) { - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - t.Skip("BEADS_PG_TEST_URL not set; skipping live Postgres smoke") - } - schema := fmt.Sprintf("smoke_%d", time.Now().UnixNano()) - ctx := context.Background() - - st, err := New(ctx, Config{DSN: url, Schema: schema}) - if err != nil { - t.Fatalf("New: %v", err) - } - defer st.Close() - // Schema DDL must run over a raw (non-translating) DB; st.DB() is the - // translating one used for the actual issueops workload below. - raw, err := pgdialect.OpenRaw(url, schema) - if err != nil { - t.Fatalf("OpenRaw: %v", err) - } - if err := InitSchema(ctx, raw, schema); err != nil { - _ = raw.Close() - t.Fatalf("InitSchema: %v", err) - } - _ = raw.Close() - t.Cleanup(func() { - _, _ = st.DB().ExecContext(context.Background(), fmt.Sprintf(`DROP SCHEMA IF EXISTS %q CASCADE`, schema)) - }) - - if err := st.SetConfig(ctx, "issue_prefix", "smoke"); err != nil { - t.Fatalf("SetConfig: %v", err) - } - - mk := func(id, title string) { - iss := &types.Issue{ - ID: id, Title: title, IssueType: types.IssueType("task"), - Status: types.Status("open"), Priority: 2, CreatedBy: "tester", - } - if err := st.CreateIssue(ctx, iss, "tester"); err != nil { - t.Fatalf("CreateIssue(%s): %v", id, err) - } - } - mk("smoke-1", "first") - mk("smoke-2", "second") - - got, err := st.GetIssue(ctx, "smoke-1") - if err != nil || got == nil { - t.Fatalf("GetIssue(smoke-1): %v (got=%v)", err, got) - } - if got.Title != "first" { - t.Fatalf("GetIssue title = %q, want %q", got.Title, "first") - } - - readyIDs := func() []string { - rows, err := st.GetReadyWork(ctx, types.WorkFilter{}) - if err != nil { - t.Fatalf("GetReadyWork: %v", err) - } - ids := make([]string, len(rows)) - for i, r := range rows { - ids[i] = r.ID - } - return ids - } - - // Both open, no deps -> both ready. - if ids := readyIDs(); len(ids) != 2 { - t.Fatalf("before dep: ready=%v, want 2", ids) - } - - // smoke-2 depends on (is blocked by) smoke-1. - dep := &types.Dependency{IssueID: "smoke-2", DependsOnID: "smoke-1", Type: types.DependencyType("blocks"), CreatedBy: "tester"} - if err := st.AddDependency(ctx, dep, "tester"); err != nil { - t.Fatalf("AddDependency: %v", err) - } - - // Now only smoke-1 is ready (readiness projection ran in-tx). - if ids := readyIDs(); len(ids) != 1 || ids[0] != "smoke-1" { - t.Fatalf("after dep: ready=%v, want [smoke-1]", ids) - } - - // Close smoke-1 -> smoke-2 unblocks. - if err := st.CloseIssue(ctx, "smoke-1", "done", "tester", ""); err != nil { - t.Fatalf("CloseIssue: %v", err) - } - if ids := readyIDs(); len(ids) != 1 || ids[0] != "smoke-2" { - t.Fatalf("after close: ready=%v, want [smoke-2]", ids) - } -} diff --git a/internal/storage/postgres/store.go b/internal/storage/postgres/store.go deleted file mode 100644 index 9304023b6..000000000 --- a/internal/storage/postgres/store.go +++ /dev/null @@ -1,87 +0,0 @@ -// Package postgres is the Postgres backend for bd: the shared sqlkit.Store -// bundled with the Postgres dialect and a readiness strategy, plus the non-Dolt -// markers. It is a strategy bundle over the shared SQL-family implementation — -// no storage semantics are re-derived here. -package postgres - -import ( - "context" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/sqlkit" -) - -// Backend is the metadata.json backend identifier for this store. -const Backend = "postgres" - -// Store is the Postgres backend. It embeds *sqlkit.Store, so it inherits every -// core method and overrides only what Postgres specializes (nothing yet — the -// readiness projection and FOR UPDATE SKIP LOCKED claim are later strategy -// swaps that override GetReadyWork/ClaimReadyIssue without touching sqlkit). -type Store struct { - *sqlkit.Store - // unsupportedDoltStorage (generated, unsupported_gen.go) provides the - // capability surface Postgres does not implement — VC/history/remote/sync/ - // compaction/federation and a few non-demo core methods — each returning a - // typed *storage.ErrUnsupported. It is generated as the exact complement of - // *sqlkit.Store's method set, so there is no ambiguous-selector overlap. - unsupportedDoltStorage -} - -// Compile-time guard on the generated skip list: the composite backend (real -// *sqlkit.Store methods plus the typed-unsupported shell) must fully satisfy -// storage.DoltStorage. This fails the build on skip-list drift — a skipped -// method sqlkit does not actually implement (missing method), or a method both -// implemented and stubbed (ambiguous selector) — so no method can silently -// become "unsupported". -var _ storage.DoltStorage = (*Store)(nil) - -// Config configures a Postgres backend. -type Config struct { - DSN string // password merged from env at open; never persisted to metadata.json - Schema string // per-workspace schema, pinned via search_path -} - -// New builds the Postgres backend from its strategy bundle: the pg dialect -// (translating driver) and a no-op readiness strategy (the shared issueops -// helpers already maintain is_blocked targeted and in-transaction, matching the -// Dolt reference; SyncReadiness would only add a redundant per-write recompute). -func New(ctx context.Context, cfg Config) (*Store, error) { - base, err := sqlkit.New(ctx, sqlkit.Config{ - Dialect: pgDialect{dsn: cfg.DSN, searchPath: cfg.Schema}, - Readiness: sqlkit.NoopReadiness{}, - }) - if err != nil { - return nil, err - } - return &Store{Store: base}, nil -} - -// CommitGraphUnsupported is the negative maintenance marker (see -// storage.NonCommitGraphBackend): it tells cmd/bd's PostRun to skip Dolt-only -// maintenance. Only non-Dolt backends implement it, so the default path is -// unaffected. -func (s *Store) CommitGraphUnsupported() bool { return true } - -// CommitPending is a no-op on a non-version-controlled backend; write paths -// invoke it opportunistically and must not error. -func (s *Store) CommitPending(_ context.Context, _ string) (bool, error) { - return false, nil -} - -// Commit and its variants are no-ops on Postgres, NOT unsupported: a Dolt -// "commit" flushes the working set to history, but every sqlkit write already -// committed its own SQL transaction, so the data is durable. Command paths call -// store.Commit() opportunistically after writes; returning nil lets those writes -// stand instead of erroring on a history operation that has no PG meaning. -func (s *Store) Commit(_ context.Context, _ string) error { return nil } -func (s *Store) CommitWithConfig(_ context.Context, _ string) error { return nil } -func (s *Store) CommitMergeResolution(_ context.Context, _ string) error { return nil } - -// Compile-time proof the Postgres backend satisfies the full storage seam -// (core methods via *sqlkit.Store, the rest via the generated shell) and the -// negative maintenance marker. -var ( - _ storage.DoltStorage = (*Store)(nil) - _ storage.NonCommitGraphBackend = (*Store)(nil) -) diff --git a/internal/storage/postgres/unsupported.go b/internal/storage/postgres/unsupported.go deleted file mode 100644 index 6d1e45ae8..000000000 --- a/internal/storage/postgres/unsupported.go +++ /dev/null @@ -1,24 +0,0 @@ -package postgres - -import ( - "github.com/steveyegge/beads/internal/storage" -) - -// Regeneration: the postgres shell is the exact complement of *sqlkit.Store's -// method set. Regenerate unsupported_gen.go with the directive below after -// finalizing the skip list (the sqlkit-implemented ops — the integrator fills -// in ). gen's strict unmatched-skip validation then doubles as a drift -// tripwire against DoltStorage interface changes. -// -//go:generate go run ../unsupportedgen -pkg postgres -src .. -out unsupported_gen.go -type DoltStorage -skip AddDependency,AddIssueComment,AddLabel,ClaimIssue,ClaimReadyIssue,Close,CloseIssue,Commit,CommitMergeResolution,CommitPending,CommitWithConfig,CountDependencies,CountDependents,CountEvents,CountIssueComments,CountIssues,CountIssuesByGroup,CreateIssue,CreateIssues,DeleteConfig,DeleteIssue,DeleteIssues,DetectCycles,GetAllConfig,GetBlockedIssues,GetBlockingInfoForIssues,GetCommentCounts,GetCommentsForIssues,GetConfig,GetCustomStatuses,GetCustomStatusesDetailed,GetCustomTypes,GetDependencies,GetDependenciesWithMetadata,GetDependencyCounts,GetDependencyRecords,GetDependencyRecordsForIssues,GetDependencyTree,GetDependents,GetDependentsWithMetadata,GetEpicsEligibleForClosure,GetEvents,GetInfraTypes,GetIssue,GetIssueByExternalRef,GetIssueComments,GetIssuesByIDs,GetIssuesByLabel,GetLabels,GetLabelsForIssues,GetLocalMetadata,GetMetadata,GetNewlyUnblockedByClose,GetNextChildID,GetReadyWork,GetReadyWorkWithCounts,GetStaleIssues,GetStatistics,IsBlocked,IsInfraTypeCtx,IterBlockedIssues,IterDependenciesWithMetadata,IterDependentsWithMetadata,IterEvents,IterIssueComments,IterIssues,IterReadyWork,IterWisps,ListWisps,RemoveDependency,RemoveLabel,ReopenIssue,RunInTransaction,SearchIssues,SearchIssuesWithCounts,SetConfig,SetLocalMetadata,SetMetadata,UpdateIssue,UpdateIssueType,AddComment,ClearRepoMtime,CountDependentsByStatus,DeleteIssuesBySourceRepo,FindWispDependentsRecursive,GetAllDependencyRecords,GetAllEventsSince,GetMoleculeLastActivity,GetMoleculeProgress,GetRepoMtime,ImportIssueComment,IterAllDependencyRecords,IterAllEventsSince,PromoteFromEphemeral,SetRepoMtime,UpdateIssueID,CreateIssuesWithFullOptions,SlotClear,SlotGet,SlotSet,SearchIssueIDs,HeartbeatIssue,ReclaimExpiredLeases,UnclaimIssue - -// errUnsupported is the constructor every generated stub in unsupported_gen.go -// calls. It returns the backend-agnostic *storage.ErrUnsupported sentinel, whose -// Error() renders `operation %q not supported by the %s backend`. That message is -// correct for every stubbed op — the shell also stubs non-VC core methods -// (GetStatistics, DeleteIssues, ...) that a Dolt backend is not the remedy for — -// so it carries no history/version-control hint. Backend is the package const -// "postgres"; callers can errors.As/Is on the returned sentinel. -func errUnsupported(op string) error { - return &storage.ErrUnsupported{Op: op, Backend: Backend} -} diff --git a/internal/storage/postgres/unsupported_gen.go b/internal/storage/postgres/unsupported_gen.go deleted file mode 100644 index ce228433e..000000000 --- a/internal/storage/postgres/unsupported_gen.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by gen (postgres typed-unsupported shell); DO NOT EDIT. - -package postgres - -import ( - "context" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/types" -) - -// unsupportedDoltStorage is the generated typed-unsupported shell for storage.DoltStorage. -// Every method returns *storage.ErrUnsupported; embed it and override the -// real slice. DO NOT hand-edit — regenerate with `go generate ./...`. -type unsupportedDoltStorage struct{} - -func (unsupportedDoltStorage) MergeSlotCreate(_ context.Context, _ string) (_ *types.Issue, err error) { - err = errUnsupported("MergeSlotCreate") - return -} - -func (unsupportedDoltStorage) MergeSlotCheck(_ context.Context) (_ *storage.MergeSlotStatus, err error) { - err = errUnsupported("MergeSlotCheck") - return -} - -func (unsupportedDoltStorage) MergeSlotAcquire(_ context.Context, _ string, _ string, _ bool) (_ *storage.MergeSlotResult, err error) { - err = errUnsupported("MergeSlotAcquire") - return -} - -func (unsupportedDoltStorage) MergeSlotRelease(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("MergeSlotRelease") - return -} - -func (unsupportedDoltStorage) Branch(_ context.Context, _ string) (err error) { - err = errUnsupported("Branch") - return -} - -func (unsupportedDoltStorage) Checkout(_ context.Context, _ string) (err error) { - err = errUnsupported("Checkout") - return -} - -func (unsupportedDoltStorage) CurrentBranch(_ context.Context) (_ string, err error) { - err = errUnsupported("CurrentBranch") - return -} - -func (unsupportedDoltStorage) DeleteBranch(_ context.Context, _ string) (err error) { - err = errUnsupported("DeleteBranch") - return -} - -func (unsupportedDoltStorage) ListBranches(_ context.Context) (_ []string, err error) { - err = errUnsupported("ListBranches") - return -} - -func (unsupportedDoltStorage) CommitExists(_ context.Context, _ string) (_ bool, err error) { - err = errUnsupported("CommitExists") - return -} - -func (unsupportedDoltStorage) GetCurrentCommit(_ context.Context) (_ string, err error) { - err = errUnsupported("GetCurrentCommit") - return -} - -func (unsupportedDoltStorage) Status(_ context.Context) (_ *storage.Status, err error) { - err = errUnsupported("Status") - return -} - -func (unsupportedDoltStorage) Log(_ context.Context, _ int) (_ []storage.CommitInfo, err error) { - err = errUnsupported("Log") - return -} - -func (unsupportedDoltStorage) Merge(_ context.Context, _ string) (_ []storage.Conflict, err error) { - err = errUnsupported("Merge") - return -} - -func (unsupportedDoltStorage) GetConflicts(_ context.Context) (_ []storage.Conflict, err error) { - err = errUnsupported("GetConflicts") - return -} - -func (unsupportedDoltStorage) ResolveConflicts(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("ResolveConflicts") - return -} - -func (unsupportedDoltStorage) History(_ context.Context, _ string) (_ []*storage.HistoryEntry, err error) { - err = errUnsupported("History") - return -} - -func (unsupportedDoltStorage) AsOf(_ context.Context, _ string, _ string) (_ *types.Issue, err error) { - err = errUnsupported("AsOf") - return -} - -func (unsupportedDoltStorage) Diff(_ context.Context, _ string, _ string) (_ []*storage.DiffEntry, err error) { - err = errUnsupported("Diff") - return -} - -func (unsupportedDoltStorage) AddRemote(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("AddRemote") - return -} - -func (unsupportedDoltStorage) RemoveRemote(_ context.Context, _ string) (err error) { - err = errUnsupported("RemoveRemote") - return -} - -func (unsupportedDoltStorage) HasRemote(_ context.Context, _ string) (_ bool, err error) { - err = errUnsupported("HasRemote") - return -} - -func (unsupportedDoltStorage) ListRemotes(_ context.Context) (_ []storage.RemoteInfo, err error) { - err = errUnsupported("ListRemotes") - return -} - -func (unsupportedDoltStorage) Push(_ context.Context) (err error) { - err = errUnsupported("Push") - return -} - -func (unsupportedDoltStorage) Pull(_ context.Context) (err error) { - err = errUnsupported("Pull") - return -} - -func (unsupportedDoltStorage) ForcePush(_ context.Context) (err error) { - err = errUnsupported("ForcePush") - return -} - -func (unsupportedDoltStorage) PushRemote(_ context.Context, _ string, _ bool) (err error) { - err = errUnsupported("PushRemote") - return -} - -func (unsupportedDoltStorage) PullRemote(_ context.Context, _ string) (err error) { - err = errUnsupported("PullRemote") - return -} - -func (unsupportedDoltStorage) Fetch(_ context.Context, _ string) (err error) { - err = errUnsupported("Fetch") - return -} - -func (unsupportedDoltStorage) PushTo(_ context.Context, _ string) (err error) { - err = errUnsupported("PushTo") - return -} - -func (unsupportedDoltStorage) PullFrom(_ context.Context, _ string) (_ []storage.Conflict, err error) { - err = errUnsupported("PullFrom") - return -} - -func (unsupportedDoltStorage) Sync(_ context.Context, _ string, _ string) (_ *storage.SyncResult, err error) { - err = errUnsupported("Sync") - return -} - -func (unsupportedDoltStorage) SyncStatus(_ context.Context, _ string) (_ *storage.SyncStatus, err error) { - err = errUnsupported("SyncStatus") - return -} - -func (unsupportedDoltStorage) AddFederationPeer(_ context.Context, _ *storage.FederationPeer) (err error) { - err = errUnsupported("AddFederationPeer") - return -} - -func (unsupportedDoltStorage) GetFederationPeer(_ context.Context, _ string) (_ *storage.FederationPeer, err error) { - err = errUnsupported("GetFederationPeer") - return -} - -func (unsupportedDoltStorage) ListFederationPeers(_ context.Context) (_ []*storage.FederationPeer, err error) { - err = errUnsupported("ListFederationPeers") - return -} - -func (unsupportedDoltStorage) RemoveFederationPeer(_ context.Context, _ string) (err error) { - err = errUnsupported("RemoveFederationPeer") - return -} - -func (unsupportedDoltStorage) CheckEligibility(_ context.Context, _ string, _ int) (_ bool, _ string, err error) { - err = errUnsupported("CheckEligibility") - return -} - -func (unsupportedDoltStorage) ApplyCompaction(_ context.Context, _ string, _ int, _ int, _ int, _ string) (err error) { - err = errUnsupported("ApplyCompaction") - return -} - -func (unsupportedDoltStorage) GetTier1Candidates(_ context.Context) (_ []*types.CompactionCandidate, err error) { - err = errUnsupported("GetTier1Candidates") - return -} - -func (unsupportedDoltStorage) GetTier2Candidates(_ context.Context) (_ []*types.CompactionCandidate, err error) { - err = errUnsupported("GetTier2Candidates") - return -} - -func (unsupportedDoltStorage) SnapshotIssue(_ context.Context, _ string, _ int) (err error) { - err = errUnsupported("SnapshotIssue") - return -} - -func (unsupportedDoltStorage) GetCompactionSnapshot(_ context.Context, _ string) (_ *types.IssueSnapshot, err error) { - err = errUnsupported("GetCompactionSnapshot") - return -} - -func (unsupportedDoltStorage) RestoreFromSnapshot(_ context.Context, _ string) (_ *types.IssueSnapshot, err error) { - err = errUnsupported("RestoreFromSnapshot") - return -} - -// NOTE: partial shell (104 methods skipped); the embedding composite must assert storage.DoltStorage itself. diff --git a/internal/storage/sqlbuild/sort.go b/internal/storage/sqlbuild/sort.go index 53bfd7825..755b7b576 100644 --- a/internal/storage/sqlbuild/sort.go +++ b/internal/storage/sqlbuild/sort.go @@ -70,11 +70,9 @@ func OrderByForColumns(sortBy string, sortDesc bool, col func(sortKey string) st if sortBy == "" || sortBy == "priority" { return fmt.Sprintf("ORDER BY %s %s, %s DESC, %s ASC", col("priority"), dir, col("created"), col("id")) } - // A nullable sort column (closed_at, assignee) must order NULLs the MySQL way — NULL - // treated as lowest, so first on ASC and last on DESC — on every backend. MySQL/Dolt/ - // SQLite do this by default; Postgres defaults the opposite way (NULLS FIRST on DESC), - // so lead with an explicit (col IS NULL) key for those two. NOT NULL columns keep the - // plain clause (byte-identical to before). + // A nullable sort column (closed_at, assignee) treats NULL as lowest: first on ASC + // and last on DESC. Lead with an explicit (col IS NULL) key so the contract does not + // depend on a driver's default NULL ordering. NOT NULL columns keep the plain clause. if sortBy == "closed" || sortBy == "assignee" { return fmt.Sprintf("ORDER BY (%s IS NULL) %s, %s %s, %s ASC", col(sortBy), flipDir(dir), col(sortBy), dir, col("id")) } @@ -102,7 +100,7 @@ func OrderBy(sortBy string, sortDesc bool, table string) string { // Less is the Go-side mirror of OrderBy for merge sorts over rows fetched // from separate queries (issues + wisps). It must order exactly the way the -// SQL does, including MySQL NULL-first semantics for nullable columns; +// SQL does, including NULL-first ascending semantics for nullable columns; // otherwise a post-merge limit cut keeps a different row set than SQL // selected. func Less(a, b *types.Issue, sortBy string, sortDesc bool) bool { diff --git a/internal/storage/sqlite/completeness_test.go b/internal/storage/sqlite/completeness_test.go deleted file mode 100644 index 06af61c75..000000000 --- a/internal/storage/sqlite/completeness_test.go +++ /dev/null @@ -1,107 +0,0 @@ -package sqlite - -import ( - "os" - "regexp" - "sort" - "testing" - - "github.com/steveyegge/beads/internal/storage/conformance" -) - -// legitimatelyUnsupported is the EXPLICIT denominator of every storage.DoltStorage -// method the Postgres wedge deliberately does not implement, each with a reason. -// -// The interface-completeness gate (TestInterfaceCompleteness) asserts the -// generated capability shell (unsupported_gen.go) contains EXACTLY these methods -// — no more, no less. This is the guard the red-team had to stand in for: a -// method that silently resolves to the typed-unsupported shell (the class that -// bit us: DeleteIssues, GetCustomStatuses, the batch reads, …) fails this test -// at build time instead of failing a user at runtime. Adding a method to the -// shell without an entry here is a hard error that forces the triage question: -// "implement it in sqlkit, or record here why the wedge legitimately omits it." -var legitimatelyUnsupported = map[string]string{ - // VersionControl — the Dolt commit graph. The wedge's whole premise is - // "bd on Postgres, history/version-control simply absent". - "Branch": "VC: Dolt branch", "Checkout": "VC: Dolt checkout", - "CurrentBranch": "VC", "DeleteBranch": "VC", "ListBranches": "VC", - // Commit/CommitWithConfig/CommitMergeResolution are NO-OPS on Postgres (data - // is already durable per-tx), not unsupported — implemented on postgres.Store. - "CommitExists": "VC", "GetCurrentCommit": "VC: Dolt hash", "Status": "VC", - "Log": "VC: dolt_log", "Merge": "VC", "GetConflicts": "VC", "ResolveConflicts": "VC", - - // HistoryViewer — Dolt time-travel. - "History": "history: dolt_log", "AsOf": "history: as-of ref", "Diff": "history: dolt_diff", - - // RemoteStore — Dolt remotes. - "AddRemote": "remote", "RemoveRemote": "remote", "HasRemote": "remote", "ListRemotes": "remote", - "Push": "remote", "Pull": "remote", "ForcePush": "remote", "PushRemote": "remote", - "PullRemote": "remote", "Fetch": "remote", "PushTo": "remote", "PullFrom": "remote", - - // SyncStore — Dolt peer sync. - "Sync": "sync", "SyncStatus": "sync", - - // FederationStore — Dolt-remote-backed peer table. - "AddFederationPeer": "federation", "GetFederationPeer": "federation", - "ListFederationPeers": "federation", "RemoveFederationPeer": "federation", - - // CompactionStore — bound to Dolt commit hashes. - "CheckEligibility": "compaction", "ApplyCompaction": "compaction", - "GetTier1Candidates": "compaction", "GetTier2Candidates": "compaction", - "SnapshotIssue": "compaction", "GetCompactionSnapshot": "compaction", "RestoreFromSnapshot": "compaction", - - // MergeSlot — the Dolt merge-serialization primitive. - "MergeSlotCreate": "merge-slot", "MergeSlotCheck": "merge-slot", - "MergeSlotAcquire": "merge-slot", "MergeSlotRelease": "merge-slot", -} - -var shellMethodRe = regexp.MustCompile(`func \(unsupportedDoltStorage\) ([A-Za-z0-9]+)\(`) - -// TestInterfaceCompleteness is the interface-completeness gate: the generated -// shell must equal the audited legitimatelyUnsupported set, both directions. -func TestInterfaceCompleteness(t *testing.T) { - src, err := os.ReadFile("unsupported_gen.go") - if err != nil { - t.Fatalf("read unsupported_gen.go: %v", err) - } - shell := map[string]bool{} - for _, m := range shellMethodRe.FindAllStringSubmatch(string(src), -1) { - shell[m[1]] = true - } - if len(shell) == 0 { - t.Fatal("parsed 0 shell methods — regex or file drift") - } - - // (1) No SILENT gap: every shell method must be explicitly justified. - var unjustified []string - for m := range shell { - if _, ok := legitimatelyUnsupported[m]; !ok { - unjustified = append(unjustified, m) - } - } - sort.Strings(unjustified) - for _, m := range unjustified { - t.Errorf("method %q resolves to the typed-unsupported shell but is NOT in legitimatelyUnsupported: implement it on *sqlkit.Store, or add it here with a reason", m) - } - - // (2) No STALE allowlist: every justified method must still be in the shell - // (else it was implemented and the entry should be removed). - var stale []string - for m := range legitimatelyUnsupported { - if !shell[m] { - stale = append(stale, m) - } - } - sort.Strings(stale) - for _, m := range stale { - t.Errorf("method %q is in legitimatelyUnsupported but no longer in the shell (implemented?): remove the allowlist entry", m) - } -} - -// TestUnsupportedContract is the behavioral complement to TestInterfaceCompleteness: -// every allowlisted method must actually return a typed storage.ErrUnsupported when -// called, not panic or return a different error. DB-free — the generated stubs ignore -// their receiver, so a zero-value store answers them. -func TestUnsupportedContract(t *testing.T) { - conformance.RunUnsupportedContract(t, &Store{}, legitimatelyUnsupported) -} diff --git a/internal/storage/sqlite/conformance_test.go b/internal/storage/sqlite/conformance_test.go deleted file mode 100644 index 31b126520..000000000 --- a/internal/storage/sqlite/conformance_test.go +++ /dev/null @@ -1,49 +0,0 @@ -package sqlite - -import ( - "context" - "path/filepath" - "testing" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/conformance" -) - -// TestConformance runs bd's backend-agnostic storage conformance suite against the -// SQLite backend. SQLite is embedded (pure-Go modernc), so it always runs — no env -// gate. Every failure is a SQLite gap: an allowlisted-unsupported method or a latent -// divergence. -func TestConformance(t *testing.T) { - conformance.RunAll(t, sqliteConformanceFactory()) -} - -// TestDeferredReads runs the shared deferred non-version-control reads (statistics, -// external-ref, stale) that the backend now implements through issueops, as a GREEN -// gate. RunAll stays the fail-loud measurement (red on genuinely Dolt-only methods -// like slots), so this focused gate is what conformance.sh runs. -func TestDeferredReads(t *testing.T) { - conformance.RunDeferredReads(t, sqliteConformanceFactory()) -} - -// TestPortableMethods runs the full portable-method behavior contract. Red until the -// methods are wired into sqlkit; green after. -func TestPortableMethods(t *testing.T) { - conformance.RunPortableMethods(t, sqliteConformanceFactory()) -} - -// sqliteConformanceFactory returns a fresh, file-isolated store per sub-test, seeded -// with issue_prefix as `bd init` leaves it. -func sqliteConformanceFactory() conformance.Factory { - return func(t *testing.T) storage.DoltStorage { - ctx := context.Background() - st, err := Provision(ctx, filepath.Join(t.TempDir(), "conf.db")) - if err != nil { - t.Fatalf("Provision: %v", err) - } - if err := st.SetConfig(ctx, "issue_prefix", "test"); err != nil { - t.Fatalf("SetConfig(issue_prefix): %v", err) - } - t.Cleanup(func() { _ = st.Close() }) - return st - } -} diff --git a/internal/storage/sqlite/dialect.go b/internal/storage/sqlite/dialect.go deleted file mode 100644 index ecddd6ef0..000000000 --- a/internal/storage/sqlite/dialect.go +++ /dev/null @@ -1,30 +0,0 @@ -package sqlite - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/sqlitedialect" -) - -// sqliteDialect is the SQLite SQL flavor: it opens a *sql.DB over modernc.org/sqlite -// whose driver translates bd's canonical MySQL SQL to SQLite (small: mainly -// INSERT IGNORE → INSERT OR IGNORE). The dsn already carries the file path + pragmas. -type sqliteDialect struct{ dsn string } - -func (d sqliteDialect) Name() string { return "sqlite" } - -func (d sqliteDialect) Open(_ context.Context) (*sql.DB, error) { - db, err := sqlitedialect.Open(d.dsn) - if err != nil { - return nil, err - } - // SQLite is single-writer. Pin the pool to one connection so overlapping - // operations from parallel workers sharing this *Store serialize in-process - // (waiting on the connection) instead of colliding with a raw SQLITE_BUSY / - // "database is locked" — the same single-connection posture the Dolt backend - // takes (SetMaxOpenConns(1)). Cross-process contention is covered by the DSN's - // busy_timeout + WAL. - db.SetMaxOpenConns(1) - return db, nil -} diff --git a/internal/storage/sqlite/dsn.go b/internal/storage/sqlite/dsn.go deleted file mode 100644 index 50cfd9a03..000000000 --- a/internal/storage/sqlite/dsn.go +++ /dev/null @@ -1,44 +0,0 @@ -package sqlite - -import "strings" - -// dsn builds a modernc.org/sqlite DSN for a database file path. Pragmas: -// - foreign_keys(1): FK enforcement (off by default in SQLite). -// - journal_mode(WAL): readers don't block the writer and vice versa, so a read -// no longer collides with an in-flight write. -// - busy_timeout(5000): on lock contention, wait up to 5s for the lock instead of -// immediately surfacing a raw "database is locked" (SQLITE_BUSY). This is the -// cross-process analog of Dolt's transparent serialization retry; combined with -// the single-connection pool (see sqliteDialect.Open) it covers both intra- and -// inter-process contention. -// - _txlock=immediate: writers take the write lock up front and fail fast rather -// than deadlocking mid-transaction on lock upgrade. -// - case_sensitive_like(1): LIKE parity with the other backends. Dolt/MySQL use -// the utf8mb4_0900_bin table collation and Postgres uses collation "C", so -// `id LIKE 'bd-A%'` is case-sensitive there; SQLite's default LIKE is -// ASCII-case-INsensitive, which silently diverged on raw-cased operands -// (--id-prefix filtering, parent-descendant `id LIKE parent || '.%'`, -// GetNextChildID's child scan). Intentionally case-insensitive searches are -// unaffected: they wrap both sides in LOWER(). _pragma params are applied by -// modernc on EVERY new connection, so the whole pool gets it (bd-oyvc2.10). -// -// _time_format=datetime is required for Dolt parity, not a nicety. Without it modernc -// binds every time.Time through t.String() ("2026-07-09 12:34:56.123 +0000 UTC"), a -// shape SQLite's date functions cannot parse — so the DATE_FORMAT(created_at,…) the -// counts mega-query renders (translated to strftime by sqlitedialect) returns NULL and -// deps_json exposes a zero created_at instead of the real timestamp. datetime stores -// "2026-07-09 12:34:56", which strftime yields as "2026-07-09T12:34:56Z", giving the -// same whole-second GRANULARITY as Dolt/MySQL datetime(0) and unifying bound timestamps -// with the DEFAULT CURRENT_TIMESTAMP rows into one sortable, strftime-parseable format. -// -// Note the granularity matches but the sub-second RULE does not: Go's Format truncates -// the fraction, whereas Dolt/MySQL datetime(0) round half-up (Postgres keeps microseconds). -// This sub-second divergence is an accepted, documented waiver — the portable contract is -// a whole-second round-trip (see conformance.testAuditImportCommentSubSecond); forcing -// round-down parity would only discard the SQL backends' native precision. -func dsn(path string) string { - if strings.HasPrefix(path, "file:") { - return path - } - return "file:" + path + "?_pragma=foreign_keys(1)&_pragma=journal_mode(WAL)&_pragma=busy_timeout(5000)&_pragma=case_sensitive_like(1)&_txlock=immediate&_time_format=datetime" -} diff --git a/internal/storage/sqlite/dsn_test.go b/internal/storage/sqlite/dsn_test.go deleted file mode 100644 index 5961ef285..000000000 --- a/internal/storage/sqlite/dsn_test.go +++ /dev/null @@ -1,32 +0,0 @@ -package sqlite - -import ( - "database/sql" - "path/filepath" - "testing" -) - -// TestDSNCaseSensitiveLike pins the mechanism behind bd-oyvc2.10: dsn() must carry -// _pragma=case_sensitive_like(1), and modernc.org/sqlite must apply it on EVERY new -// connection (DSN _pragma params are per-connection), so raw-cased LIKE matches the -// other backends' case-sensitive collations. The behavioral contract is covered by -// the conformance corpus (Audit/*CaseSensitive); this guards the DSN wiring itself. -func TestDSNCaseSensitiveLike(t *testing.T) { - db, err := sql.Open("sqlite", dsn(filepath.Join(t.TempDir(), "like.db"))) - if err != nil { - t.Fatal(err) - } - defer db.Close() - - // Multiple pooled connections, each of which must have the pragma applied. - db.SetMaxOpenConns(4) - for i := 0; i < 4; i++ { - var v int - if err := db.QueryRow("SELECT 'a' LIKE 'A'").Scan(&v); err != nil { - t.Fatal(err) - } - if v != 0 { - t.Fatalf("'a' LIKE 'A' = %d, want 0 (case-sensitive; SQLite default is ASCII-case-insensitive)", v) - } - } -} diff --git a/internal/storage/sqlite/fromconfig.go b/internal/storage/sqlite/fromconfig.go deleted file mode 100644 index 7b311bf4a..000000000 --- a/internal/storage/sqlite/fromconfig.go +++ /dev/null @@ -1,50 +0,0 @@ -package sqlite - -import ( - "context" - "database/sql" - "fmt" - "path/filepath" - - "github.com/steveyegge/beads/internal/configfile" - "github.com/steveyegge/beads/internal/storage" -) - -// NewFromConfig opens the SQLite backend for a workspace, reading the database file -// path from .beads/metadata.json (default beads.db, relative to the beads dir). SQLite -// is file-based, so there is no DSN password to manage. -func NewFromConfig(ctx context.Context, beadsDir string) (storage.DoltStorage, error) { - cfg, err := configfile.Load(beadsDir) - if err != nil { - return nil, fmt.Errorf("sqlite: load config: %w", err) - } - path := cfg.GetSQLitePath() - if path == "" { - path = "beads.db" - } - if !filepath.IsAbs(path) { - path = filepath.Join(beadsDir, path) - } - return Provision(ctx, path) -} - -// Provision opens the SQLite database file, applies the schema (idempotent; config -// seeds on first provision), and returns the store. bd init calls this directly. -func Provision(ctx context.Context, dbPath string) (storage.DoltStorage, error) { - if dbPath == "" { - return nil, fmt.Errorf("sqlite: empty database path") - } - d := dsn(dbPath) - // DDL and seeds are native SQLite; a raw modernc connection (no translation) runs - // them. The store's own connection goes through the translating dialect. - raw, err := sql.Open("sqlite", d) - if err != nil { - return nil, fmt.Errorf("sqlite: open (raw): %w", err) - } - if err := InitSchema(ctx, raw); err != nil { - _ = raw.Close() - return nil, fmt.Errorf("sqlite: init schema: %w", err) - } - _ = raw.Close() - return New(ctx, Config{DSN: d}) -} diff --git a/internal/storage/sqlite/locking_test.go b/internal/storage/sqlite/locking_test.go deleted file mode 100644 index 9d32b0fa4..000000000 --- a/internal/storage/sqlite/locking_test.go +++ /dev/null @@ -1,129 +0,0 @@ -package sqlite - -import ( - "context" - "fmt" - "path/filepath" - "strings" - "sync" - "testing" - - "github.com/steveyegge/beads/internal/types" -) - -// TestConcurrentAccessNoLockError guards the SQLite locking posture (single-conn -// pool + WAL + busy_timeout in the DSN): overlapping reads and writes from several -// goroutines sharing one *Store must complete without ever surfacing a raw -// "database is locked" (SQLITE_BUSY). Before the pool was pinned to one connection -// and the DSN gained busy_timeout/WAL, `_txlock=immediate` took a RESERVED lock on -// every transaction (reads included) and overlapping operations collided with an -// immediate SQLITE_BUSY. -func TestConcurrentAccessNoLockError(t *testing.T) { - ctx := context.Background() - st, err := Provision(ctx, filepath.Join(t.TempDir(), "lock.db")) - if err != nil { - t.Fatalf("Provision: %v", err) - } - t.Cleanup(func() { _ = st.Close() }) - if err := st.SetConfig(ctx, "issue_prefix", "test"); err != nil { - t.Fatalf("SetConfig(issue_prefix): %v", err) - } - - const workers, perWorker = 8, 15 - var wg sync.WaitGroup - errCh := make(chan error, workers*perWorker*2) - for w := 0; w < workers; w++ { - wg.Add(1) - go func(w int) { - defer wg.Done() - for i := 0; i < perWorker; i++ { - issue := withDefaults(&types.Issue{ID: fmt.Sprintf("test-%d-%d", w, i), Title: "concurrent"}) - if err := st.CreateIssue(ctx, issue, "actor"); err != nil { - errCh <- fmt.Errorf("worker %d create %d: %w", w, i, err) - } - // A read overlapping the other workers' writes: under the old posture - // this could also collide with an immediate SQLITE_BUSY. - if _, err := st.GetReadyWork(ctx, types.WorkFilter{}); err != nil { - errCh <- fmt.Errorf("worker %d ready %d: %w", w, i, err) - } - } - }(w) - } - wg.Wait() - close(errCh) - - for err := range errCh { - if isLockError(err) { - t.Errorf("concurrent access surfaced a lock error: %v", err) - } else { - t.Errorf("unexpected concurrent-access error: %v", err) - } - } -} - -// TestReadConcurrentWithHeldWriteLock guards WAL reader/writer independence -// across separate store handles — the cross-process analog: two bd processes on -// one database file. Handle A holds SQLite's single write lock in an open -// transaction (the DSN's `_txlock=immediate` takes it at BEGIN); a read through -// handle B must still succeed, because under WAL readers never wait on the -// writer. Before withReadTx passed sql.TxOptions{ReadOnly: true}, B's read also -// issued BEGIN IMMEDIATE, queued on the write lock, and surfaced SQLITE_BUSY -// after busy_timeout — so during any long write (e.g. a large import) every -// concurrent read failed, forfeiting WAL's reader concurrency entirely. -func TestReadConcurrentWithHeldWriteLock(t *testing.T) { - ctx := context.Background() - path := filepath.Join(t.TempDir(), "wal-read.db") - stA, err := Provision(ctx, path) - if err != nil { - t.Fatalf("Provision: %v", err) - } - t.Cleanup(func() { _ = stA.Close() }) - if err := stA.SetConfig(ctx, "issue_prefix", "test"); err != nil { - t.Fatalf("SetConfig(issue_prefix): %v", err) - } - - // Second, independent handle (own pool/connection) on the same file. - stB, err := New(ctx, Config{DSN: dsn(path)}) - if err != nil { - t.Fatalf("New (second handle): %v", err) - } - t.Cleanup(func() { _ = stB.Close() }) - - // Hold the write lock on A: with _txlock=immediate, BeginTx issues BEGIN - // IMMEDIATE. The uncommitted INSERT makes it a real in-flight write. - writeTx, err := stA.(*Store).DB().BeginTx(ctx, nil) - if err != nil { - t.Fatalf("begin write tx on handle A: %v", err) - } - defer func() { _ = writeTx.Rollback() }() - if _, err := writeTx.ExecContext(ctx, - "INSERT INTO metadata (key, value) VALUES ('lock_probe', 'held')"); err != nil { - t.Fatalf("write inside held tx: %v", err) - } - - // The read on B must complete while A's write transaction is still open. - got, err := stB.GetConfig(ctx, "issue_prefix") - if err != nil { - t.Fatalf("read during held write lock: %v", err) - } - if got != "test" { - t.Fatalf("read during held write lock: got %q, want %q", got, "test") - } -} - -// withDefaults mirrors the conformance helper (Status/IssueType defaulting) so this -// package-internal test can build a minimally-valid issue without the harness. -func withDefaults(i *types.Issue) *types.Issue { - if i.Status == "" { - i.Status = types.StatusOpen - } - if i.IssueType == "" { - i.IssueType = types.TypeTask - } - return i -} - -func isLockError(err error) bool { - s := strings.ToLower(err.Error()) - return strings.Contains(s, "database is locked") || strings.Contains(s, "sqlite_busy") -} diff --git a/internal/storage/sqlite/schema.go b/internal/storage/sqlite/schema.go deleted file mode 100644 index 8087532e8..000000000 --- a/internal/storage/sqlite/schema.go +++ /dev/null @@ -1,124 +0,0 @@ -package sqlite - -import ( - "context" - "database/sql" - _ "embed" - "errors" - "fmt" - "strings" -) - -// ddl is the SQLite backend schema, embedded from schema.sql. It is the Dolt/MySQL -// schema with SQLite adjustments: ENGINE/CHARSET/COLLATE stripped, inline KEY/UNIQUE -// KEY lifted to CREATE INDEX (SQLite forbids inline non-PK indexes), ON UPDATE -// CURRENT_TIMESTAMP dropped (unsupported), json → text, and prefix-index lengths -// removed (SQLite has no InnoDB key-length cap). Backticks, `?` placeholders, and -// tinyint(1) all work natively. -// -//go:embed schema.sql -var ddl string - -const ( - schemaVersion = "1" - schemaVersionKey = "sqlite_schema_version" -) - -// InitSchema applies the DDL, seeds the default config rows on first provision, and -// stamps the schema version. db is a raw modernc connection (the DDL and seeds are -// native SQLite and need no dialect translation). -func InitSchema(ctx context.Context, db *sql.DB) error { - for _, stmt := range splitStatements(ddl) { - if _, err := db.ExecContext(ctx, stmt); err != nil { - return fmt.Errorf("sqlite: exec DDL statement: %w\n-- statement:\n%s", err, stmt) - } - } - fresh, err := stampSchemaVersion(ctx, db) - if err != nil { - return err - } - if fresh { - if err := seedDefaultConfig(ctx, db); err != nil { - return err - } - } - return nil -} - -// defaultConfigSeeds mirrors migration 0016 exactly. Seeded only on first provision. -var defaultConfigSeeds = [][2]string{ - {"compaction_enabled", "false"}, - {"compact_tier1_days", "30"}, - {"compact_tier1_dep_levels", "2"}, - {"compact_tier2_days", "90"}, - {"compact_tier2_dep_levels", "5"}, - {"compact_tier2_commits", "100"}, - {"compact_batch_size", "50"}, - {"compact_parallel_workers", "5"}, - {"auto_compact_enabled", "false"}, -} - -func seedDefaultConfig(ctx context.Context, db *sql.DB) error { - for _, kv := range defaultConfigSeeds { - if _, err := db.ExecContext(ctx, - "INSERT OR IGNORE INTO config (`key`, `value`) VALUES (?, ?)", kv[0], kv[1]); err != nil { - return fmt.Errorf("sqlite: seed default config %q: %w", kv[0], err) - } - } - return nil -} - -// stampSchemaVersion records schemaVersion on first provision and refuses a mismatched -// workspace (no migrator in the wedge). Returns fresh=true only on the first stamp. -func stampSchemaVersion(ctx context.Context, db *sql.DB) (fresh bool, err error) { - var stored string - err = db.QueryRowContext(ctx, "SELECT `value` FROM metadata WHERE `key` = ?", schemaVersionKey).Scan(&stored) - switch { - case errors.Is(err, sql.ErrNoRows): - // Provision runs on every open; two bd processes opening a not-yet- - // provisioned workspace concurrently can both reach here. INSERT OR - // IGNORE lets both succeed; only the opener that inserted the row - // (RowsAffected==1) is fresh and seeds defaults. - res, ierr := db.ExecContext(ctx, "INSERT OR IGNORE INTO metadata (`key`, `value`) VALUES (?, ?)", schemaVersionKey, schemaVersion) - if ierr != nil { - return false, fmt.Errorf("sqlite: stamp schema version: %w", ierr) - } - if n, _ := res.RowsAffected(); n == 1 { - return true, nil - } - // Lost the race: re-read what the winner stored and version-check it. - if rerr := db.QueryRowContext(ctx, "SELECT `value` FROM metadata WHERE `key` = ?", schemaVersionKey).Scan(&stored); rerr != nil { - return false, fmt.Errorf("sqlite: read schema version after conflict: %w", rerr) - } - if stored != schemaVersion { - return false, fmt.Errorf("sqlite: workspace schema version %s, this binary requires %s — recreate the workspace or use a matching binary", stored, schemaVersion) - } - return false, nil - case err != nil: - return false, fmt.Errorf("sqlite: read schema version: %w", err) - case stored != schemaVersion: - return false, fmt.Errorf("sqlite: workspace schema version %s, this binary requires %s — recreate the workspace or use a matching binary", stored, schemaVersion) - default: - return false, nil - } -} - -// splitStatements splits the DDL on ';' at statement boundaries; the schema has no -// procedural bodies or embedded ';'. Blank fragments and line comments are dropped. -func splitStatements(ddl string) []string { - var stmts []string - for _, raw := range strings.Split(ddl, ";") { - var b strings.Builder - for _, line := range strings.Split(raw, "\n") { - if strings.HasPrefix(strings.TrimSpace(line), "--") { - continue - } - b.WriteString(line) - b.WriteString("\n") - } - if s := strings.TrimSpace(b.String()); s != "" { - stmts = append(stmts, s) - } - } - return stmts -} diff --git a/internal/storage/sqlite/schema.sql b/internal/storage/sqlite/schema.sql deleted file mode 100644 index edc79f7ad..000000000 --- a/internal/storage/sqlite/schema.sql +++ /dev/null @@ -1,327 +0,0 @@ -CREATE TABLE IF NOT EXISTS `issues` ( - `id` varchar(255) NOT NULL, - `content_hash` varchar(64), - `title` varchar(500) NOT NULL, - `description` longtext NOT NULL, - `design` longtext NOT NULL, - `acceptance_criteria` longtext NOT NULL, - `notes` longtext NOT NULL, - `status` varchar(32) NOT NULL DEFAULT 'open', - `priority` int NOT NULL DEFAULT '2', - `issue_type` varchar(32) NOT NULL DEFAULT 'task', - `assignee` varchar(255), - `estimated_minutes` int, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) DEFAULT '', - `owner` varchar(255) DEFAULT '', - `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP , - `closed_at` datetime, - `closed_by_session` varchar(255) DEFAULT '', - `external_ref` varchar(255), - `spec_id` varchar(1024), - `compaction_level` int DEFAULT '0', - `compacted_at` datetime, - `compacted_at_commit` varchar(64), - `original_size` int, - `sender` varchar(255) DEFAULT '', - `ephemeral` tinyint(1) DEFAULT '0', - `wisp_type` varchar(32) DEFAULT '', - `pinned` tinyint(1) DEFAULT '0', - `is_template` tinyint(1) DEFAULT '0', - `mol_type` varchar(32) DEFAULT '', - `work_type` varchar(32) DEFAULT 'mutex', - `source_system` varchar(255) DEFAULT '', - `metadata` text DEFAULT '{}', - `source_repo` varchar(512) DEFAULT '', - `close_reason` longtext DEFAULT (''), - `event_kind` varchar(32) DEFAULT '', - `actor` varchar(255) DEFAULT '', - `target` varchar(255) DEFAULT '', - `payload` text DEFAULT (''), - `await_type` varchar(32) DEFAULT '', - `await_id` varchar(255) DEFAULT '', - `timeout_ns` bigint DEFAULT '0', - `waiters` text DEFAULT (''), - `hook_bead` varchar(255) DEFAULT '', - `role_bead` varchar(255) DEFAULT '', - `agent_state` varchar(32) DEFAULT '', - `last_activity` datetime, - `role_type` varchar(32) DEFAULT '', - `rig` varchar(255) DEFAULT '', - `due_at` datetime, - `defer_until` datetime, - `no_history` tinyint(1) DEFAULT '0', - `started_at` datetime, - `is_blocked` tinyint(1) NOT NULL DEFAULT '0', - `row_lock` bigint NOT NULL DEFAULT 0, - PRIMARY KEY (`id`) -); - --- Ephemeral claim leases (bd-lrgn1): node-local, never exported by backup. --- One row per live claim. See issueops.UpsertLeaseInTx for the invariant. -CREATE TABLE IF NOT EXISTS `leases` ( - `issue_id` varchar(255) NOT NULL, - `holder` varchar(255) NOT NULL, - `granted_at` datetime NOT NULL, - `lease_expires_at` datetime NOT NULL, - `heartbeat_at` datetime NOT NULL, - PRIMARY KEY (`issue_id`) -); - -CREATE TABLE IF NOT EXISTS `wisps` ( - `id` varchar(255) NOT NULL, - `content_hash` varchar(64), - `title` varchar(500) NOT NULL, - `description` longtext NOT NULL DEFAULT (''), - `design` longtext NOT NULL DEFAULT (''), - `acceptance_criteria` longtext NOT NULL DEFAULT (''), - `notes` longtext NOT NULL DEFAULT (''), - `status` varchar(32) NOT NULL DEFAULT 'open', - `priority` int NOT NULL DEFAULT '2', - `issue_type` varchar(32) NOT NULL DEFAULT 'task', - `assignee` varchar(255), - `estimated_minutes` int, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) DEFAULT '', - `owner` varchar(255) DEFAULT '', - `updated_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP , - `closed_at` datetime, - `closed_by_session` varchar(255) DEFAULT '', - `external_ref` varchar(255), - `spec_id` varchar(1024), - `compaction_level` int DEFAULT '0', - `compacted_at` datetime, - `compacted_at_commit` varchar(64), - `original_size` int, - `sender` varchar(255) DEFAULT '', - `ephemeral` tinyint(1) DEFAULT '0', - `wisp_type` varchar(32) DEFAULT '', - `pinned` tinyint(1) DEFAULT '0', - `is_template` tinyint(1) DEFAULT '0', - `mol_type` varchar(32) DEFAULT '', - `work_type` varchar(32) DEFAULT 'mutex', - `source_system` varchar(255) DEFAULT '', - `metadata` text DEFAULT '{}', - `source_repo` varchar(512) DEFAULT '', - `close_reason` longtext DEFAULT (''), - `event_kind` varchar(32) DEFAULT '', - `actor` varchar(255) DEFAULT '', - `target` varchar(255) DEFAULT '', - `payload` text DEFAULT (''), - `await_type` varchar(32) DEFAULT '', - `await_id` varchar(255) DEFAULT '', - `timeout_ns` bigint DEFAULT '0', - `waiters` text DEFAULT (''), - `hook_bead` varchar(255) DEFAULT '', - `role_bead` varchar(255) DEFAULT '', - `agent_state` varchar(32) DEFAULT '', - `last_activity` datetime, - `role_type` varchar(32) DEFAULT '', - `rig` varchar(255) DEFAULT '', - `due_at` datetime, - `defer_until` datetime, - `no_history` tinyint(1) DEFAULT '0', - `started_at` datetime, - `is_blocked` tinyint(1) NOT NULL DEFAULT '0', - `row_lock` bigint NOT NULL DEFAULT 0, - PRIMARY KEY (`id`) -); - -CREATE TABLE IF NOT EXISTS `labels` ( - `issue_id` varchar(255) NOT NULL, - `label` varchar(255) NOT NULL, - PRIMARY KEY (`issue_id`,`label`), - CONSTRAINT `fk_labels_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `wisp_labels` ( - `issue_id` varchar(255) NOT NULL, - `label` varchar(255) NOT NULL, - PRIMARY KEY (`issue_id`,`label`), - CONSTRAINT `fk_wisp_labels_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `dependencies` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `type` varchar(32) NOT NULL DEFAULT 'blocks', - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) NOT NULL, - `metadata` text DEFAULT '{}', - `thread_id` varchar(255) DEFAULT '', - `depends_on_issue_id` varchar(255), - `depends_on_wisp_id` varchar(255), - `depends_on_external` varchar(255), - PRIMARY KEY (`id`), - CONSTRAINT `fk_dep_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_dep_issue_target` FOREIGN KEY (`depends_on_issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `wisp_dependencies` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `depends_on_issue_id` varchar(255), - `depends_on_wisp_id` varchar(255), - `depends_on_external` varchar(255), - `type` varchar(32) NOT NULL DEFAULT 'blocks', - `created_at` datetime DEFAULT CURRENT_TIMESTAMP, - `created_by` varchar(255) DEFAULT '', - `metadata` text DEFAULT '{}', - `thread_id` varchar(255) DEFAULT '', - PRIMARY KEY (`id`), - CONSTRAINT `fk_wisp_dep_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_wisp_dep_issue_target` FOREIGN KEY (`depends_on_issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `fk_wisp_dep_wisp_target` FOREIGN KEY (`depends_on_wisp_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `comments` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `author` varchar(255) NOT NULL, - `text` longtext NOT NULL, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - CONSTRAINT `fk_comments_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `wisp_comments` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `author` varchar(255) DEFAULT '', - `text` text NOT NULL, - `created_at` datetime DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - CONSTRAINT `fk_wisp_comments_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `events` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `event_type` varchar(32) NOT NULL, - `actor` varchar(255) NOT NULL, - `old_value` longtext, - `new_value` longtext, - `comment` text, - `created_at` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - CONSTRAINT `fk_events_issue` FOREIGN KEY (`issue_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `wisp_events` ( - `id` char(36) NOT NULL, - `issue_id` varchar(255) NOT NULL, - `event_type` varchar(32) NOT NULL, - `actor` varchar(255) DEFAULT '', - `old_value` longtext DEFAULT (''), - `new_value` longtext DEFAULT (''), - `comment` text DEFAULT (''), - `created_at` datetime DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`id`), - CONSTRAINT `fk_wisp_events_issue` FOREIGN KEY (`issue_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `config` ( - `key` varchar(255) NOT NULL, - `value` text NOT NULL, - PRIMARY KEY (`key`) -); - -CREATE TABLE IF NOT EXISTS `metadata` ( - `key` varchar(255) NOT NULL, - `value` text NOT NULL, - PRIMARY KEY (`key`) -); - -CREATE TABLE IF NOT EXISTS `local_metadata` ( - `key` varchar(255) NOT NULL, - `value` text NOT NULL DEFAULT (''), - PRIMARY KEY (`key`) -); - -CREATE TABLE IF NOT EXISTS `issue_counter` ( - `prefix` varchar(255) NOT NULL, - `last_id` int NOT NULL DEFAULT '0', - PRIMARY KEY (`prefix`) -); - -CREATE TABLE IF NOT EXISTS `child_counters` ( - `parent_id` varchar(255) NOT NULL, - `last_child` int NOT NULL DEFAULT '0', - PRIMARY KEY (`parent_id`), - CONSTRAINT `fk_counter_parent` FOREIGN KEY (`parent_id`) REFERENCES `issues` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `wisp_child_counters` ( - `parent_id` varchar(255) NOT NULL, - `last_child` int NOT NULL DEFAULT '0', - PRIMARY KEY (`parent_id`), - CONSTRAINT `fk_wisp_child_counters_parent` FOREIGN KEY (`parent_id`) REFERENCES `wisps` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -); - -CREATE TABLE IF NOT EXISTS `custom_statuses` ( - `name` varchar(64) NOT NULL, - `category` varchar(32) NOT NULL DEFAULT 'unspecified', - PRIMARY KEY (`name`) -); - -CREATE TABLE IF NOT EXISTS `custom_types` ( - `name` varchar(64) NOT NULL, - PRIMARY KEY (`name`) -); - -CREATE TABLE IF NOT EXISTS `repo_mtimes` ( - `repo_path` varchar(512) NOT NULL, - `jsonl_path` varchar(512) NOT NULL, - `mtime_ns` bigint NOT NULL, - `last_checked` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, - PRIMARY KEY (`repo_path`) -); - -CREATE INDEX IF NOT EXISTS idx_issues_assignee ON `issues` (`assignee`); -CREATE INDEX IF NOT EXISTS idx_issues_created_at ON `issues` (`created_at`); -CREATE INDEX IF NOT EXISTS idx_issues_defer_until ON `issues` (`defer_until`); -CREATE INDEX IF NOT EXISTS idx_issues_external_ref ON `issues` (`external_ref`); -CREATE INDEX IF NOT EXISTS idx_issues_is_blocked ON `issues` (`is_blocked`,`status`); -CREATE INDEX IF NOT EXISTS idx_issues_issue_type ON `issues` (`issue_type`); -CREATE INDEX IF NOT EXISTS idx_issues_priority ON `issues` (`priority`); -CREATE INDEX IF NOT EXISTS idx_issues_spec_id ON `issues` (`spec_id`); -CREATE INDEX IF NOT EXISTS idx_issues_status_updated_at ON `issues` (`status`,`updated_at`); -CREATE INDEX IF NOT EXISTS idx_leases_expires ON `leases` (`lease_expires_at`); -CREATE INDEX IF NOT EXISTS idx_wisps_assignee ON `wisps` (`assignee`); -CREATE INDEX IF NOT EXISTS idx_wisps_created_at ON `wisps` (`created_at`); -CREATE INDEX IF NOT EXISTS idx_wisps_external_ref ON `wisps` (`external_ref`); -CREATE INDEX IF NOT EXISTS idx_wisps_is_blocked ON `wisps` (`is_blocked`,`status`); -CREATE INDEX IF NOT EXISTS idx_wisps_issue_type ON `wisps` (`issue_type`); -CREATE INDEX IF NOT EXISTS idx_wisps_priority ON `wisps` (`priority`); -CREATE INDEX IF NOT EXISTS idx_wisps_spec_id ON `wisps` (`spec_id`); -CREATE INDEX IF NOT EXISTS idx_wisps_status ON `wisps` (`status`); -CREATE INDEX IF NOT EXISTS idx_labels_label ON `labels` (`label`); -CREATE INDEX IF NOT EXISTS idx_wisp_labels_label ON `wisp_labels` (`label`); -CREATE INDEX IF NOT EXISTS idx_dep_external_target ON `dependencies` (`depends_on_external`); -CREATE INDEX IF NOT EXISTS idx_dep_issue_target ON `dependencies` (`depends_on_issue_id`); -CREATE INDEX IF NOT EXISTS idx_dep_type_external ON `dependencies` (`type`,`depends_on_external`); -CREATE INDEX IF NOT EXISTS idx_dep_type_issue ON `dependencies` (`type`,`depends_on_issue_id`); -CREATE INDEX IF NOT EXISTS idx_dep_type_wisp ON `dependencies` (`type`,`depends_on_wisp_id`); -CREATE INDEX IF NOT EXISTS idx_dep_wisp_target ON `dependencies` (`depends_on_wisp_id`); -CREATE INDEX IF NOT EXISTS idx_dependencies_issue ON `dependencies` (`issue_id`); -CREATE INDEX IF NOT EXISTS idx_dependencies_thread ON `dependencies` (`thread_id`); -CREATE UNIQUE INDEX IF NOT EXISTS uk_dep_external_target ON `dependencies` (`issue_id`,`depends_on_external`); -CREATE UNIQUE INDEX IF NOT EXISTS uk_dep_issue_target ON `dependencies` (`issue_id`,`depends_on_issue_id`); -CREATE UNIQUE INDEX IF NOT EXISTS uk_dep_wisp_target ON `dependencies` (`issue_id`,`depends_on_wisp_id`); -CREATE INDEX IF NOT EXISTS fk_wisp_dep_issue_target ON `wisp_dependencies` (`depends_on_issue_id`); -CREATE INDEX IF NOT EXISTS fk_wisp_dep_wisp_target ON `wisp_dependencies` (`depends_on_wisp_id`); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type ON `wisp_dependencies` (`type`); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type_external ON `wisp_dependencies` (`type`,`depends_on_external`); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type_issue ON `wisp_dependencies` (`type`,`depends_on_issue_id`); -CREATE INDEX IF NOT EXISTS idx_wisp_dep_type_wisp ON `wisp_dependencies` (`type`,`depends_on_wisp_id`); -CREATE UNIQUE INDEX IF NOT EXISTS uk_wisp_dep_external_target ON `wisp_dependencies` (`issue_id`,`depends_on_external`); -CREATE UNIQUE INDEX IF NOT EXISTS uk_wisp_dep_issue_target ON `wisp_dependencies` (`issue_id`,`depends_on_issue_id`); -CREATE UNIQUE INDEX IF NOT EXISTS uk_wisp_dep_wisp_target ON `wisp_dependencies` (`issue_id`,`depends_on_wisp_id`); -CREATE INDEX IF NOT EXISTS idx_comments_created_at ON `comments` (`created_at`); -CREATE INDEX IF NOT EXISTS idx_comments_issue ON `comments` (`issue_id`); -CREATE INDEX IF NOT EXISTS idx_wisp_comments_issue ON `wisp_comments` (`issue_id`); -CREATE INDEX IF NOT EXISTS idx_events_created_at ON `events` (`created_at`); -CREATE INDEX IF NOT EXISTS idx_events_issue ON `events` (`issue_id`); -CREATE INDEX IF NOT EXISTS idx_wisp_events_created_at ON `wisp_events` (`created_at`); -CREATE INDEX IF NOT EXISTS idx_wisp_events_issue ON `wisp_events` (`issue_id`); -CREATE INDEX IF NOT EXISTS idx_repo_mtimes_checked ON `repo_mtimes` (`last_checked`); diff --git a/internal/storage/sqlite/seed_test.go b/internal/storage/sqlite/seed_test.go deleted file mode 100644 index 0c190e09f..000000000 --- a/internal/storage/sqlite/seed_test.go +++ /dev/null @@ -1,38 +0,0 @@ -package sqlite - -import ( - "context" - "path/filepath" - "testing" -) - -// TestSeedOnlyOnFirstProvision guards that re-opening a SQLite workspace (InitSchema -// runs every open) does not resurrect a key the user `config unset`. -func TestSeedOnlyOnFirstProvision(t *testing.T) { - ctx := context.Background() - path := filepath.Join(t.TempDir(), "seed.db") - - st, err := Provision(ctx, path) - if err != nil { - t.Fatalf("Provision: %v", err) - } - if v, _ := st.GetConfig(ctx, "auto_compact_enabled"); v != "false" { - t.Fatalf("first provision: want seeded auto_compact_enabled=false, got %q", v) - } - if err := st.DeleteConfig(ctx, "auto_compact_enabled"); err != nil { - t.Fatalf("DeleteConfig: %v", err) - } - if v, _ := st.GetConfig(ctx, "auto_compact_enabled"); v != "" { - t.Fatalf("after unset: want empty, got %q", v) - } - _ = st.Close() - - st2, err := Provision(ctx, path) - if err != nil { - t.Fatalf("re-Provision: %v", err) - } - defer st2.Close() - if v, _ := st2.GetConfig(ctx, "auto_compact_enabled"); v != "" { - t.Fatalf("REGRESSION: re-provision resurrected an unset key: got %q (want empty)", v) - } -} diff --git a/internal/storage/sqlite/store.go b/internal/storage/sqlite/store.go deleted file mode 100644 index 85e632bfc..000000000 --- a/internal/storage/sqlite/store.go +++ /dev/null @@ -1,60 +0,0 @@ -// Package sqlite is the SQLite backend for bd: the shared sqlkit.Store bundled with -// the SQLite dialect and a no-op readiness strategy, plus the non-Dolt markers. It is -// a pure-Go, file-based, embedded backend (modernc.org/sqlite; no CGO, no server). -package sqlite - -import ( - "context" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/sqlkit" -) - -// Backend is the metadata.json backend identifier for this store. -const Backend = "sqlite" - -// Store is the SQLite backend: *sqlkit.Store + the generated typed-unsupported shell. -type Store struct { - *sqlkit.Store - unsupportedDoltStorage -} - -// Compile-time guard on the generated skip list: the composite backend (real -// *sqlkit.Store methods plus the typed-unsupported shell) must fully satisfy -// storage.DoltStorage. This fails the build on skip-list drift — a skipped -// method sqlkit does not actually implement (missing method), or a method both -// implemented and stubbed (ambiguous selector) — so no method can silently -// become "unsupported". -var _ storage.DoltStorage = (*Store)(nil) - -// Config configures a SQLite backend. DSN is a modernc.org/sqlite file DSN. -type Config struct{ DSN string } - -// New builds the SQLite backend from its strategy bundle: the sqlite dialect and a -// no-op readiness strategy (issueops maintains is_blocked in-tx, like Dolt). -func New(ctx context.Context, cfg Config) (*Store, error) { - base, err := sqlkit.New(ctx, sqlkit.Config{ - Dialect: sqliteDialect{dsn: cfg.DSN}, - Readiness: sqlkit.NoopReadiness{}, - }) - if err != nil { - return nil, err - } - return &Store{Store: base}, nil -} - -// CommitGraphUnsupported tells cmd/bd's PostRun to skip Dolt-only maintenance. -func (s *Store) CommitGraphUnsupported() bool { return true } - -// CommitPending is a no-op on a non-version-controlled backend. -func (s *Store) CommitPending(_ context.Context, _ string) (bool, error) { return false, nil } - -// Commit and variants are no-ops on SQLite (writes are already durable per-tx). -func (s *Store) Commit(_ context.Context, _ string) error { return nil } -func (s *Store) CommitWithConfig(_ context.Context, _ string) error { return nil } -func (s *Store) CommitMergeResolution(_ context.Context, _ string) error { return nil } - -var ( - _ storage.DoltStorage = (*Store)(nil) - _ storage.NonCommitGraphBackend = (*Store)(nil) -) diff --git a/internal/storage/sqlite/unsupported.go b/internal/storage/sqlite/unsupported.go deleted file mode 100644 index 5c92264b2..000000000 --- a/internal/storage/sqlite/unsupported.go +++ /dev/null @@ -1,11 +0,0 @@ -package sqlite - -import "github.com/steveyegge/beads/internal/storage" - -//go:generate go run ../unsupportedgen -pkg sqlite -src .. -out unsupported_gen.go -type DoltStorage -skip AddDependency,AddIssueComment,AddLabel,ClaimIssue,ClaimReadyIssue,Close,CloseIssue,Commit,CommitMergeResolution,CommitPending,CommitWithConfig,CountDependencies,CountDependents,CountEvents,CountIssueComments,CountIssues,CountIssuesByGroup,CreateIssue,CreateIssues,DeleteConfig,DeleteIssue,DeleteIssues,DetectCycles,GetAllConfig,GetBlockedIssues,GetBlockingInfoForIssues,GetCommentCounts,GetCommentsForIssues,GetConfig,GetCustomStatuses,GetCustomStatusesDetailed,GetCustomTypes,GetDependencies,GetDependenciesWithMetadata,GetDependencyCounts,GetDependencyRecords,GetDependencyRecordsForIssues,GetDependencyTree,GetDependents,GetDependentsWithMetadata,GetEpicsEligibleForClosure,GetEvents,GetInfraTypes,GetIssue,GetIssueByExternalRef,GetIssueComments,GetIssuesByIDs,GetIssuesByLabel,GetLabels,GetLabelsForIssues,GetLocalMetadata,GetMetadata,GetNewlyUnblockedByClose,GetNextChildID,GetReadyWork,GetReadyWorkWithCounts,GetStaleIssues,GetStatistics,IsBlocked,IsInfraTypeCtx,IterBlockedIssues,IterDependenciesWithMetadata,IterDependentsWithMetadata,IterEvents,IterIssueComments,IterIssues,IterReadyWork,IterWisps,ListWisps,RemoveDependency,RemoveLabel,ReopenIssue,RunInTransaction,SearchIssues,SearchIssuesWithCounts,SetConfig,SetLocalMetadata,SetMetadata,UpdateIssue,UpdateIssueType,AddComment,ClearRepoMtime,CountDependentsByStatus,DeleteIssuesBySourceRepo,FindWispDependentsRecursive,GetAllDependencyRecords,GetAllEventsSince,GetMoleculeLastActivity,GetMoleculeProgress,GetRepoMtime,ImportIssueComment,IterAllDependencyRecords,IterAllEventsSince,PromoteFromEphemeral,SetRepoMtime,UpdateIssueID,CreateIssuesWithFullOptions,SlotClear,SlotGet,SlotSet,SearchIssueIDs,HeartbeatIssue,ReclaimExpiredLeases,UnclaimIssue - -// errUnsupported returns the backend-agnostic *storage.ErrUnsupported sentinel; Backend -// is "sqlite". Same allowlist as postgres/mysql (identical sqlkit base + overrides). -func errUnsupported(op string) error { - return &storage.ErrUnsupported{Op: op, Backend: Backend} -} diff --git a/internal/storage/sqlite/unsupported_gen.go b/internal/storage/sqlite/unsupported_gen.go deleted file mode 100644 index d89e56c0d..000000000 --- a/internal/storage/sqlite/unsupported_gen.go +++ /dev/null @@ -1,236 +0,0 @@ -// Code generated by gen (sqlite typed-unsupported shell); DO NOT EDIT. - -package sqlite - -import ( - "context" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/types" -) - -// unsupportedDoltStorage is the generated typed-unsupported shell for storage.DoltStorage. -// Every method returns *storage.ErrUnsupported; embed it and override the -// real slice. DO NOT hand-edit — regenerate with `go generate ./...`. -type unsupportedDoltStorage struct{} - -func (unsupportedDoltStorage) MergeSlotCreate(_ context.Context, _ string) (_ *types.Issue, err error) { - err = errUnsupported("MergeSlotCreate") - return -} - -func (unsupportedDoltStorage) MergeSlotCheck(_ context.Context) (_ *storage.MergeSlotStatus, err error) { - err = errUnsupported("MergeSlotCheck") - return -} - -func (unsupportedDoltStorage) MergeSlotAcquire(_ context.Context, _ string, _ string, _ bool) (_ *storage.MergeSlotResult, err error) { - err = errUnsupported("MergeSlotAcquire") - return -} - -func (unsupportedDoltStorage) MergeSlotRelease(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("MergeSlotRelease") - return -} - -func (unsupportedDoltStorage) Branch(_ context.Context, _ string) (err error) { - err = errUnsupported("Branch") - return -} - -func (unsupportedDoltStorage) Checkout(_ context.Context, _ string) (err error) { - err = errUnsupported("Checkout") - return -} - -func (unsupportedDoltStorage) CurrentBranch(_ context.Context) (_ string, err error) { - err = errUnsupported("CurrentBranch") - return -} - -func (unsupportedDoltStorage) DeleteBranch(_ context.Context, _ string) (err error) { - err = errUnsupported("DeleteBranch") - return -} - -func (unsupportedDoltStorage) ListBranches(_ context.Context) (_ []string, err error) { - err = errUnsupported("ListBranches") - return -} - -func (unsupportedDoltStorage) CommitExists(_ context.Context, _ string) (_ bool, err error) { - err = errUnsupported("CommitExists") - return -} - -func (unsupportedDoltStorage) GetCurrentCommit(_ context.Context) (_ string, err error) { - err = errUnsupported("GetCurrentCommit") - return -} - -func (unsupportedDoltStorage) Status(_ context.Context) (_ *storage.Status, err error) { - err = errUnsupported("Status") - return -} - -func (unsupportedDoltStorage) Log(_ context.Context, _ int) (_ []storage.CommitInfo, err error) { - err = errUnsupported("Log") - return -} - -func (unsupportedDoltStorage) Merge(_ context.Context, _ string) (_ []storage.Conflict, err error) { - err = errUnsupported("Merge") - return -} - -func (unsupportedDoltStorage) GetConflicts(_ context.Context) (_ []storage.Conflict, err error) { - err = errUnsupported("GetConflicts") - return -} - -func (unsupportedDoltStorage) ResolveConflicts(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("ResolveConflicts") - return -} - -func (unsupportedDoltStorage) History(_ context.Context, _ string) (_ []*storage.HistoryEntry, err error) { - err = errUnsupported("History") - return -} - -func (unsupportedDoltStorage) AsOf(_ context.Context, _ string, _ string) (_ *types.Issue, err error) { - err = errUnsupported("AsOf") - return -} - -func (unsupportedDoltStorage) Diff(_ context.Context, _ string, _ string) (_ []*storage.DiffEntry, err error) { - err = errUnsupported("Diff") - return -} - -func (unsupportedDoltStorage) AddRemote(_ context.Context, _ string, _ string) (err error) { - err = errUnsupported("AddRemote") - return -} - -func (unsupportedDoltStorage) RemoveRemote(_ context.Context, _ string) (err error) { - err = errUnsupported("RemoveRemote") - return -} - -func (unsupportedDoltStorage) HasRemote(_ context.Context, _ string) (_ bool, err error) { - err = errUnsupported("HasRemote") - return -} - -func (unsupportedDoltStorage) ListRemotes(_ context.Context) (_ []storage.RemoteInfo, err error) { - err = errUnsupported("ListRemotes") - return -} - -func (unsupportedDoltStorage) Push(_ context.Context) (err error) { - err = errUnsupported("Push") - return -} - -func (unsupportedDoltStorage) Pull(_ context.Context) (err error) { - err = errUnsupported("Pull") - return -} - -func (unsupportedDoltStorage) ForcePush(_ context.Context) (err error) { - err = errUnsupported("ForcePush") - return -} - -func (unsupportedDoltStorage) PushRemote(_ context.Context, _ string, _ bool) (err error) { - err = errUnsupported("PushRemote") - return -} - -func (unsupportedDoltStorage) PullRemote(_ context.Context, _ string) (err error) { - err = errUnsupported("PullRemote") - return -} - -func (unsupportedDoltStorage) Fetch(_ context.Context, _ string) (err error) { - err = errUnsupported("Fetch") - return -} - -func (unsupportedDoltStorage) PushTo(_ context.Context, _ string) (err error) { - err = errUnsupported("PushTo") - return -} - -func (unsupportedDoltStorage) PullFrom(_ context.Context, _ string) (_ []storage.Conflict, err error) { - err = errUnsupported("PullFrom") - return -} - -func (unsupportedDoltStorage) Sync(_ context.Context, _ string, _ string) (_ *storage.SyncResult, err error) { - err = errUnsupported("Sync") - return -} - -func (unsupportedDoltStorage) SyncStatus(_ context.Context, _ string) (_ *storage.SyncStatus, err error) { - err = errUnsupported("SyncStatus") - return -} - -func (unsupportedDoltStorage) AddFederationPeer(_ context.Context, _ *storage.FederationPeer) (err error) { - err = errUnsupported("AddFederationPeer") - return -} - -func (unsupportedDoltStorage) GetFederationPeer(_ context.Context, _ string) (_ *storage.FederationPeer, err error) { - err = errUnsupported("GetFederationPeer") - return -} - -func (unsupportedDoltStorage) ListFederationPeers(_ context.Context) (_ []*storage.FederationPeer, err error) { - err = errUnsupported("ListFederationPeers") - return -} - -func (unsupportedDoltStorage) RemoveFederationPeer(_ context.Context, _ string) (err error) { - err = errUnsupported("RemoveFederationPeer") - return -} - -func (unsupportedDoltStorage) CheckEligibility(_ context.Context, _ string, _ int) (_ bool, _ string, err error) { - err = errUnsupported("CheckEligibility") - return -} - -func (unsupportedDoltStorage) ApplyCompaction(_ context.Context, _ string, _ int, _ int, _ int, _ string) (err error) { - err = errUnsupported("ApplyCompaction") - return -} - -func (unsupportedDoltStorage) GetTier1Candidates(_ context.Context) (_ []*types.CompactionCandidate, err error) { - err = errUnsupported("GetTier1Candidates") - return -} - -func (unsupportedDoltStorage) GetTier2Candidates(_ context.Context) (_ []*types.CompactionCandidate, err error) { - err = errUnsupported("GetTier2Candidates") - return -} - -func (unsupportedDoltStorage) SnapshotIssue(_ context.Context, _ string, _ int) (err error) { - err = errUnsupported("SnapshotIssue") - return -} - -func (unsupportedDoltStorage) GetCompactionSnapshot(_ context.Context, _ string) (_ *types.IssueSnapshot, err error) { - err = errUnsupported("GetCompactionSnapshot") - return -} - -func (unsupportedDoltStorage) RestoreFromSnapshot(_ context.Context, _ string) (_ *types.IssueSnapshot, err error) { - err = errUnsupported("RestoreFromSnapshot") - return -} - -// NOTE: partial shell (104 methods skipped); the embedding composite must assert storage.DoltStorage itself. diff --git a/internal/storage/sqlitedialect/driver.go b/internal/storage/sqlitedialect/driver.go deleted file mode 100644 index 078ceadad..000000000 --- a/internal/storage/sqlitedialect/driver.go +++ /dev/null @@ -1,72 +0,0 @@ -package sqlitedialect - -import ( - "context" - "database/sql" - "database/sql/driver" - - sqlite "modernc.org/sqlite" -) - -// Open returns a *sql.DB over modernc.org/sqlite whose Prepare translates bd's -// canonical MySQL SQL to SQLite (see Translate). Like pgdialect it exposes no -// Execer/Queryer fast path, so database/sql routes every statement through Prepare. -// The caller supplies foreign-key enforcement etc. via DSN pragmas. -func Open(dsn string) (*sql.DB, error) { - return sql.OpenDB(&connector{dsn: dsn}), nil -} - -// connector opens a fresh modernc connection per Connect. A zero-value -// modernc Driver carries no user-registered udfs/collations/hooks, which is exactly -// what the wedge wants; connection config travels in the DSN. -type connector struct{ dsn string } - -func (c *connector) Connect(_ context.Context) (driver.Conn, error) { - base, err := (&sqlite.Driver{}).Open(c.dsn) - if err != nil { - return nil, err - } - return &conn{base: base}, nil -} - -func (c *connector) Driver() driver.Driver { return &sqlite.Driver{} } - -type conn struct{ base driver.Conn } - -func (c *conn) Prepare(query string) (driver.Stmt, error) { - return c.base.Prepare(Translate(query)) -} - -func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) { - q := Translate(query) - if p, ok := c.base.(driver.ConnPrepareContext); ok { - return p.PrepareContext(ctx, q) - } - return c.base.Prepare(q) -} - -func (c *conn) Close() error { return c.base.Close() } - -//nolint:staticcheck // SA1019: driver.Conn requires the deprecated Begin; BeginTx forwarded below. -func (c *conn) Begin() (driver.Tx, error) { return c.base.Begin() } - -func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) { - if b, ok := c.base.(driver.ConnBeginTx); ok { - return b.BeginTx(ctx, opts) - } - return c.base.Begin() //nolint:staticcheck -} - -func (c *conn) ResetSession(ctx context.Context) error { - if rs, ok := c.base.(driver.SessionResetter); ok { - return rs.ResetSession(ctx) - } - return nil -} - -func (c *conn) IsValid() bool { - if v, ok := c.base.(driver.Validator); ok { - return v.IsValid() - } - return true -} diff --git a/internal/storage/sqlitedialect/translate.go b/internal/storage/sqlitedialect/translate.go deleted file mode 100644 index 218360dc6..000000000 --- a/internal/storage/sqlitedialect/translate.go +++ /dev/null @@ -1,488 +0,0 @@ -// Package sqlitedialect translates bd's canonical (MySQL-dialect) SQL to SQLite and -// wraps the modernc.org/sqlite driver. SQLite is closer to MySQL than Postgres is — -// backtick identifiers, `?` placeholders, bool→integer binding, INSTR, json_object, -// REPLACE INTO, and CURRENT_TIMESTAMP (UTC) all work natively — so the translation is -// a small subset of pgdialect's: INSERT IGNORE, the ON DUPLICATE KEY upsert (standard -// ON CONFLICT, shared with Postgres), CONCAT, and unqualified UPDATE SET targets. The -// string-scanning machinery (codeMask/rewriteFuncCalls/…) is shared in shape with -// pgdialect. Isolated here; shared issueops/sqlkit and other backends are untouched. -package sqlitedialect - -import ( - "regexp" - "strings" -) - -// Translate rewrites one statement from bd's MySQL dialect to SQLite. Applied at -// prepare time; statements with no MySQL-ism pass through unchanged. -func Translate(sql string) string { - out := sql - out = rewriteFuncCalls(out, "CONCAT", concatArgs) // CONCAT(a,b) -> (a || b) - // SQLite has no LOCATE; INSTR(haystack, needle) is the equivalent but with the - // arguments REVERSED vs MySQL LOCATE(needle, haystack). Run after CONCAT so a nested - // LOCATE(CONCAT(...), path) already has its inner CONCAT rewritten. Without this the - // recursive parent-descendant CTE (ready/blocked --parent) errors and returns nothing. - out = rewriteFuncCalls(out, "LOCATE", locateArgs) // LOCATE(n,h) -> INSTR(h,n) - // SQLite json_extract already returns an unquoted scalar, so MySQL's explicit - // JSON_UNQUOTE wrapper is dropped; the inner JSON_EXTRACT is native SQLite. - out = rewriteFuncCalls(out, "JSON_UNQUOTE", jsonUnquoteArgs) - // MySQL JSON_ARRAYAGG(x) -> SQLite json_group_array(x). JSON_OBJECT/JSON_EXTRACT/ - // JSON_ARRAY are native SQLite (same names), so they pass through. - out = rewriteFuncCalls(out, "JSON_ARRAYAGG", jsonArrayAggArgs) - // SQLite has no variadic GREATEST/LEAST, but its scalar max()/min() take the - // same (>=2 arg) form and return the largest/smallest argument. bd emits - // GREATEST(last_child, ?) in the child-counter upsert (issueops/create.go), so - // without this rewrite creating or importing any hierarchical dotted issue ID - // (e.g. x-1.2) fails on the SQLite backend with "no such function: GREATEST". - out = rewriteFuncCalls(out, "GREATEST", greatestArgs) // GREATEST(a,b,…) -> max(a,b,…) - out = rewriteFuncCalls(out, "LEAST", leastArgs) // LEAST(a,b,…) -> min(a,b,…) - out = rewriteFuncCalls(out, "DATE_FORMAT", dateFormatArgs) // -> strftime (SQLite format codes) - // SQLite CURRENT_TIMESTAMP is UTC, matching bd's naive-UTC storage discipline. - out = replaceIdentAll(out, "UTC_TIMESTAMP()", "CURRENT_TIMESTAMP") - out = replaceIdentAll(out, "NOW()", "CURRENT_TIMESTAMP") - out = rewriteLabelOrderBy(out) - out = rewriteInsertIgnore(out) // INSERT IGNORE -> INSERT OR IGNORE - out = rewriteOnDuplicateKey(out) // ON DUPLICATE KEY UPDATE -> ON CONFLICT ... - out = addUpdateAlias(out) // UPDATE t alias SET -> UPDATE t AS alias SET (SQLite needs AS) - out = rewriteUpdateSetTargets(out) // SET t.col -> SET col (SQLite forbids qualified) - return out -} - -// updateAliasRe matches an aliased UPDATE target (`UPDATE issues i SET …`), which -// SQLite rejects without the AS keyword. The no-alias form (`UPDATE t SET …`) has only -// one identifier before SET and does not match. -var updateAliasRe = regexp.MustCompile(`(?i)\bUPDATE\s+(\w+)\s+(\w+)\s+SET\b`) - -func addUpdateAlias(sql string) string { - return updateAliasRe.ReplaceAllStringFunc(sql, func(m string) string { - g := updateAliasRe.FindStringSubmatch(m) - if strings.EqualFold(g[2], "set") { // guard: `UPDATE t SET` — g[2] can't be SET here, but be safe - return m - } - return "UPDATE " + g[1] + " AS " + g[2] + " SET" - }) -} - -// replaceIdentAll replaces every code-region occurrence of a literal token -// (case-insensitive) with repl, in a single forward pass. -func replaceIdentAll(sql, token, repl string) string { - lower := strings.ToLower(token) - m := codeMask(sql) - var b strings.Builder - for i := 0; i < len(sql); { - if m[i] && i+len(token) <= len(sql) && strings.ToLower(sql[i:i+len(token)]) == lower { - b.WriteString(repl) - i += len(token) - continue - } - b.WriteByte(sql[i]) - i++ - } - return b.String() -} - -func rewriteLabelOrderBy(sql string) string { - sql = replaceIdentAll(sql, "ORDER BY issue_id, label", "ORDER BY issue_id, label COLLATE BINARY") - return replaceIdentAll(sql, "ORDER BY label", "ORDER BY label COLLATE BINARY") -} - -var insertIgnoreRe = regexp.MustCompile(`(?i)\bINSERT\s+IGNORE\s+INTO\b`) - -// rewriteInsertIgnore: MySQL INSERT IGNORE INTO -> SQLite INSERT OR IGNORE INTO. -func rewriteInsertIgnore(sql string) string { - return insertIgnoreRe.ReplaceAllString(sql, "INSERT OR IGNORE INTO") -} - -// --- ON DUPLICATE KEY UPDATE -> ON CONFLICT (standard SQL, same syntax as Postgres) --- - -// onConflictTargets maps a table to its ON CONFLICT arbiter (the key MySQL's ON -// DUPLICATE KEY infers). Only DO UPDATE upserts need an entry. -var onConflictTargets = map[string]string{ - "issues": "id", - "wisps": "id", - "issue_counter": "prefix", - "child_counters": "parent_id", - "wisp_child_counters": "parent_id", - "repo_mtimes": "repo_path", - "federation_peers": "name", - "leases": "issue_id", -} - -func rewriteOnDuplicateKey(sql string) string { - const odk = "on duplicate key update" - i := indexCodeFold(sql, odk) - if i < 0 { - return sql - } - head := strings.TrimRight(sql[:i], " \n\t") - body := strings.TrimSpace(sql[i+len(odk):]) - if isSelfAssign(body) { - return head + " ON CONFLICT DO NOTHING" - } - // Inside the upsert body, VALUES(col) is the proposed row value (excluded.col) and - // IF(c,a,b) is the ternary (CASE) — translated here where they can't be confused - // with the INSERT ... VALUES keyword. - body = rewriteFuncCalls(body, "IF", ifArgs) - body = rewriteFuncCalls(body, "VALUES", valuesArgs) - target := onConflictTargets[insertTable(sql)] - if target == "" { - return head + " ON CONFLICT () DO UPDATE SET " + body // unknown: fail loud at PREPARE - } - return head + " ON CONFLICT (" + target + ") DO UPDATE SET " + body -} - -func isSelfAssign(body string) bool { - parts := strings.SplitN(body, "=", 2) - if len(parts) != 2 { - return false - } - l := strings.TrimSpace(parts[0]) - r := strings.TrimSpace(strings.TrimRight(parts[1], " \n\t")) - return l != "" && l == r && !strings.ContainsAny(l, " (),") -} - -func insertTable(sql string) string { - toks := strings.Fields(sql) - for i := 0; i+1 < len(toks); i++ { - if strings.EqualFold(toks[i], "INTO") { - t := strings.Trim(toks[i+1], "`\"") - if p := strings.IndexAny(t, "("); p >= 0 { - t = t[:p] - } - return t - } - } - return "" -} - -// --- arg rebuilders --- - -// jsonUnquoteArgs unwraps JSON_UNQUOTE(x) -> x: SQLite's json_extract (the x) already -// returns unquoted scalars, so the wrapper is redundant. -func jsonUnquoteArgs(args []string) string { - if len(args) != 1 { - return "JSON_UNQUOTE(" + strings.Join(args, ", ") + ")" - } - return strings.TrimSpace(args[0]) -} - -// mysqlDateFormatISO8601 is the only DATE_FORMAT pattern bd emits (counts.go renders -// created_at as RFC3339). Any other literal is left loud so it fails at PREPARE rather -// than silently producing a differently-shaped timestamp. -const mysqlDateFormatISO8601 = `'%Y-%m-%dT%H:%i:%sZ'` - -// dateFormatArgs: MySQL DATE_FORMAT(t,'%Y-%m-%dT%H:%i:%sZ') -> SQLite -// strftime('%Y-%m-%dT%H:%M:%SZ', t) (SQLite uses %M minutes / %S seconds). -func dateFormatArgs(args []string) string { - if len(args) != 2 || strings.TrimSpace(args[1]) != mysqlDateFormatISO8601 { - return "DATE_FORMAT(" + strings.Join(args, ", ") + ")" - } - return "strftime('%Y-%m-%dT%H:%M:%SZ', " + strings.TrimSpace(args[0]) + ")" -} - -// jsonArrayAggArgs: MySQL JSON_ARRAYAGG(x) -> SQLite json_group_array(x). -func jsonArrayAggArgs(args []string) string { - for i := range args { - args[i] = strings.TrimSpace(args[i]) - } - return "json_group_array(" + strings.Join(args, ", ") + ")" -} - -func concatArgs(args []string) string { - for i := range args { - args[i] = strings.TrimSpace(args[i]) - } - return "(" + strings.Join(args, " || ") + ")" -} - -// greatestArgs: MySQL GREATEST(a, b, …) -> SQLite scalar max(a, b, …). SQLite's max -// is the aggregate with a single argument and the scalar largest-of with two or -// more, so only the multi-arg form is rewritten; a lone GREATEST(x) is left loud -// so it fails at PREPARE rather than silently collapsing into an aggregate. -func greatestArgs(args []string) string { - if len(args) < 2 { - return "GREATEST(" + strings.Join(args, ", ") + ")" - } - for i := range args { - args[i] = strings.TrimSpace(args[i]) - } - return "max(" + strings.Join(args, ", ") + ")" -} - -// leastArgs: MySQL LEAST(a, b, …) -> SQLite scalar min(a, b, …). Same one-vs-many -// caveat as greatestArgs. -func leastArgs(args []string) string { - if len(args) < 2 { - return "LEAST(" + strings.Join(args, ", ") + ")" - } - for i := range args { - args[i] = strings.TrimSpace(args[i]) - } - return "min(" + strings.Join(args, ", ") + ")" -} - -// locateArgs rewrites MySQL LOCATE(needle, haystack) -> SQLite INSTR(haystack, needle): -// SQLite's INSTR takes the string first and the substring second, reversed from LOCATE. -func locateArgs(args []string) string { - if len(args) != 2 { - return "LOCATE(" + strings.Join(args, ", ") + ")" // 3-arg form is not on bd's path; leave loud - } - return "INSTR(" + strings.TrimSpace(args[1]) + ", " + strings.TrimSpace(args[0]) + ")" -} - -func ifArgs(args []string) string { - if len(args) != 3 { - return "IF(" + strings.Join(args, ", ") + ")" - } - return "CASE WHEN " + strings.TrimSpace(args[0]) + " THEN " + strings.TrimSpace(args[1]) + - " ELSE " + strings.TrimSpace(args[2]) + " END" -} - -// valuesArgs: VALUES(col) -> excluded.col (SQLite's proposed-row alias; case-insensitive). -func valuesArgs(args []string) string { - if len(args) != 1 { - return "VALUES(" + strings.Join(args, ", ") + ")" - } - return "excluded." + strings.TrimSpace(args[0]) -} - -// --- unqualified UPDATE SET targets (SQLite forbids SET t.col) --- - -func rewriteUpdateSetTargets(sql string) string { - m := codeMask(sql) - start := skipWS(sql, 0) - if !wordAtFold(sql, start, "update") { - return sql - } - setPos := scanKeyword(sql, m, start, "set") - if setPos < 0 { - return sql - } - clauseStart := setPos + len("set") - clauseEnd := scanKeyword(sql, m, clauseStart, "where") - if clauseEnd < 0 { - clauseEnd = len(sql) - } - clause := sql[clauseStart:clauseEnd] - cm := codeMask(clause) - var out strings.Builder - depth, segStart := 0, 0 - for j := 0; j < len(clause); j++ { - if cm[j] { - switch clause[j] { - case '(': - depth++ - case ')': - depth-- - case ',': - if depth == 0 { - out.WriteString(unqualifySetTarget(clause[segStart:j])) - out.WriteByte(',') - segStart = j + 1 - } - } - } - } - out.WriteString(unqualifySetTarget(clause[segStart:])) - return sql[:clauseStart] + out.String() + sql[clauseEnd:] -} - -func unqualifySetTarget(seg string) string { - eq := strings.IndexByte(seg, '=') - if eq < 0 { - return seg - } - lhs := seg[:eq] - trimmed := strings.TrimSpace(lhs) - dot := strings.IndexByte(trimmed, '.') - if dot <= 0 || !isIdentWord(trimmed[:dot]) || !isIdentWord(trimmed[dot+1:]) { - return seg - } - lead := lhs[:len(lhs)-len(strings.TrimLeft(lhs, " \t\r\n"))] - return lead + trimmed[dot+1:] + " " + seg[eq:] -} - -func isIdentWord(s string) bool { - s = strings.Trim(s, "`\"") - if s == "" { - return false - } - for i := 0; i < len(s); i++ { - if !isIdentByte(s[i]) { - return false - } - } - return true -} - -func skipWS(s string, i int) int { - for i < len(s) && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n' || s[i] == '\r') { - i++ - } - return i -} - -func wordAtFold(s string, i int, w string) bool { - if i+len(w) > len(s) || strings.ToLower(s[i:i+len(w)]) != w { - return false - } - return i+len(w) == len(s) || !isIdentByte(s[i+len(w)]) -} - -// scanKeyword returns the code-region index of the standalone keyword kw at/after from. -func scanKeyword(s string, m []bool, from int, kw string) int { - for i := from; i+len(kw) <= len(s); i++ { - if !m[i] { - continue - } - if strings.ToLower(s[i:i+len(kw)]) != kw { - continue - } - if i > 0 && isIdentByte(s[i-1]) { - continue - } - if i+len(kw) < len(s) && isIdentByte(s[i+len(kw)]) { - continue - } - return i - } - return -1 -} - -// --- shared string-scanning machinery (shape mirrors pgdialect) --- - -func codeMask(sql string) []bool { - b := []byte(sql) - mask := make([]bool, len(b)) - var inStr, inLine, inBlock bool - for i := 0; i < len(b); i++ { - c := b[i] - switch { - case inLine: - if c == '\n' { - inLine = false - } - case inBlock: - if c == '*' && i+1 < len(b) && b[i+1] == '/' { - i++ - inBlock = false - } - case inStr: - if c == '\'' { - if i+1 < len(b) && b[i+1] == '\'' { - i++ - } else { - inStr = false - } - } - default: - switch { - case c == '\'': - inStr = true - case c == '-' && i+1 < len(b) && b[i+1] == '-': - i++ - inLine = true - case c == '/' && i+1 < len(b) && b[i+1] == '*': - i++ - inBlock = true - default: - mask[i] = true - } - } - } - return mask -} - -func isIdentByte(c byte) bool { - return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') -} - -func indexCodeFold(sql, sub string) int { - m := codeMask(sql) - lower := strings.ToLower(sub) - for i := 0; i+len(sub) <= len(sql); i++ { - if m[i] && strings.ToLower(sql[i:i+len(sub)]) == lower { - return i - } - } - return -1 -} - -func findCallStart(sql, lowerName string, from int) int { - m := codeMask(sql) - for i := from; i+len(lowerName) <= len(sql); i++ { - if !m[i] || strings.ToLower(sql[i:i+len(lowerName)]) != lowerName { - continue - } - if i > 0 && isIdentByte(sql[i-1]) { - continue - } - j := i + len(lowerName) - for j < len(sql) && (sql[j] == ' ' || sql[j] == '\t' || sql[j] == '\n') { - j++ - } - if j < len(sql) && sql[j] == '(' { - return i - } - } - return -1 -} - -func splitCallArgs(sql string, afterName int) (args []string, end int, ok bool) { - m := codeMask(sql) - i := afterName - for i < len(sql) && sql[i] != '(' { - if sql[i] != ' ' && sql[i] != '\t' && sql[i] != '\n' { - return nil, 0, false - } - i++ - } - if i >= len(sql) || sql[i] != '(' { - return nil, 0, false - } - depth := 0 - start := i + 1 - for ; i < len(sql); i++ { - if !m[i] { - continue - } - switch sql[i] { - case '(': - depth++ - case ')': - depth-- - if depth == 0 { - args = append(args, sql[start:i]) - return args, i + 1, true - } - case ',': - if depth == 1 { - args = append(args, sql[start:i]) - start = i + 1 - } - } - } - return nil, 0, false -} - -func rewriteFuncCalls(sql, name string, rebuild func(args []string) string) string { - lower := strings.ToLower(name) - searchFrom := 0 - for { - idx := findCallStart(sql, lower, searchFrom) - if idx < 0 { - return sql - } - args, end, ok := splitCallArgs(sql, idx+len(name)) - if !ok { - searchFrom = idx + len(name) - continue - } - for i := range args { - args[i] = rewriteFuncCalls(strings.TrimSpace(args[i]), name, rebuild) - } - rebuilt := rebuild(args) - sql = sql[:idx] + rebuilt + sql[end:] - searchFrom = idx + len(rebuilt) - } -} diff --git a/internal/storage/sqlitedialect/translate_test.go b/internal/storage/sqlitedialect/translate_test.go deleted file mode 100644 index 17f609e75..000000000 --- a/internal/storage/sqlitedialect/translate_test.go +++ /dev/null @@ -1,48 +0,0 @@ -package sqlitedialect - -import ( - "strings" - "testing" -) - -func TestTranslate(t *testing.T) { - cases := []struct { - name string - in string - want string // substring that must appear - notWant string // substring that must NOT appear - }{ - {"insert ignore", "INSERT IGNORE INTO labels (a) VALUES (?)", "INSERT OR IGNORE INTO", "INSERT IGNORE INTO"}, - {"concat", "SELECT CONCAT(a, b)", "(a || b)", "CONCAT"}, - {"now", "SELECT NOW()", "CURRENT_TIMESTAMP", "NOW()"}, - {"utc_timestamp", "SELECT UTC_TIMESTAMP()", "CURRENT_TIMESTAMP", "UTC_TIMESTAMP"}, - {"json_arrayagg", "SELECT JSON_ARRAYAGG(x)", "json_group_array(x)", "JSON_ARRAYAGG"}, - {"json_unquote unwrap", "SELECT JSON_UNQUOTE(JSON_EXTRACT(m, '$.k'))", "JSON_EXTRACT(m, '$.k')", "JSON_UNQUOTE"}, - {"date_format", "SELECT DATE_FORMAT(created_at, '%Y-%m-%dT%H:%i:%sZ')", "strftime('%Y-%m-%dT%H:%M:%SZ', created_at)", "DATE_FORMAT"}, - {"binary label collation", "SELECT label FROM labels WHERE issue_id = ? ORDER BY label", "ORDER BY label COLLATE BINARY", "utf8mb4_0900_bin"}, - {"update alias", "UPDATE issues i SET i.is_blocked = 1 WHERE i.id IN (?)", "UPDATE issues AS i SET", ""}, - {"on duplicate key", "INSERT INTO issues (id) VALUES (?) ON DUPLICATE KEY UPDATE title = VALUES(title)", "ON CONFLICT (id) DO UPDATE SET title = excluded.title", "DUPLICATE"}, - {"greatest", "SELECT GREATEST(last_child, ?)", "max(last_child, ?)", "GREATEST"}, - {"least", "SELECT LEAST(a, b)", "min(a, b)", "LEAST"}, - // The exact child-counter upsert from issueops/create.go: GREATEST must be - // rewritten to SQLite's scalar max even inside the ON DUPLICATE KEY envelope, - // otherwise hierarchical dotted child IDs fail on SQLite. - {"child counter upsert", "INSERT INTO child_counters (parent_id, last_child) VALUES (?, ?) ON DUPLICATE KEY UPDATE last_child = GREATEST(last_child, ?)", "ON CONFLICT (parent_id) DO UPDATE SET last_child = max(last_child, ?)", "GREATEST"}, - // The lease upsert from issueops/lease.go (bd-lrgn1): leases keys on - // issue_id, so the arbiter map must know it or the upsert fails at PREPARE. - {"lease upsert", "INSERT INTO leases (issue_id, holder) VALUES (?, ?) ON DUPLICATE KEY UPDATE holder = VALUES(holder)", "ON CONFLICT (issue_id) DO UPDATE SET holder = excluded.holder", "DUPLICATE"}, - {"lease import-restore live guard", "INSERT INTO leases (issue_id, holder) VALUES (?, ?) ON DUPLICATE KEY UPDATE holder = IF(leases.lease_expires_at >= ?, leases.holder, VALUES(holder))", "ON CONFLICT (issue_id) DO UPDATE SET holder = CASE WHEN leases.lease_expires_at >= ? THEN leases.holder ELSE excluded.holder END", "IF("}, - {"passthrough select", "SELECT * FROM issues WHERE id = ?", "SELECT * FROM issues WHERE id = ?", ""}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - got := Translate(tc.in) - if tc.want != "" && !strings.Contains(got, tc.want) { - t.Errorf("Translate(%q) = %q; missing %q", tc.in, got, tc.want) - } - if tc.notWant != "" && strings.Contains(got, tc.notWant) { - t.Errorf("Translate(%q) = %q; must not contain %q", tc.in, got, tc.notWant) - } - }) - } -} diff --git a/internal/storage/sqlkit/annotations.go b/internal/storage/sqlkit/annotations.go deleted file mode 100644 index 0db42db11..000000000 --- a/internal/storage/sqlkit/annotations.go +++ /dev/null @@ -1,89 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// AddIssueComment adds a structured comment to an issue, stamped with the -// current UTC time. issueops verifies the issue exists and wisp-routes. -func (s *Store) AddIssueComment(ctx context.Context, issueID, author, text string) (*types.Comment, error) { - var result *types.Comment - err := s.withWriteTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.AddIssueCommentInTx(ctx, tx, issueID, author, text) - return e - }) - return result, err -} - -// GetIssueComments returns all comments on an issue, oldest first. -func (s *Store) GetIssueComments(ctx context.Context, issueID string) ([]*types.Comment, error) { - var result []*types.Comment - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetIssueCommentsInTx(ctx, tx, issueID) - return e - }) - return result, err -} - -// GetEvents returns the audit-trail events for an issue (limit <= 0 = all). -func (s *Store) GetEvents(ctx context.Context, issueID string, limit int) ([]*types.Event, error) { - var result []*types.Event - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetEventsInTx(ctx, tx, issueID, limit) - return e - }) - return result, err -} - -// CountIssueComments returns the number of comments on an issue. Intentionally -// not wisp-routed — mirrors the dolt body for oracle parity. -func (s *Store) CountIssueComments(ctx context.Context, issueID string) (int64, error) { - var n int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - return tx.QueryRowContext(ctx, - "SELECT count(*) FROM comments WHERE issue_id = ?", issueID).Scan(&n) - }) - return n, err -} - -// CountEvents returns the number of audit events for an issue, capped at limit -// (or unbounded if limit == 0). Not wisp-routed, matching the dolt body. -func (s *Store) CountEvents(ctx context.Context, issueID string, limit int) (int64, error) { - var n int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - return tx.QueryRowContext(ctx, - "SELECT count(*) FROM events WHERE issue_id = ?", issueID).Scan(&n) - }) - if err != nil { - return 0, err - } - if limit > 0 && n > int64(limit) { - n = int64(limit) - } - return n, nil -} - -// SetLocalMetadata writes a clone-local (dolt-ignored) metadata value. -func (s *Store) SetLocalMetadata(ctx context.Context, key, value string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.SetLocalMetadataInTx(ctx, tx, key, value) - }) -} - -// GetLocalMetadata reads a clone-local metadata value ("" when absent). -func (s *Store) GetLocalMetadata(ctx context.Context, key string) (string, error) { - var v string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - v, e = issueops.GetLocalMetadataInTx(ctx, tx, key) - return e - }) - return v, err -} diff --git a/internal/storage/sqlkit/capabilities.go b/internal/storage/sqlkit/capabilities.go deleted file mode 100644 index 559e00566..000000000 --- a/internal/storage/sqlkit/capabilities.go +++ /dev/null @@ -1,328 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/config" - "github.com/steveyegge/beads/internal/storage/domain" - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// This file fills in the capability surface the CLI verbs reach but the earlier -// implement-set left as typed-unsupported stubs on the backend shell. Every -// method is a thin delegation to the backend-neutral issueops layer, mirroring -// the internal/storage/dolt/*.go bodies with the Dolt residue (DOLT_ADD/COMMIT, -// per-lifetime caches, the wisp-batch write-timeout workaround) dropped: wisps -// live in the same database here, so a single *sql.Tx serves every table and -// issueops does its own wisp partitioning internally. - -// --- blocking / newly-unblocked reads --- - -// IsBlocked reports whether an issue is blocked by open dependencies, returning -// the blocker IDs. -func (s *Store) IsBlocked(ctx context.Context, issueID string) (bool, []string, error) { - var blocked bool - var blockers []string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - blocked, blockers, e = issueops.IsBlockedInTx(ctx, tx, issueID) - return e - }) - if err != nil { - return false, nil, err - } - return blocked, blockers, nil -} - -// GetNewlyUnblockedByClose finds issues that become unblocked when closedIssueID -// is closed. -func (s *Store) GetNewlyUnblockedByClose(ctx context.Context, closedIssueID string) ([]*types.Issue, error) { - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetNewlyUnblockedByCloseInTx(ctx, tx, closedIssueID) - return e - }) - return result, err -} - -// --- claim / delete / child-id writes --- - -// ClaimIssue atomically claims an issue (assignee=actor, status=in_progress) -// only if it is currently unassigned. Runs in a mutation tx so the claim and its -// is_blocked reprojection commit atomically. -func (s *Store) ClaimIssue(ctx context.Context, id string, actor string) error { - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - _, err := issueops.ClaimIssueInTx(ctx, tx, id, actor) - return err - }) -} - -// UnclaimIssue releases a claim (clears assignee, returns to open) in a mutation -// tx so the change and its is_blocked reprojection commit atomically. -func (s *Store) UnclaimIssue(ctx context.Context, id string, actor string, force bool) error { - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - return issueops.UnclaimIssueInTx(ctx, tx, id, actor, force) - }) -} - -// ClaimReadyIssue atomically claims the first ready issue matching filter, or -// returns (nil, nil) when nothing is ready. -func (s *Store) ClaimReadyIssue(ctx context.Context, filter types.WorkFilter, actor string) (*types.Issue, error) { - var claimed *types.Issue - err := s.withMutationTx(ctx, func(tx *sql.Tx) error { - var e error - claimed, e = issueops.ClaimReadyIssueInTx(ctx, tx, filter, actor) - return e - }) - if err != nil { - return nil, err - } - return claimed, nil -} - -// DeleteIssues deletes multiple issues in a single transaction. issueops does -// its own wisp partitioning and cascade/force/orphan handling, so all IDs go -// straight through — dolt's outer wisp-batch loop is a write-timeout workaround -// that does not apply here. The partial result is preserved alongside an error -// so OrphanedIssues survives the non-cascade/non-force rejection path. -func (s *Store) DeleteIssues(ctx context.Context, ids []string, cascade bool, force bool, dryRun bool) (*types.DeleteIssuesResult, error) { - if len(ids) == 0 { - return &types.DeleteIssuesResult{}, nil - } - var result *types.DeleteIssuesResult - err := s.withMutationTx(ctx, func(tx *sql.Tx) error { - r, e := issueops.DeleteIssuesInTx(ctx, tx, ids, cascade, force, dryRun) - result = r - return e - }) - return result, err -} - -// GetNextChildID returns the next available child ID for a parent, seeding and -// bumping the child_counters row in the same tx. -func (s *Store) GetNextChildID(ctx context.Context, parentID string) (string, error) { - var childID string - err := s.withMutationTx(ctx, func(tx *sql.Tx) error { - var e error - childID, e = issueops.GetNextChildIDTx(ctx, tx, parentID) - return e - }) - return childID, err -} - -// --- custom statuses / types (uncached; the dolt cache is only an optimization) --- - -// GetCustomStatusesDetailed returns the configured custom statuses with their -// full definitions. -func (s *Store) GetCustomStatusesDetailed(ctx context.Context) ([]types.CustomStatus, error) { - // Read the normalized custom_statuses table (ORDER BY name), matching the - // embedded-Dolt reference — SetConfig("status.custom") keeps it in sync. On a tx - // error fall back to config.yaml exactly as dolt does. - var result []types.CustomStatus - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.ResolveCustomStatusesDetailedInTx(ctx, tx) - return e - }) - if err != nil { - if yamlStatuses := config.GetCustomStatusesFromYAML(); len(yamlStatuses) > 0 { - return issueops.ParseStatusFallback(yamlStatuses), nil - } - return nil, nil - } - return result, nil -} - -// GetCustomStatuses returns the configured custom status names. -func (s *Store) GetCustomStatuses(ctx context.Context) ([]string, error) { - detailed, err := s.GetCustomStatusesDetailed(ctx) - if err != nil { - return nil, err - } - return types.CustomStatusNames(detailed), nil -} - -// GetCustomTypes returns the configured custom issue-type values. -func (s *Store) GetCustomTypes(ctx context.Context) ([]string, error) { - // Read the normalized custom_types table (ORDER BY name), matching the embedded-Dolt - // reference; SetConfig("types.custom") keeps it in sync. Fall back to config.yaml on a - // tx error, as dolt does. - var result []string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.ResolveCustomTypesInTx(ctx, tx) - return e - }) - if err != nil { - if yamlTypes := config.GetCustomTypesFromYAML(); len(yamlTypes) > 0 { - return yamlTypes, nil - } - return nil, err - } - return result, nil -} - -// --- infra types --- - -// GetInfraTypes returns the infrastructure type names (routed to the wisps -// table). issueops resolves DB config → config.yaml → defaults; on a tx error it -// yields nil, in which case we fall back to YAML-then-defaults exactly as dolt -// does. These signatures have no error channel, so a silent nil here would let -// `bd wisp gc` hard-delete protected infra beads — hence the explicit fallback. -func (s *Store) GetInfraTypes(ctx context.Context) map[string]bool { - var result map[string]bool - if err := s.withReadTx(ctx, func(tx *sql.Tx) error { - result = issueops.ResolveInfraTypesInTx(ctx, tx) - return nil - }); err != nil || result == nil { - var typeList []string - if yamlTypes := config.GetInfraTypesFromYAML(); len(yamlTypes) > 0 { - typeList = yamlTypes - } else { - typeList = domain.DefaultInfraTypes() - } - result = make(map[string]bool, len(typeList)) - for _, t := range typeList { - result[t] = true - } - } - return result -} - -// IsInfraTypeCtx reports whether t is a configured infrastructure type. -func (s *Store) IsInfraTypeCtx(ctx context.Context, t types.IssueType) bool { - return s.GetInfraTypes(ctx)[string(t)] -} - -// --- metadata / config --- - -// GetMetadata reads a metadata value ("" when absent). -func (s *Store) GetMetadata(ctx context.Context, key string) (string, error) { - var value string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - value, e = issueops.GetMetadataInTx(ctx, tx, key) - return e - }) - return value, err -} - -// SetMetadata writes a metadata value. Metadata cannot change is_blocked, so -// this uses a plain write tx. -func (s *Store) SetMetadata(ctx context.Context, key, value string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.SetMetadataInTx(ctx, tx, key, value) - }) -} - -// DeleteConfig removes a config value. -func (s *Store) DeleteConfig(ctx context.Context, key string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.DeleteConfigInTx(ctx, tx, key) - }) -} - -// --- batch reads (permanent + wisp mixed-table union handled inside issueops) --- - -// GetBlockingInfoForIssues returns the blocked-by, blocks, and parent maps for a -// set of issue IDs. -func (s *Store) GetBlockingInfoForIssues(ctx context.Context, issueIDs []string) ( - blockedByMap map[string][]string, - blocksMap map[string][]string, - parentMap map[string]string, - err error, -) { - err = s.withReadTx(ctx, func(tx *sql.Tx) error { - var txErr error - blockedByMap, blocksMap, parentMap, txErr = issueops.GetBlockingInfoForIssuesInTx(ctx, tx, issueIDs) - return txErr - }) - return -} - -// GetDependencyCounts returns dependency/dependent counts for multiple issues. -func (s *Store) GetDependencyCounts(ctx context.Context, issueIDs []string) (map[string]*types.DependencyCounts, error) { - var result map[string]*types.DependencyCounts - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetDependencyCountsInTx(ctx, tx, issueIDs) - return e - }) - return result, err -} - -// GetCommentCounts returns the comment count for each issue in a single batch. -func (s *Store) GetCommentCounts(ctx context.Context, issueIDs []string) (map[string]int, error) { - var result map[string]int - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetCommentCountsInTx(ctx, tx, issueIDs) - return e - }) - return result, err -} - -// GetLabelsForIssues returns the labels for each issue in a single batch. -func (s *Store) GetLabelsForIssues(ctx context.Context, issueIDs []string) (map[string][]string, error) { - var result map[string][]string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetLabelsForIssuesInTx(ctx, tx, issueIDs) - return e - }) - return result, err -} - -// GetCommentsForIssues returns the comments for each issue in a single batch. -func (s *Store) GetCommentsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Comment, error) { - var result map[string][]*types.Comment - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetCommentsForIssuesInTx(ctx, tx, issueIDs) - return e - }) - return result, err -} - -// GetDependencyRecords returns the raw dependency rows for a single issue. -// Delegates to the batch helper, which partitions wisp vs permanent IDs and -// resolves targets via the split physical columns internally. -func (s *Store) GetDependencyRecords(ctx context.Context, issueID string) ([]*types.Dependency, error) { - var deps []*types.Dependency - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - byID, e := issueops.GetDependencyRecordsForIssuesInTx(ctx, tx, []string{issueID}) - if e != nil { - return e - } - deps = byID[issueID] - return nil - }) - return deps, err -} - -// GetDependencyRecordsForIssues returns the raw dependency rows for multiple -// issues. -func (s *Store) GetDependencyRecordsForIssues(ctx context.Context, issueIDs []string) (map[string][]*types.Dependency, error) { - var result map[string][]*types.Dependency - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.GetDependencyRecordsForIssuesInTx(ctx, tx, issueIDs) - return e - }) - return result, err -} - -// DetectCycles finds circular dependencies across both the permanent and wisp -// dependency tables. -func (s *Store) DetectCycles(ctx context.Context) ([][]*types.Issue, error) { - var result [][]*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - result, e = issueops.DetectCyclesInTx(ctx, tx) - return e - }) - return result, err -} diff --git a/internal/storage/sqlkit/dependencies.go b/internal/storage/sqlkit/dependencies.go deleted file mode 100644 index bf7922e8a..000000000 --- a/internal/storage/sqlkit/dependencies.go +++ /dev/null @@ -1,161 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - "strings" - - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// AddDependency adds a dependency between two issues. Routing (which -// dependency table the edge lives in, and how the target is classified) is -// resolved inside the mutation tx via IsActiveWispInTx; issueops.AddDependencyInTx -// validates, cycle-checks, and inserts. Running everything in withMutationTx -// commits the edge and its is_blocked reprojection atomically. -func (s *Store) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error { - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - isCrossPrefix := types.ExtractPrefix(dep.IssueID) != types.ExtractPrefix(dep.DependsOnID) - - writeTable, sourceTable := "dependencies", "issues" - if issueops.IsActiveWispInTx(ctx, tx, dep.IssueID) { - writeTable, sourceTable = "wisp_dependencies", "wisps" - } - - targetTable := "issues" - kind := issueops.DepTargetIssue - switch { - case isCrossPrefix, strings.HasPrefix(dep.DependsOnID, "external:"): - kind = issueops.DepTargetExternal - default: - if issueops.IsActiveWispInTx(ctx, tx, dep.DependsOnID) { - targetTable = "wisps" - kind = issueops.DepTargetWisp - } - } - - return issueops.AddDependencyInTx(ctx, tx, dep, actor, issueops.AddDependencyOpts{ - SourceTable: sourceTable, - TargetTable: targetTable, - WriteTable: writeTable, - IsCrossPrefix: isCrossPrefix, - TargetKind: &kind, - }) - }) -} - -// RemoveDependency removes a dependency between two issues. issueops handles -// wisp routing internally, so both source classes collapse to one call. actor -// is unused (kept to satisfy the storage.Storage signature). -func (s *Store) RemoveDependency(ctx context.Context, issueID, dependsOnID string, actor string) error { - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - return issueops.RemoveDependencyInTx(ctx, tx, issueID, dependsOnID) - }) -} - -// GetDependencies retrieves issues that this issue depends on. -func (s *Store) GetDependencies(ctx context.Context, issueID string) ([]*types.Issue, error) { - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetDependenciesInTx(ctx, tx, issueID) - return err - }) - return result, err -} - -// GetDependents retrieves issues that depend on this issue. -func (s *Store) GetDependents(ctx context.Context, issueID string) ([]*types.Issue, error) { - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetDependentsInTx(ctx, tx, issueID) - return err - }) - return result, err -} - -// GetDependenciesWithMetadata returns dependencies with their edge metadata. -// issueops queries both dependencies and wisp_dependencies and hydrates the -// targets, so there is no store-level wisp branch or inline SQL. -func (s *Store) GetDependenciesWithMetadata(ctx context.Context, issueID string) ([]*types.IssueWithDependencyMetadata, error) { - var result []*types.IssueWithDependencyMetadata - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetDependenciesWithMetadataInTx(ctx, tx, issueID) - return err - }) - return result, err -} - -// GetDependentsWithMetadata returns dependents with their edge metadata. -func (s *Store) GetDependentsWithMetadata(ctx context.Context, issueID string) ([]*types.IssueWithDependencyMetadata, error) { - var result []*types.IssueWithDependencyMetadata - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetDependentsWithMetadataInTx(ctx, tx, issueID) - return err - }) - return result, err -} - -// GetDependencyTree returns a dependency tree for visualization. -func (s *Store) GetDependencyTree(ctx context.Context, issueID string, maxDepth int, showAllPaths bool, reverse bool) ([]*types.TreeNode, error) { - var result []*types.TreeNode - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetDependencyTreeInTx(ctx, tx, issueID, maxDepth, showAllPaths, reverse) - return err - }) - return result, err -} - -// CountDependents returns the number of issues that depend on issueID. -// Counts both dependency tables so the total matches GetDependentsWithMetadata: -// a dependent may be a permanent issue (edge in `dependencies`) or a wisp (edge -// in `wisp_dependencies`, routed there by WispTableRouting on the source). -// -// Both tables' targets are resolved via issueops.DepTargetExpr (the split -// physical columns) rather than the STORED generated depends_on_id, which a -// count(*) can fail to resolve under the pure-Go GMS analyzer. -func (s *Store) CountDependents(ctx context.Context, issueID string) (int64, error) { - var n int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var perm, wisp int64 - if err := tx.QueryRowContext(ctx, - `SELECT count(*) FROM dependencies WHERE `+issueops.DepTargetExpr+` = ?`, issueID).Scan(&perm); err != nil { - return err - } - if err := tx.QueryRowContext(ctx, - `SELECT count(*) FROM wisp_dependencies WHERE `+issueops.DepTargetExpr+` = ?`, issueID).Scan(&wisp); err != nil { - return err - } - n = perm + wisp - return nil - }) - return n, err -} - -// CountDependencies returns the number of issues that issueID depends on. -// Counts both dependency tables so the total matches GetDependenciesWithMetadata: -// a wisp's outgoing edges live in `wisp_dependencies`, a permanent issue's in -// `dependencies`. Counted as two separate queries summed in Go (see -// CountDependents for why a single combined query is avoided). -func (s *Store) CountDependencies(ctx context.Context, issueID string) (int64, error) { - var n int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var perm, wisp int64 - if err := tx.QueryRowContext(ctx, - `SELECT count(*) FROM dependencies WHERE issue_id = ?`, issueID).Scan(&perm); err != nil { - return err - } - if err := tx.QueryRowContext(ctx, - `SELECT count(*) FROM wisp_dependencies WHERE issue_id = ?`, issueID).Scan(&wisp); err != nil { - return err - } - n = perm + wisp - return nil - }) - return n, err -} diff --git a/internal/storage/sqlkit/issues.go b/internal/storage/sqlkit/issues.go deleted file mode 100644 index 93a3629b4..000000000 --- a/internal/storage/sqlkit/issues.go +++ /dev/null @@ -1,312 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - "encoding/json" - "fmt" - "os" - "strings" - "time" - - "github.com/steveyegge/beads/internal/config" - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// CreateIssue creates a new issue. Wisp routing (ephemeral / no-history / infra -// type) is resolved inside the tx; issueops picks the wisps table from there. -func (s *Store) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error { - if issue == nil { - return fmt.Errorf("issue must not be nil") - } - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - // Route to wisps if ephemeral, no-history, or an infra type. Infra types - // get marked ephemeral (legacy behavior); TableRouting inside issueops - // then selects the wisps table. - useWisps := issue.Ephemeral || issue.NoHistory || - issueops.ResolveInfraTypesInTx(ctx, tx)[string(issue.IssueType)] - if useWisps && !issue.NoHistory { - issue.Ephemeral = true - } - // SkipPrefixValidation matches legacy: the single-issue path never - // prefix-validates explicit IDs. - bc, err := issueops.NewBatchContext(ctx, tx, storage.BatchCreateOptions{ - SkipPrefixValidation: true, - }) - if err != nil { - return err - } - _, err = issueops.CreateIssueInTxWithResult(ctx, tx, bc, issue, actor) - return err - }) -} - -// CreateIssues creates multiple issues in a single transaction. issueops routes -// mixed batches per issue and validates cross-bucket dependencies internally. -func (s *Store) CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error { - if len(issues) == 0 { - return nil - } - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - _, err := issueops.CreateIssuesInTxWithResult(ctx, tx, issues, actor, storage.BatchCreateOptions{ - OrphanHandling: storage.OrphanAllow, - SkipPrefixValidation: false, - }) - return err - }) -} - -// GetIssue retrieves an issue by ID. Returns storage.ErrNotFound (wrapped) when -// the issue does not exist. -func (s *Store) GetIssue(ctx context.Context, id string) (*types.Issue, error) { - var issue *types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - issue, e = issueops.GetIssueInTx(ctx, tx, id) - return e - }) - return issue, err -} - -// GetIssueByExternalRef retrieves an issue by its external reference, spanning both -// the issues and wisps tiers. Returns a wrapped storage.ErrNotFound when none matches. -// Resolves the ID in a read tx (issueops), then reuses GetIssue so wisp-tier hydration -// and not-found semantics are identical to a normal fetch. -func (s *Store) GetIssueByExternalRef(ctx context.Context, externalRef string) (*types.Issue, error) { - var id string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - id, e = issueops.GetIssueByExternalRefInTx(ctx, tx, externalRef) - return e - }) - if err != nil { - return nil, err - } - return s.GetIssue(ctx, id) -} - -// GetIssuesByIDs retrieves multiple issues by ID, spanning both the issues and -// wisps tiers. -func (s *Store) GetIssuesByIDs(ctx context.Context, ids []string) ([]*types.Issue, error) { - if len(ids) == 0 { - return nil, nil - } - var out []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetIssuesByIDsInTx(ctx, tx, ids, nil) - return e - }) - return out, err -} - -// UpdateIssue updates fields on an issue. Metadata is validated against the -// configured schema before delegation; wisp routing happens inside issueops. -func (s *Store) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error { - // Validate metadata against schema before delegation (GH#1416 Phase 2). - if rawMeta, ok := updates["metadata"]; ok { - metadataStr, err := storage.NormalizeMetadataValue(rawMeta) - if err != nil { - return fmt.Errorf("invalid metadata: %w", err) - } - if err := validateMetadataIfConfigured(json.RawMessage(metadataStr)); err != nil { - return err - } - } - - // Setting no_history/wisp on a durable issue is an IN-PLACE column write on the - // embedded-Dolt reference (the default backend + our oracle): updateIssueInTx routes - // by IsActiveWispInTx and, for a durable id, updates the issues row in place — the row - // is NOT migrated to the wisps table (only the server-Dolt store's DemoteToWisp does - // that). Delegating to the same shared helper matches the reference exactly. - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - _, err := issueops.UpdateIssueInTx(ctx, tx, id, updates, actor) - return err - }) -} - -// UpdateIssueType changes the issue_type field of an issue. Type validation -// happens inside UpdateIssueInTx via ResolveCustomTypesInTx. -func (s *Store) UpdateIssueType(ctx context.Context, id string, issueType string, actor string) error { - return s.UpdateIssue(ctx, id, map[string]interface{}{"issue_type": issueType}, actor) -} - -// ReopenIssue reopens a closed issue: sets status=open, clears closed_at and -// defer_until, records EventReopened, adds the reason comment when non-empty, -// and recomputes is_blocked for affected IDs — all in one tx. -func (s *Store) ReopenIssue(ctx context.Context, id string, reason string, actor string) error { - // Mirror the embedded-Dolt reference exactly: reopen via UpdateIssue (which always - // records a status event, bumps updated_at, and returns a wrapped storage.ErrNotFound - // for a missing id — even when the issue is already open), then attach the reason as a - // comment. The old issueops.ReopenIssueInTx path used WHERE status='closed', which made - // reopening an already-open issue a silent no-op and returned a plain not-found error. - updates := map[string]interface{}{ - "status": string(types.StatusOpen), - "defer_until": nil, - } - if err := s.UpdateIssue(ctx, id, updates, actor); err != nil { - return err - } - if reason != "" { - return s.AddComment(ctx, id, actor, reason) - } - return nil -} - -// DeleteIssue permanently removes an issue. issueops routes wisps internally and -// recomputes is_blocked for affected neighbors. -func (s *Store) DeleteIssue(ctx context.Context, id string) error { - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - return issueops.DeleteIssueInTx(ctx, tx, id) - }) -} - -// HeartbeatIssue renews the lease on a claimed issue. Mirrors embeddeddolt: -// wisps are ephemeral and never leased, so heartbeating one is ErrNotClaimable; -// otherwise delegate to issueops.HeartbeatIssueInTx. -func (s *Store) HeartbeatIssue(ctx context.Context, id, actor string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - if issueops.IsActiveWispInTx(ctx, tx, id) { - return fmt.Errorf("%w: %s is ephemeral", storage.ErrNotClaimable, id) - } - return issueops.HeartbeatIssueInTx(ctx, tx, id, actor) - }) -} - -// ReclaimExpiredLeases reverts in_progress issues whose lease expired more than -// olderThan ago back to ready, recovering work stranded by dead workers. Mirrors -// embeddeddolt (issueops.ReclaimExpiredLeasesInTx does the shared SQL). -func (s *Store) ReclaimExpiredLeases(ctx context.Context, olderThan time.Duration, actor string) ([]types.ReclaimedLease, error) { - cutoff := time.Now().UTC().Add(-olderThan) - var reclaimed []types.ReclaimedLease - err := s.withWriteTx(ctx, func(tx *sql.Tx) error { - var err error - reclaimed, err = issueops.ReclaimExpiredLeasesInTx(ctx, tx, cutoff, actor) - return err - }) - return reclaimed, err -} - -// --- metadata schema helpers (config-only; copied from dolt/metadata_schema.go) --- - -// loadMetadataSchema reads the metadata validation config from YAML and -// returns a parsed schema. Returns mode "none" with empty fields if config -// is not initialized, mode is empty/unknown, or no fields are defined. -func loadMetadataSchema() storage.MetadataSchemaConfig { - mode := config.MetadataValidationMode() - if mode == "none" { - return storage.MetadataSchemaConfig{Mode: "none"} - } - - rawFields := config.MetadataSchemaFields() - if rawFields == nil { - return storage.MetadataSchemaConfig{Mode: "none"} - } - - 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 storage.MetadataSchemaConfig{Mode: "none"} - } - - return storage.MetadataSchemaConfig{ - Mode: mode, - Fields: fields, - } -} - -// 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 - } - - // Parse enum values - 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: - // Comma-separated fallback - for _, s := range strings.Split(v, ",") { - s = strings.TrimSpace(s) - if s != "" { - schema.Values = append(schema.Values, s) - } - } - } - } - - // Parse min/max for numeric types - if min, ok := toFloat64(m["min"]); ok { - schema.Min = &min - } - if max, ok := toFloat64(m["max"]); ok { - schema.Max = &max - } - - return schema -} - -// toFloat64 converts an interface{} to float64, handling int and float YAML values. -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 - } -} - -// validateMetadataIfConfigured checks metadata against the schema from config. -// In "warn" mode, prints warnings to stderr and returns nil. -// In "error" mode, returns the first validation error. -// In "none" mode (or if config is not initialized), does nothing. -func validateMetadataIfConfigured(metadata json.RawMessage) error { - schema := loadMetadataSchema() - if schema.Mode == "none" { - return nil - } - - errs := storage.ValidateMetadataSchema(metadata, schema) - if len(errs) == 0 { - return nil - } - - if schema.Mode == "warn" { - for _, e := range errs { - fmt.Fprintf(os.Stderr, "warning: %s\n", e.Error()) - } - return nil - } - - // mode == "error" - return fmt.Errorf("metadata schema violation: %s", errs[0].Error()) -} diff --git a/internal/storage/sqlkit/iter.go b/internal/storage/sqlkit/iter.go deleted file mode 100644 index 12528b15b..000000000 --- a/internal/storage/sqlkit/iter.go +++ /dev/null @@ -1,150 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - "fmt" - "sort" - "strings" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/storage/sqlbuild" - "github.com/steveyegge/beads/internal/types" -) - -// IterIssues returns issues matching the filter from the `issues` table only. -// -// Unlike SearchIssues (which merges the wisps tier), this iterator is -// contractually issues-table-only; callers that need wisps stream IterWisps -// separately. Rows and their labels are read inside one read tx, then wrapped -// in a SliceIter (buffer-then-hydrate keeps everything on one connection). -func (s *Store) IterIssues(ctx context.Context, query string, filter types.IssueFilter) (storage.Iter[types.Issue], error) { - whereClauses, args, err := issueops.BuildIssueFilterClauses(query, filter, issueops.IssuesFilterTables) - if err != nil { - return nil, fmt.Errorf("iter issues: build filter: %w", err) - } - whereSQL := "" - if len(whereClauses) > 0 { - whereSQL = "WHERE " + strings.Join(whereClauses, " AND ") - } - limitSQL := "" - if filter.Limit > 0 { - limitSQL = fmt.Sprintf(" LIMIT %d", filter.Limit) - } - - //nolint:gosec // G201: whereSQL contains column comparisons with ?, limitSQL is a safe integer - q := fmt.Sprintf(`SELECT %s FROM issues %s %s ORDER BY priority ASC, created_at DESC, id ASC%s`, - issueops.IssueSelectColumns, sqlbuild.LeaseJoin("issues"), whereSQL, limitSQL) - - var issues []*types.Issue - txErr := s.withReadTx(ctx, func(tx *sql.Tx) error { - rows, err := tx.QueryContext(ctx, q, args...) - if err != nil { - return fmt.Errorf("iter issues: query: %w", err) - } - defer func() { _ = rows.Close() }() - ids := make([]string, 0) - for rows.Next() { - iss, scanErr := issueops.ScanIssueFrom(rows) - if scanErr != nil { - return fmt.Errorf("iter issues: scan: %w", scanErr) - } - issues = append(issues, iss) - ids = append(ids, iss.ID) - } - if err := rows.Err(); err != nil { - return fmt.Errorf("iter issues: rows: %w", err) - } - // A *sql.Tx is bound to one connection, so the cursor must be closed - // before the label query can run on it (idempotent with the defer). - _ = rows.Close() - labelMap, err := issueops.GetLabelsForIssuesFromTableInTx(ctx, tx, "labels", ids) - if err != nil { - return fmt.Errorf("iter issues: hydrate labels: %w", err) - } - for _, iss := range issues { - if labels, ok := labelMap[iss.ID]; ok { - iss.Labels = labels - } - } - return nil - }) - if txErr != nil { - return nil, txErr - } - return storage.NewSliceIter(issues), nil -} - -// IterDependentsWithMetadata streams the dependents of an issue (both tables). -// The underlying slice path (GetDependentsWithMetadata) scans both dependency -// tables unordered, so we sort here to match dolt/iter_dependents.go's -// `ORDER BY created_at ASC` (the dependent issue's created_at), tiebreaking on -// ID for stable, deterministic output across backends. -func (s *Store) IterDependentsWithMetadata(ctx context.Context, issueID string) (storage.Iter[types.IssueWithDependencyMetadata], error) { - ds, err := s.GetDependentsWithMetadata(ctx, issueID) - if err != nil { - return nil, err - } - sort.SliceStable(ds, func(i, j int) bool { - if !ds[i].CreatedAt.Equal(ds[j].CreatedAt) { - return ds[i].CreatedAt.Before(ds[j].CreatedAt) - } - return ds[i].ID < ds[j].ID - }) - return storage.NewSliceIter(ds), nil -} - -// IterDependenciesWithMetadata streams the dependencies of an issue (both tables). -func (s *Store) IterDependenciesWithMetadata(ctx context.Context, issueID string) (storage.Iter[types.IssueWithDependencyMetadata], error) { - ds, err := s.GetDependenciesWithMetadata(ctx, issueID) - if err != nil { - return nil, err - } - return storage.NewSliceIter(ds), nil -} - -// IterIssueComments streams the comments on an issue. -func (s *Store) IterIssueComments(ctx context.Context, issueID string) (storage.Iter[types.Comment], error) { - cs, err := s.GetIssueComments(ctx, issueID) - if err != nil { - return nil, err - } - return storage.NewSliceIter(cs), nil -} - -// IterEvents streams the audit-trail events for an issue. -func (s *Store) IterEvents(ctx context.Context, issueID string, limit int) (storage.Iter[types.Event], error) { - ev, err := s.GetEvents(ctx, issueID, limit) - if err != nil { - return nil, err - } - return storage.NewSliceIter(ev), nil -} - -// IterReadyWork streams ready-work issues. -func (s *Store) IterReadyWork(ctx context.Context, filter types.WorkFilter) (storage.Iter[types.Issue], error) { - is, err := s.GetReadyWork(ctx, filter) - if err != nil { - return nil, err - } - return storage.NewSliceIter(is), nil -} - -// IterBlockedIssues streams blocked issues. -func (s *Store) IterBlockedIssues(ctx context.Context, filter types.WorkFilter) (storage.Iter[types.BlockedIssue], error) { - bs, err := s.GetBlockedIssues(ctx, filter) - if err != nil { - return nil, err - } - return storage.NewSliceIter(bs), nil -} - -// IterWisps streams ephemeral issues matching the filter. -func (s *Store) IterWisps(ctx context.Context, filter types.WispFilter) (storage.Iter[types.Issue], error) { - ws, err := s.ListWisps(ctx, filter) - if err != nil { - return nil, err - } - return storage.NewSliceIter(ws), nil -} diff --git a/internal/storage/sqlkit/labels.go b/internal/storage/sqlkit/labels.go deleted file mode 100644 index 919325425..000000000 --- a/internal/storage/sqlkit/labels.go +++ /dev/null @@ -1,56 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// AddLabel adds a label to an issue. Passing empty table names lets issueops -// auto-route between the permanent and wisp label/event tables. Labels cannot -// change is_blocked, so this uses withWriteTx. -func (s *Store) AddLabel(ctx context.Context, issueID, label, actor string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.AddLabelInTx(ctx, tx, "", "", issueID, label, actor) - }) -} - -// RemoveLabel removes a label from an issue. issueops handles wisp routing. -func (s *Store) RemoveLabel(ctx context.Context, issueID, label, actor string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.RemoveLabelInTx(ctx, tx, "", "", issueID, label, actor) - }) -} - -// GetLabels retrieves all labels for an issue. The empty table argument routes -// to the correct label table automatically. -func (s *Store) GetLabels(ctx context.Context, issueID string) ([]string, error) { - var labels []string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - labels, err = issueops.GetLabelsInTx(ctx, tx, "", issueID) - return err - }) - return labels, err -} - -// GetIssuesByLabel retrieves all issues carrying a specific label. Both the -// id lookup and the issue hydration run in one read tx (a single *sql.Tx serves -// every table since wisps live in the same DB). -func (s *Store) GetIssuesByLabel(ctx context.Context, label string) ([]*types.Issue, error) { - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - ids, err := issueops.GetIssuesByLabelInTx(ctx, tx, label) - if err != nil { - return err - } - if len(ids) == 0 { - return nil - } - result, err = issueops.GetIssuesByIDsInTx(ctx, tx, ids, nil) - return err - }) - return result, err -} diff --git a/internal/storage/sqlkit/portable.go b/internal/storage/sqlkit/portable.go deleted file mode 100644 index 9b111981f..000000000 --- a/internal/storage/sqlkit/portable.go +++ /dev/null @@ -1,218 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - "time" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// This file wires the shared "portable" non-version-control methods onto *Store. Each is -// the same thin issueops delegation the embedded-Dolt reference uses, so behavior is the -// reference's by construction; the dialect layer translates the underlying SQL. Reads run -// in a read tx, writes in a write tx. - -// --- Molecule rollups --- - -func (s *Store) GetMoleculeProgress(ctx context.Context, moleculeID string) (*types.MoleculeProgressStats, error) { - var out *types.MoleculeProgressStats - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetMoleculeProgressInTx(ctx, tx, moleculeID) - return e - }) - return out, err -} - -func (s *Store) GetMoleculeLastActivity(ctx context.Context, moleculeID string) (*types.MoleculeLastActivity, error) { - var out *types.MoleculeLastActivity - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetMoleculeLastActivityInTx(ctx, tx, moleculeID) - return e - }) - return out, err -} - -// --- Repo-mtime cache --- - -func (s *Store) GetRepoMtime(ctx context.Context, repoPath string) (int64, error) { - var out int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetRepoMtimeInTx(ctx, tx, repoPath) - return e - }) - return out, err -} - -func (s *Store) SetRepoMtime(ctx context.Context, repoPath, jsonlPath string, mtimeNs int64) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.SetRepoMtimeInTx(ctx, tx, repoPath, jsonlPath, mtimeNs) - }) -} - -func (s *Store) ClearRepoMtime(ctx context.Context, repoPath string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.ClearRepoMtimeInTx(ctx, tx, repoPath) - }) -} - -// --- Event / dependency streams --- - -func (s *Store) GetAllEventsSince(ctx context.Context, since time.Time) ([]*types.Event, error) { - var out []*types.Event - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetAllEventsSinceInTx(ctx, tx, since) - return e - }) - return out, err -} - -func (s *Store) IterAllEventsSince(ctx context.Context, since time.Time) (storage.Iter[types.Event], error) { - events, err := s.GetAllEventsSince(ctx, since) - if err != nil { - return nil, err - } - return storage.NewSliceIter(events), nil -} - -func (s *Store) GetAllDependencyRecords(ctx context.Context) (map[string][]*types.Dependency, error) { - var out map[string][]*types.Dependency - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetAllDependencyRecordsInTx(ctx, tx) - return e - }) - return out, err -} - -func (s *Store) IterAllDependencyRecords(ctx context.Context) (storage.Iter[types.Dependency], error) { - all, err := s.GetAllDependencyRecords(ctx) - if err != nil { - return nil, err - } - var flat []*types.Dependency - for _, deps := range all { - flat = append(flat, deps...) - } - return storage.NewSliceIter(flat), nil -} - -// --- Dependent counts --- - -// CountDependentsByStatus counts issues that depend on issueID whose source issue is in -// the given status, summed across the durable and wisp dependency tables. Mirrors the -// embedded-Dolt reference (counts.go): COALESCE resolves the edge target, and both -// classes are counted so a durable issue with a wisp dependent is not under-counted. -func (s *Store) CountDependentsByStatus(ctx context.Context, issueID string, status types.Status) (int64, error) { - var total int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var perm, wisp int64 - if err := tx.QueryRowContext(ctx, ` - SELECT COUNT(*) FROM dependencies d - JOIN issues i ON i.id = d.issue_id - WHERE COALESCE(d.depends_on_issue_id, d.depends_on_wisp_id, d.depends_on_external) = ? AND i.status = ? - `, issueID, string(status)).Scan(&perm); err != nil { - return err - } - if err := tx.QueryRowContext(ctx, ` - SELECT COUNT(*) FROM wisp_dependencies d - JOIN wisps w ON w.id = d.issue_id - WHERE COALESCE(d.depends_on_issue_id, d.depends_on_wisp_id, d.depends_on_external) = ? AND w.status = ? - `, issueID, string(status)).Scan(&wisp); err != nil { - return err - } - total = perm + wisp - return nil - }) - return total, err -} - -func (s *Store) FindWispDependentsRecursive(ctx context.Context, ids []string) (map[string]bool, error) { - var out map[string]bool - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.FindWispDependentsRecursiveInTx(ctx, tx, ids) - return e - }) - return out, err -} - -// --- Comment / audit writes --- - -func (s *Store) AddComment(ctx context.Context, issueID, actor, comment string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.AddCommentEventInTx(ctx, tx, issueID, actor, comment) - }) -} - -func (s *Store) ImportIssueComment(ctx context.Context, issueID, author, text string, createdAt time.Time) (*types.Comment, error) { - var out *types.Comment - err := s.withWriteTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.ImportIssueCommentInTx(ctx, tx, issueID, author, text, createdAt) - return e - }) - return out, err -} - -// --- Id rekey / wisp promote / source-repo purge --- - -func (s *Store) UpdateIssueID(ctx context.Context, oldID, newID string, issue *types.Issue, actor string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.UpdateIssueIDInTx(ctx, tx, oldID, newID, issue, actor) - }) -} - -func (s *Store) PromoteFromEphemeral(ctx context.Context, id, actor string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.PromoteFromEphemeralInTx(ctx, tx, id, actor) - }) -} - -func (s *Store) DeleteIssuesBySourceRepo(ctx context.Context, sourceRepo string) (int, error) { - var count int - err := s.withWriteTx(ctx, func(tx *sql.Tx) error { - var e error - count, e = issueops.DeleteIssuesBySourceRepoInTx(ctx, tx, sourceRepo) - return e - }) - return count, err -} - -// --- Batch create --- - -// CreateIssuesWithFullOptions mirrors the embedded-Dolt reference (dolt/issues.go): -// an all-wisps batch marks every issue ephemeral (unless it is explicitly -// no-history) so the rows route to the wisp tables, and EVERY batch — all-wisps or -// mixed/durable — is created in a SINGLE transaction through -// issueops.CreateIssuesInTx. That batch path is what threads opts, persists inline -// dependencies, applies conflict/stale policy, reconciles child counters, and -// recomputes is_blocked. The reference keeps two arms only to skip Dolt versioning -// for the all-wisps case; sqlkit has no Dolt versioning, so the arms differ solely -// in the ephemeral marking. -// -// Do NOT loop the single-issue issueops.CreateIssueInTx here: it never runs the -// dependency-persist pass, so an all-wisps batch carrying inline dependencies would -// silently drop every edge, and one transaction per issue would forfeit batch -// atomicity. -func (s *Store) CreateIssuesWithFullOptions(ctx context.Context, issues []*types.Issue, actor string, opts storage.BatchCreateOptions) error { - if len(issues) == 0 { - return nil - } - if issueops.AllWisps(issues) { - for _, issue := range issues { - if !issue.NoHistory { - issue.Ephemeral = true - } - } - } - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - return issueops.CreateIssuesInTx(ctx, tx, issues, actor, opts) - }) -} diff --git a/internal/storage/sqlkit/queries.go b/internal/storage/sqlkit/queries.go deleted file mode 100644 index ba4f8be3d..000000000 --- a/internal/storage/sqlkit/queries.go +++ /dev/null @@ -1,159 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// SearchIssues finds issues matching query and filters. -// Delegates to issueops.SearchIssuesInTx for shared query logic. -func (s *Store) SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) { - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.SearchIssuesInTx(ctx, tx, query, filter) - return err - }) - return result, err -} - -// SearchIssueIDs is the narrow-projection variant of SearchIssues, returning -// only matching ids. Delegates to issueops.SearchIssueIDsInTx (parity with the -// Dolt stores). -func (s *Store) SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error) { - var result []string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.SearchIssueIDsInTx(ctx, tx, query, filter) - return err - }) - return result, err -} - -// SearchIssuesWithCounts finds issues matching query and filters, hydrating -// per-issue dependency/dependent counts. -func (s *Store) SearchIssuesWithCounts(ctx context.Context, query string, filter types.IssueFilter) ([]*types.IssueWithCounts, error) { - var result []*types.IssueWithCounts - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.SearchIssuesWithCountsInTx(ctx, tx, query, filter) - return err - }) - return result, err -} - -// GetReadyWorkWithCounts returns ready-to-work issues with dependency counts. -func (s *Store) GetReadyWorkWithCounts(ctx context.Context, filter types.WorkFilter) ([]*types.IssueWithCounts, error) { - var result []*types.IssueWithCounts - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetReadyWorkWithCountsInTx(ctx, tx, filter) - return err - }) - return result, err -} - -// CountReadyWork returns the total ready-work count for filter. It is identical -// to len(GetReadyWorkWithCounts(filter with Limit=0)) but sizes the total with -// cheap indexed COUNT(*)s instead of re-running the counts mega-query, so every -// SQL backend (Postgres/MySQL/SQLite) satisfies storage.ReadyWorkCounter and -// `bd ready --json` prints "Showing X of N" without the unbounded pass. -func (s *Store) CountReadyWork(ctx context.Context, filter types.WorkFilter) (int, error) { - var n int - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - n, err = issueops.CountReadyWorkInTx(ctx, tx, filter) - return err - }) - return n, err -} - -// GetBlockedIssues returns issues that are blocked by open dependencies. -func (s *Store) GetBlockedIssues(ctx context.Context, filter types.WorkFilter) ([]*types.BlockedIssue, error) { - var result []*types.BlockedIssue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetBlockedIssuesInTx(ctx, tx, filter) - return err - }) - return result, err -} - -// GetStatistics returns summary statistics (counts, blocked, ready) for the workspace. -func (s *Store) GetStatistics(ctx context.Context) (*types.Statistics, error) { - var stats *types.Statistics - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - stats, err = issueops.GetStatisticsInTx(ctx, tx) - return err - }) - return stats, err -} - -// GetStaleIssues returns non-ephemeral issues not updated within the filter window. -func (s *Store) GetStaleIssues(ctx context.Context, filter types.StaleFilter) ([]*types.Issue, error) { - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetStaleIssuesInTx(ctx, tx, filter) - return err - }) - return result, err -} - -// GetEpicsEligibleForClosure returns epics whose children are all closed. -func (s *Store) GetEpicsEligibleForClosure(ctx context.Context) ([]*types.EpicStatus, error) { - var result []*types.EpicStatus - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.GetEpicsEligibleForClosureInTx(ctx, tx) - return err - }) - return result, err -} - -// ListWisps returns ephemeral issues matching the filter. -// It always queries the wisps table (Ephemeral=true); callers do not need to -// set that flag. WispFilterToIssueFilter sets Ephemeral=true (and excludes -// closed unless IncludeClosed), and SearchIssuesInTx routes Ephemeral=true -// queries to the wisps table. -func (s *Store) ListWisps(ctx context.Context, filter types.WispFilter) ([]*types.Issue, error) { - issueFilter := issueops.WispFilterToIssueFilter(filter) - var result []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.SearchIssuesInTx(ctx, tx, "", issueFilter) - return err - }) - return result, err -} - -// CountIssues returns the number of issues matching query and filter. -// Filter.Limit and Filter.Offset are ignored; all other fields apply. -func (s *Store) CountIssues(ctx context.Context, query string, filter types.IssueFilter) (int64, error) { - var n int64 - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - count, err := issueops.CountIssuesInTx(ctx, tx, query, filter) - if err != nil { - return err - } - n = int64(count) - return nil - }) - return n, err -} - -// CountIssuesByGroup returns per-group issue counts. groupBy is one of: -// status, priority, type, assignee, label. -func (s *Store) CountIssuesByGroup(ctx context.Context, filter types.IssueFilter, groupBy string) (map[string]int, error) { - var result map[string]int - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var err error - result, err = issueops.CountIssuesByGroupInTx(ctx, tx, filter, groupBy) - return err - }) - return result, err -} diff --git a/internal/storage/sqlkit/slots.go b/internal/storage/sqlkit/slots.go deleted file mode 100644 index a039110fb..000000000 --- a/internal/storage/sqlkit/slots.go +++ /dev/null @@ -1,88 +0,0 @@ -package sqlkit - -import ( - "context" - "encoding/json" - "fmt" -) - -// Metadata slots are a gt per-issue key/value store layered over the issue's metadata -// JSON column. They are pure GetIssue/UpdateIssue manipulation with no version-control -// dependency, so the logic is identical to the embedded-Dolt reference (slots.go). - -// SlotSet sets a key/value pair in the issue's metadata JSON. -func (s *Store) SlotSet(ctx context.Context, issueID, key, value, actor string) error { - issue, err := s.GetIssue(ctx, issueID) - if err != nil { - return fmt.Errorf("getting issue %s: %w", issueID, err) - } - - metadata := make(map[string]interface{}) - if len(issue.Metadata) > 0 { - if err := json.Unmarshal(issue.Metadata, &metadata); err != nil { - return fmt.Errorf("parsing metadata for %s: %w", issueID, err) - } - } - metadata[key] = value - - raw, err := json.Marshal(metadata) - if err != nil { - return fmt.Errorf("marshaling metadata for %s: %w", issueID, err) - } - return s.UpdateIssue(ctx, issueID, map[string]interface{}{"metadata": string(raw)}, actor) -} - -// SlotGet retrieves the value of a metadata key from an issue. -func (s *Store) SlotGet(ctx context.Context, issueID, key string) (string, error) { - issue, err := s.GetIssue(ctx, issueID) - if err != nil { - return "", fmt.Errorf("getting issue %s: %w", issueID, err) - } - if len(issue.Metadata) == 0 { - return "", fmt.Errorf("no slot %q on %s: no metadata", key, issueID) - } - - metadata := make(map[string]interface{}) - if err := json.Unmarshal(issue.Metadata, &metadata); err != nil { - return "", fmt.Errorf("parsing metadata for %s: %w", issueID, err) - } - val, ok := metadata[key] - if !ok { - return "", fmt.Errorf("no slot %q on %s: key not found", key, issueID) - } - if str, ok := val.(string); ok { - return str, nil - } - raw, err := json.Marshal(val) - if err != nil { - return "", fmt.Errorf("marshaling slot value for %s.%s: %w", issueID, key, err) - } - return string(raw), nil -} - -// SlotClear removes a metadata key from an issue. Clearing an absent key (or an issue -// with no metadata) is a silent no-op. -func (s *Store) SlotClear(ctx context.Context, issueID, key, actor string) error { - issue, err := s.GetIssue(ctx, issueID) - if err != nil { - return fmt.Errorf("getting issue %s: %w", issueID, err) - } - if len(issue.Metadata) == 0 { - return nil - } - - metadata := make(map[string]interface{}) - if err := json.Unmarshal(issue.Metadata, &metadata); err != nil { - return fmt.Errorf("parsing metadata for %s: %w", issueID, err) - } - if _, ok := metadata[key]; !ok { - return nil - } - delete(metadata, key) - - raw, err := json.Marshal(metadata) - if err != nil { - return fmt.Errorf("marshaling metadata for %s: %w", issueID, err) - } - return s.UpdateIssue(ctx, issueID, map[string]interface{}{"metadata": string(raw)}, actor) -} diff --git a/internal/storage/sqlkit/store.go b/internal/storage/sqlkit/store.go deleted file mode 100644 index 638098c13..000000000 --- a/internal/storage/sqlkit/store.go +++ /dev/null @@ -1,193 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - "errors" - "fmt" - "sync/atomic" - - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// ErrStoreClosed is returned when a method is called after Close. -var ErrStoreClosed = errors.New("store is closed") - -// Store is the shared SQL-family store. It delegates every operation to the -// backend-neutral internal/storage/issueops layer over a *sql.Tx, and is -// parameterized by a strategy bundle. Concrete backends embed *Store. -// -// NOTE: this encodes the strategy-bundle template. It implements a -// representative slice of the core surface (config, ready-work, close); the -// remaining ~50 delegation methods are mechanical fill-in (they mirror the -// internal/storage/dolt/*.go bodies, minus the Dolt-only residue) and land in -// the "implement-set" slice. -type Store struct { - db *sql.DB - dialect Dialect - readiness ReadinessStrategy - claim ClaimStrategy - - closed atomic.Bool -} - -// Config is the strategy bundle a backend supplies to build a Store. -type Config struct { - Dialect Dialect - Readiness ReadinessStrategy // defaults to NoopReadiness{} when nil - Claim ClaimStrategy // optional until the claim slice -} - -// New opens the backend via its Dialect and returns the shared Store. -func New(ctx context.Context, cfg Config) (*Store, error) { - if cfg.Dialect == nil { - return nil, errors.New("sqlkit: nil Dialect") - } - db, err := cfg.Dialect.Open(ctx) - if err != nil { - return nil, fmt.Errorf("sqlkit: open %s: %w", cfg.Dialect.Name(), err) - } - readiness := cfg.Readiness - if readiness == nil { - readiness = NoopReadiness{} - } - return &Store{db: db, dialect: cfg.Dialect, readiness: readiness, claim: cfg.Claim}, nil -} - -// DB exposes the underlying pool for diagnostics/migrations. -func (s *Store) DB() *sql.DB { return s.db } - -// DialectName reports the backend's dialect ("postgres", "sqlite", …). -func (s *Store) DialectName() string { return s.dialect.Name() } - -// Close closes the pool. Idempotent. -func (s *Store) Close() error { - if s.closed.Swap(true) { - return nil - } - return s.db.Close() -} - -// withReadTx runs fn in a read-only transaction that is always rolled back. -// -// ReadOnly is load-bearing on SQLite: the DSN's `_txlock=immediate` makes every -// default BeginTx issue BEGIN IMMEDIATE (modernc.org/sqlite honors it via -// beginMode), which takes SQLite's single write lock — so plain-BEGIN reads -// would queue behind any in-flight writer and fail with SQLITE_BUSY after -// busy_timeout, forfeiting WAL's reader/writer independence. TxOptions.ReadOnly -// suppresses beginMode (plain deferred BEGIN), letting reads run concurrently -// with a writer. On the server backends it maps to START TRANSACTION READ ONLY -// (mysql) / BEGIN READ ONLY (pgx), which every withReadTx callback satisfies: -// they are pure issueops reads. -func (s *Store) withReadTx(ctx context.Context, fn func(tx *sql.Tx) error) error { - if s.closed.Load() { - return ErrStoreClosed - } - tx, err := s.db.BeginTx(ctx, &sql.TxOptions{ReadOnly: true}) - if err != nil { - return fmt.Errorf("begin read tx: %w", err) - } - defer func() { _ = tx.Rollback() }() - return fn(tx) -} - -// withWriteTx runs fn and commits. For writes that cannot change blocked-ness -// (config, metadata). -func (s *Store) withWriteTx(ctx context.Context, fn func(tx *sql.Tx) error) error { - if s.closed.Load() { - return ErrStoreClosed - } - tx, err := s.db.BeginTx(ctx, nil) - if err != nil { - return fmt.Errorf("begin write tx: %w", err) - } - // A panicking callback must not pin the pooled connection; Rollback after - // Commit (or the explicit Rollback below) is a no-op. - defer func() { _ = tx.Rollback() }() - if err := fn(tx); err != nil { - return errors.Join(err, tx.Rollback()) - } - if err := tx.Commit(); err != nil { - return fmt.Errorf("commit write tx: %w", err) - } - return nil -} - -// withMutationTx runs fn then the readiness strategy in ONE transaction, so an -// issue/dependency mutation and its is_blocked reprojection commit atomically. -func (s *Store) withMutationTx(ctx context.Context, fn func(tx *sql.Tx) error) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - if err := fn(tx); err != nil { - return err - } - return s.readiness.AfterWrite(ctx, tx) - }) -} - -// --- representative core methods (delegating to issueops through the dialect) --- - -// SetConfig persists a config key/value. -func (s *Store) SetConfig(ctx context.Context, key, value string) error { - return s.withWriteTx(ctx, func(tx *sql.Tx) error { - if err := issueops.SetConfigInTx(ctx, tx, key, value); err != nil { - return err - } - // Sync the normalized custom-status/type tables, matching the embedded-Dolt - // reference. The sync parses+validates the value (a malformed one errors and - // rolls back the whole write tx) and is what GetCustomStatuses/GetCustomTypes - // read back ORDER BY name. - switch key { - case "status.custom": - if err := issueops.SyncCustomStatusesTable(ctx, tx, value); err != nil { - return fmt.Errorf("syncing custom_statuses table: %w", err) - } - case "types.custom": - if err := issueops.SyncCustomTypesTable(ctx, tx, value); err != nil { - return fmt.Errorf("syncing custom_types table: %w", err) - } - } - return nil - }) -} - -// GetConfig reads a config value ("" if absent). -func (s *Store) GetConfig(ctx context.Context, key string) (string, error) { - var v string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - v, e = issueops.GetConfigInTx(ctx, tx, key) - return e - }) - return v, err -} - -// GetAllConfig returns all config key/values. -func (s *Store) GetAllConfig(ctx context.Context) (map[string]string, error) { - var m map[string]string - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - m, e = issueops.GetAllConfigInTx(ctx, tx) - return e - }) - return m, err -} - -// GetReadyWork returns issues that are ready to work (no open blockers). -func (s *Store) GetReadyWork(ctx context.Context, filter types.WorkFilter) ([]*types.Issue, error) { - var out []*types.Issue - err := s.withReadTx(ctx, func(tx *sql.Tx) error { - var e error - out, e = issueops.GetReadyWorkInTx(ctx, tx, filter) - return e - }) - return out, err -} - -// CloseIssue closes an issue and reprojects blocked-ness in the same tx. -func (s *Store) CloseIssue(ctx context.Context, id, reason, actor, session string) error { - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - _, err := issueops.CloseIssueInTx(ctx, tx, id, reason, actor, session) - return err - }) -} diff --git a/internal/storage/sqlkit/strategy.go b/internal/storage/sqlkit/strategy.go deleted file mode 100644 index 3ac34cd16..000000000 --- a/internal/storage/sqlkit/strategy.go +++ /dev/null @@ -1,68 +0,0 @@ -// Package sqlkit is the single, shared SQL-family implementation of bd's storage -// semantics. Every SQL backend (Dolt, Postgres, SQLite, MySQL, …) is a strategy -// bundle over this one implementation: -// -// - Dialect — the SQL flavor (a translating driver or native emit) -// - ReadinessStrategy — how the is_blocked projection is kept current -// - ClaimStrategy — how a ready issue is atomically claimed -// -// A concrete backend embeds *Store, inherits every method, and overrides only -// the handful it specializes (a "method override") or adds capability-interface -// methods for operations that don't exist in the core contract (e.g. Dolt -// history). The query/graph/ordering/id-mint/cycle semantics live here once, in -// internal/storage/issueops, and are never re-derived per backend. -package sqlkit - -import ( - "context" - "database/sql" - - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// Dialect opens the backend's *sql.DB and names it. The shared layer emits -// canonical (MySQL-dialect) SQL; a Dialect whose driver translates that text to -// the backend's flavor is how a non-MySQL SQL engine joins the family without -// changing the shared layer (see internal/storage/pgdialect for Postgres). -type Dialect interface { - Name() string - Open(ctx context.Context) (*sql.DB, error) -} - -// ReadinessStrategy keeps the denormalized is_blocked column consistent after a -// mutation. It runs inside the same write transaction, so the mutation and its -// reprojection commit atomically. -type ReadinessStrategy interface { - AfterWrite(ctx context.Context, tx issueops.DBTX) error -} - -// ClaimStrategy selects and claims one ready issue. The wedge uses the shared -// read-then-update path (default); a backend may override with, e.g., -// SELECT … FOR UPDATE SKIP LOCKED for lock-free multi-writer claims. Wired in -// the claim slice. -type ClaimStrategy interface { - ClaimReady(ctx context.Context, tx issueops.DBTX, filter types.WorkFilter, actor string) (*types.Issue, error) -} - -// NoopReadiness performs no reprojection. It is the default: every shared -// issueops mutation helper already maintains the is_blocked column targeted and -// in-transaction (exactly like the Dolt reference, which wires no readiness -// strategy at all), so a per-write full-graph recompute is pure redundant cost. -// A backend opts IN to extra reprojection by supplying SyncReadiness explicitly. -type NoopReadiness struct{} - -func (NoopReadiness) AfterWrite(_ context.Context, _ issueops.DBTX) error { - return nil -} - -// SyncReadiness recomputes is_blocked synchronously, in-transaction, on every -// mutation via the full-graph fixpoint. Because the issueops helpers already -// keep is_blocked current, this is only useful as an explicit opt-in repair -// projection; it is no longer the nil-default. -type SyncReadiness struct{} - -func (SyncReadiness) AfterWrite(ctx context.Context, tx issueops.DBTX) error { - _, err := issueops.RecomputeAllIsBlockedInTx(ctx, tx) - return err -} diff --git a/internal/storage/sqlkit/transaction.go b/internal/storage/sqlkit/transaction.go deleted file mode 100644 index 3893f6d2c..000000000 --- a/internal/storage/sqlkit/transaction.go +++ /dev/null @@ -1,294 +0,0 @@ -package sqlkit - -import ( - "context" - "database/sql" - "encoding/json" - "fmt" - "strings" - "time" - - "github.com/steveyegge/beads/internal/storage" - "github.com/steveyegge/beads/internal/storage/issueops" - "github.com/steveyegge/beads/internal/types" -) - -// RunInTransaction executes fn inside one mutation transaction. Wisps live in -// the same database, so a single *sql.Tx serves every table; is_blocked -// reprojection runs once at commit via withMutationTx. commitMsg is Dolt -// commit-message residue and intentionally unused. -func (s *Store) RunInTransaction(ctx context.Context, commitMsg string, fn func(tx storage.Transaction) error) error { - _ = commitMsg - return s.withMutationTx(ctx, func(tx *sql.Tx) error { - // withWriteTx rolls back on a returned error but not on a panic; guard - // it here so a panicking callback still releases the transaction. - defer func() { - if r := recover(); r != nil { - _ = tx.Rollback() - panic(r) - } - }() - return fn(&sqlkitTx{tx: tx}) - }) -} - -// sqlkitTx implements storage.Transaction over a single *sql.Tx. -type sqlkitTx struct{ tx *sql.Tx } - -// CreateIssueImport is the import-friendly creation hook. The shared layer does -// not enforce prefix validation, so this delegates to CreateIssue. -func (t *sqlkitTx) CreateIssueImport(ctx context.Context, issue *types.Issue, actor string, skipPrefixValidation bool) error { - return t.CreateIssue(ctx, issue, actor) -} - -// SearchIssueIDs is the narrow-projection variant of SearchIssues over the tx -// (ids only), mirroring the Dolt transaction implementations. -func (t *sqlkitTx) SearchIssueIDs(ctx context.Context, query string, filter types.IssueFilter) ([]string, error) { - return issueops.SearchIssueIDsInTx(ctx, t.tx, query, filter) -} - -// CreateIssue creates a single issue; TableRouting inside issueops routes -// wisps, so no store-level split is needed. -func (t *sqlkitTx) CreateIssue(ctx context.Context, issue *types.Issue, actor string) error { - if issue == nil { - return fmt.Errorf("issue must not be nil") - } - bc, err := issueops.NewBatchContext(ctx, t.tx, storage.BatchCreateOptions{SkipPrefixValidation: true}) - if err != nil { - return err - } - _, err = issueops.CreateIssueInTxWithResult(ctx, t.tx, bc, issue, actor) - return err -} - -// CreateIssues creates a batch; CreateIssuesInTxWithResult routes mixed batches -// per issue and validates mixed-bucket dependencies internally. -func (t *sqlkitTx) CreateIssues(ctx context.Context, issues []*types.Issue, actor string) error { - if len(issues) == 0 { - return nil - } - _, err := issueops.CreateIssuesInTxWithResult(ctx, t.tx, issues, actor, storage.BatchCreateOptions{ - OrphanHandling: storage.OrphanAllow, - SkipPrefixValidation: true, - }) - return err -} - -// UpdateIssue applies field updates without recording an event (the WithoutEvent -// variant, matching doltTransaction.UpdateIssue). -func (t *sqlkitTx) UpdateIssue(ctx context.Context, id string, updates map[string]interface{}, actor string) error { - if rawMeta, ok := updates["metadata"]; ok { - metadataStr, err := storage.NormalizeMetadataValue(rawMeta) - if err != nil { - return fmt.Errorf("invalid metadata: %w", err) - } - if err := validateMetadataIfConfigured(json.RawMessage(metadataStr)); err != nil { - return err - } - } - _, err := issueops.UpdateIssueWithoutEventInTx(ctx, t.tx, id, updates, actor) - return err -} - -// CloseIssue closes an issue and records the close event, matching both Dolt -// reference transactions (dolt/transaction.go:645, embeddeddolt/transaction.go:79), -// which use the with-event CloseIssueInTx. The without-event variant dropped the -// EventClosed row on bd batch / bd mol squash, diverging from the Dolt oracle. -func (t *sqlkitTx) CloseIssue(ctx context.Context, id string, reason string, actor string, session string) error { - _, err := issueops.CloseIssueInTx(ctx, t.tx, id, reason, actor, session) - return err -} - -// DeleteIssue deletes an issue; issueops routes wisps internally. -func (t *sqlkitTx) DeleteIssue(ctx context.Context, id string) error { - return issueops.DeleteIssueInTx(ctx, t.tx, id) -} - -// GetIssue reads an issue for read-your-writes within the transaction. -func (t *sqlkitTx) GetIssue(ctx context.Context, id string) (*types.Issue, error) { - return issueops.GetIssueInTx(ctx, t.tx, id) -} - -// SearchIssues runs a filtered search within the transaction. -func (t *sqlkitTx) SearchIssues(ctx context.Context, query string, filter types.IssueFilter) ([]*types.Issue, error) { - return issueops.SearchIssuesInTx(ctx, t.tx, query, filter) -} - -// AddDependency adds a dependency with default options. -func (t *sqlkitTx) AddDependency(ctx context.Context, dep *types.Dependency, actor string) error { - return t.AddDependencyWithOptions(ctx, dep, actor, storage.DependencyAddOptions{}) -} - -// AddDependencyWithOptions resolves the source/target tables and edge kind, then -// delegates to issueops. Cross-prefix and external targets are recorded as -// external edges; same-DB wisp targets route to the wisps table. -func (t *sqlkitTx) AddDependencyWithOptions(ctx context.Context, dep *types.Dependency, actor string, opts storage.DependencyAddOptions) error { - writeTable, sourceTable := "dependencies", "issues" - if issueops.IsActiveWispInTx(ctx, t.tx, dep.IssueID) { - writeTable, sourceTable = "wisp_dependencies", "wisps" - } - - isCrossPrefix := types.ExtractPrefix(dep.IssueID) != types.ExtractPrefix(dep.DependsOnID) - targetTable := "issues" - kind := issueops.DepTargetIssue - switch { - case isCrossPrefix, strings.HasPrefix(dep.DependsOnID, "external:"): - kind = issueops.DepTargetExternal - default: - if issueops.IsActiveWispInTx(ctx, t.tx, dep.DependsOnID) { - targetTable = "wisps" - kind = issueops.DepTargetWisp - } - } - - return issueops.AddDependencyInTx(ctx, t.tx, dep, actor, issueops.AddDependencyOpts{ - SourceTable: sourceTable, - TargetTable: targetTable, - WriteTable: writeTable, - IsCrossPrefix: isCrossPrefix, - SkipCycleCheck: opts.SkipCycleCheck, - TargetKind: &kind, - }) -} - -// RemoveDependency removes an edge; actor is unused. issueops handles routing. -func (t *sqlkitTx) RemoveDependency(ctx context.Context, issueID, dependsOnID string, actor string) error { - return issueops.RemoveDependencyInTx(ctx, t.tx, issueID, dependsOnID) -} - -// GetDependencyRecords returns the raw dependency rows for an issue. Targets are -// resolved via DepTargetExpr (the split physical columns), never the generated -// depends_on_id column. -func (t *sqlkitTx) GetDependencyRecords(ctx context.Context, issueID string) ([]*types.Dependency, error) { - table := "dependencies" - if issueops.IsActiveWispInTx(ctx, t.tx, issueID) { - table = "wisp_dependencies" - } - - //nolint:gosec // G201: table is hardcoded - rows, err := t.tx.QueryContext(ctx, fmt.Sprintf(` - SELECT issue_id, %s AS depends_on_id, type, created_at, created_by, metadata, thread_id - FROM %s - WHERE issue_id = ? - `, issueops.DepTargetExpr, table), issueID) - if err != nil { - return nil, fmt.Errorf("get dependency records in tx: %w", err) - } - defer rows.Close() - - var deps []*types.Dependency - for rows.Next() { - var d types.Dependency - var metadata sql.NullString - var threadID sql.NullString - if err := rows.Scan(&d.IssueID, &d.DependsOnID, &d.Type, &d.CreatedAt, &d.CreatedBy, &metadata, &threadID); err != nil { - return nil, fmt.Errorf("get dependency records in tx: %w", err) - } - if metadata.Valid { - d.Metadata = metadata.String - } - if threadID.Valid { - d.ThreadID = threadID.String - } - deps = append(deps, &d) - } - return deps, rows.Err() -} - -// CycleThroughEdges reports a scheduling cycle through one of the new edges. The -// graph merges both dependency tables so uncommitted wisp and permanent edges -// are gated together. -func (t *sqlkitTx) CycleThroughEdges(ctx context.Context, edges [][2]string) (string, error) { - graph := make(map[string][]string) - if err := issueops.AppendSchedulingGraphInTx(ctx, t.tx, []string{"dependencies"}, graph); err != nil { - return "", err - } - if err := issueops.AppendSchedulingGraphInTx(ctx, t.tx, []string{"wisp_dependencies"}, graph); err != nil { - return "", err - } - return issueops.CycleThroughEdgesInGraph(graph, edges), nil -} - -// AddLabel adds a label and records the label-added event, matching both Dolt -// reference transactions (dolt/transaction.go:784, embeddeddolt/transaction.go:148), -// which delegate to issueops.AddLabelInTx. Empty table args let issueops route the -// issue vs wisp label/event tables. The prior bare INSERT dropped the -// EventLabelAdded row on every SQL-backend label mutation. -func (t *sqlkitTx) AddLabel(ctx context.Context, issueID, label, actor string) error { - return issueops.AddLabelInTx(ctx, t.tx, "", "", issueID, label, actor) -} - -// RemoveLabel removes a label and records the label-removed event, matching both -// Dolt reference transactions (dolt/transaction.go:824, embeddeddolt/transaction.go:153), -// which delegate to issueops.RemoveLabelInTx. -func (t *sqlkitTx) RemoveLabel(ctx context.Context, issueID, label, actor string) error { - return issueops.RemoveLabelInTx(ctx, t.tx, "", "", issueID, label, actor) -} - -// GetLabels returns an issue's labels; empty table arg auto-routes wisps. -func (t *sqlkitTx) GetLabels(ctx context.Context, issueID string) ([]string, error) { - return issueops.GetLabelsInTx(ctx, t.tx, "", issueID) -} - -// SetConfig sets a config value within the transaction and syncs the normalized -// custom_statuses/custom_types tables for the relevant keys, matching the -// embedded-Dolt reference (embeddeddolt/transaction.go) and Store.SetConfig. -// Without this, tx-path writes of status.custom/types.custom leave those tables -// stale, so GetCustomStatuses/GetCustomTypes (which read them) diverge. -func (t *sqlkitTx) SetConfig(ctx context.Context, key, value string) error { - if err := issueops.SetConfigInTx(ctx, t.tx, key, value); err != nil { - return err - } - switch key { - case "status.custom": - if err := issueops.SyncCustomStatusesTable(ctx, t.tx, value); err != nil { - return fmt.Errorf("syncing custom_statuses table: %w", err) - } - case "types.custom": - if err := issueops.SyncCustomTypesTable(ctx, t.tx, value); err != nil { - return fmt.Errorf("syncing custom_types table: %w", err) - } - } - return nil -} - -// GetConfig gets a config value within the transaction ("" when absent). -func (t *sqlkitTx) GetConfig(ctx context.Context, key string) (string, error) { - return issueops.GetConfigInTx(ctx, t.tx, key) -} - -// SetMetadata sets a metadata value within the transaction. -func (t *sqlkitTx) SetMetadata(ctx context.Context, key, value string) error { - return issueops.SetMetadataInTx(ctx, t.tx, key, value) -} - -// GetMetadata gets a metadata value within the transaction ("" when absent). -func (t *sqlkitTx) GetMetadata(ctx context.Context, key string) (string, error) { - return issueops.GetMetadataInTx(ctx, t.tx, key) -} - -// SetLocalMetadata writes a clone-local value; same DB, no ignored-tx split. -func (t *sqlkitTx) SetLocalMetadata(ctx context.Context, key, value string) error { - return issueops.SetLocalMetadataInTx(ctx, t.tx, key, value) -} - -// GetLocalMetadata reads a clone-local value ("" when absent). -func (t *sqlkitTx) GetLocalMetadata(ctx context.Context, key string) (string, error) { - return issueops.GetLocalMetadataInTx(ctx, t.tx, key) -} - -// AddComment records a comment-as-event within the transaction. -func (t *sqlkitTx) AddComment(ctx context.Context, issueID, actor, comment string) error { - return issueops.AddCommentEventInTx(ctx, t.tx, issueID, actor, comment) -} - -// ImportIssueComment adds a structured comment preserving createdAt. issueops -// verifies the issue exists before inserting. -func (t *sqlkitTx) ImportIssueComment(ctx context.Context, issueID, author, text string, createdAt time.Time) (*types.Comment, error) { - return issueops.ImportIssueCommentInTx(ctx, t.tx, issueID, author, text, createdAt) -} - -// GetIssueComments returns an issue's comments within the transaction. -func (t *sqlkitTx) GetIssueComments(ctx context.Context, issueID string) ([]*types.Comment, error) { - return issueops.GetIssueCommentsInTx(ctx, t.tx, issueID) -} diff --git a/internal/storage/unsupportedgen/gen_test.go b/internal/storage/unsupportedgen/gen_test.go deleted file mode 100644 index 09b6cde74..000000000 --- a/internal/storage/unsupportedgen/gen_test.go +++ /dev/null @@ -1,116 +0,0 @@ -package main - -// Regen-idempotence gate for the typed-unsupported shells. -// -// Every backend's unsupported_gen.go carries two compile-time assertions -// (var _ storage.DoltStorage = unsupportedDoltStorage{}, likewise for -// Transaction) plus a real-store assertion (var _ storage.DoltStorage = -// (*Store)(nil)) in each backend package. Together those catch interface GROWTH, -// a hand-DELETED stub, and a skip-list entry the real store does not actually -// implement — all at compile time. What nothing else catches is a hand-edited -// stub BODY: a typo'd Op string, or a stub changed to return nil instead of the -// typed error. That is the drift class this test pins — for each backend it -// regenerates from the exact flags in the backend's //go:generate directive and -// byte-compares against the committed file. -// -// It is an ordinary (ungated) unit test so plain `go test ./...` runs it; it -// needs no DB, no env, and no cgo — runConfig is pure stdlib go/ast codegen. - -import ( - "os" - "path/filepath" - "strings" - "testing" -) - -// shellBackends are the backends whose typed-unsupported shell this tool -// generates. Each dir is relative to this package (internal/storage/unsupportedgen). -var shellBackends = []string{"postgres", "mysql", "sqlite"} - -func TestGeneratedShellsAreUpToDate(t *testing.T) { - // storage package source, relative to this package dir (one level up). - const srcDir = ".." - - for _, backend := range shellBackends { - t.Run(backend, func(t *testing.T) { - dir := filepath.Join("..", backend) - cfg := parseBackendDirective(t, filepath.Join(dir, "unsupported.go")) - cfg.src = srcDir - - committedPath := filepath.Join(dir, cfg.out) - want, err := os.ReadFile(committedPath) - if err != nil { - t.Fatalf("read committed %s: %v", committedPath, err) - } - - // Regenerate into a temp file so a stale/edited committed copy is - // never clobbered by the check itself. - tmp := filepath.Join(t.TempDir(), cfg.out) - cfg.out = tmp - if err := runConfig(cfg); err != nil { - t.Fatalf("runConfig(%s): %v", backend, err) - } - got, err := os.ReadFile(tmp) - if err != nil { - t.Fatalf("read regenerated %s: %v", backend, err) - } - - if string(got) != string(want) { - t.Fatalf("%s is stale or hand-edited: it does not match a fresh `go generate ./...`.\n"+ - "Regenerate it (do not hand-edit the DO-NOT-EDIT file) and commit the result.\n"+ - "committed length=%d, regenerated length=%d", committedPath, len(want), len(got)) - } - }) - } -} - -// parseBackendDirective extracts the generator flags from the single -// `//go:generate go run ../unsupportedgen ...` line in a backend's -// unsupported.go, so the test regenerates with exactly the committed flags -// (and auto-follows any change to the skip list). -func parseBackendDirective(t *testing.T, path string) genConfig { - t.Helper() - data, err := os.ReadFile(path) - if err != nil { - t.Fatalf("read %s: %v", path, err) - } - var directive string - for _, line := range strings.Split(string(data), "\n") { - if strings.Contains(line, "go:generate") && strings.Contains(line, "unsupportedgen") { - directive = line - break - } - } - if directive == "" { - t.Fatalf("%s: no `//go:generate go run ../unsupportedgen` directive found", path) - } - - fields := strings.Fields(directive) - cfg := defaultConfig() - for i := 0; i < len(fields); i++ { - switch fields[i] { - case "-pkg": - cfg.pkg = directiveValue(t, path, fields, &i) - case "-out": - cfg.out = directiveValue(t, path, fields, &i) - case "-type": - cfg.types = splitList(directiveValue(t, path, fields, &i)) - case "-skip": - entries := splitList(directiveValue(t, path, fields, &i)) - cfg.skip = make(map[string]bool, len(entries)) - for _, e := range entries { - cfg.skip[e] = true - } - } - } - return cfg -} - -func directiveValue(t *testing.T, path string, fields []string, i *int) string { - t.Helper() - if *i+1 >= len(fields) { - t.Fatalf("%s: flag %q missing its value", path, fields[*i]) - } - *i++ - return fields[*i] -} diff --git a/internal/storage/unsupportedgen/main.go b/internal/storage/unsupportedgen/main.go deleted file mode 100644 index 4aed4efd9..000000000 --- a/internal/storage/unsupportedgen/main.go +++ /dev/null @@ -1,634 +0,0 @@ -// Command unsupportedgen produces a backend's typed-unsupported shell: for each target -// interface (storage.DoltStorage, storage.Transaction) it emits a concrete -// struct whose every method returns *storage.ErrUnsupported. A backend embeds -// the generated shell alongside its real store (e.g. *sqlkit.Store) so any -// method the backend has not really overridden fails loudly and typed, never -// with a nil-pointer panic. -// -// It is stdlib-only by design (go/parser + go/ast + go/printer + go/format): -// golang.org/x/tools is only an indirect dep and go.mod carries a pre-existing -// cosmetic edit that must not churn. This works because every interface -// DoltStorage/Transaction embed is defined in package internal/storage itself, -// so the AST flatten resolves all embeds locally. -// -// Invoked via `//go:generate go run ../unsupportedgen -pkg -src .. ...` -// from a backend package dir (e.g. internal/storage/postgres), whose CWD makes -// the storage package ".." — hence -src "..". -package main - -import ( - "bytes" - "flag" - "fmt" - "go/ast" - "go/format" - "go/parser" - "go/printer" - "go/token" - "log" - "os" - "path/filepath" - "sort" - "strings" -) - -type target struct { - iface string // interface name in package storage - typeName string // generated concrete struct name - opPrefix string // prefix for the Op string, e.g. "Transaction." -} - -var targets = []target{ - {iface: "DoltStorage", typeName: "unsupportedDoltStorage", opPrefix: ""}, - {iface: "Transaction", typeName: "unsupportedTransaction", opPrefix: "Transaction."}, -} - -const ( - // defaultSrcDir is the storage package dir relative to the go:generate CWD - // (the backend package dir); defaultOutFile is where the shell is written. - defaultSrcDir = ".." - defaultOutFile = "unsupported_gen.go" - storagePath = "github.com/steveyegge/beads/internal/storage" -) - -func main() { - log.SetFlags(0) - cfg, err := parseFlags(os.Args[1:]) - if err != nil { - log.Fatalf("gen: %v", err) - } - if err := runConfig(cfg); err != nil { - log.Fatalf("gen: %v", err) - } -} - -// genConfig is the parameterized generation request. Its zero-flag defaults -// (see defaultConfig) reproduce a backend's committed shell byte-for-byte; the -// flags exist so the same generator can emit a partial shell for another -// package (e.g. postgres) that embeds a real store alongside the generated one. -type genConfig struct { - pkg string // -pkg : package clause of the generated file - src string // -src : dir of the storage package to parse - out string // -out : output file path - types []string // -type : which target interfaces to emit (table order, not flag order) - skip map[string]bool // -skip : Op strings (opPrefix+Method) to omit -} - -func defaultConfig() genConfig { - return genConfig{ - pkg: "unsupported", - src: defaultSrcDir, - out: defaultOutFile, - types: nil, // nil => all targets, in var targets order - skip: nil, // nil => skip nothing - } -} - -// parseFlags builds a genConfig from CLI args. Every flag defaults to the -// byte-identity-preserving value, so `go run ./gen` with no flags is exactly -// the historical invocation. -func parseFlags(args []string) (genConfig, error) { - def := defaultConfig() - fs := flag.NewFlagSet("gen", flag.ContinueOnError) - pkg := fs.String("pkg", def.pkg, "package clause of the generated file") - src := fs.String("src", def.src, "directory of the storage package to parse") - out := fs.String("out", def.out, "output file path") - typeList := fs.String("type", "", "comma-separated target interface names to emit (empty = all)") - skipList := fs.String("skip", "", "comma-separated Op strings (opPrefix+Method) to omit") - if err := fs.Parse(args); err != nil { - return genConfig{}, err - } - cfg := def - cfg.pkg = *pkg - cfg.src = *src - cfg.out = *out - cfg.types = splitList(*typeList) - if entries := splitList(*skipList); len(entries) > 0 { - cfg.skip = make(map[string]bool, len(entries)) - for _, e := range entries { - cfg.skip[e] = true - } - } - return cfg, nil -} - -// splitList splits a comma-separated flag value, trimming blanks. An empty or -// all-whitespace value yields a nil slice (the "unset" sentinel). -func splitList(s string) []string { - var out []string - for _, part := range strings.Split(s, ",") { - if part = strings.TrimSpace(part); part != "" { - out = append(out, part) - } - } - return out -} - -type pkgInfo struct { - fset *token.FileSet - interfaces map[string]*ast.InterfaceType // package-level interface types by name - typeNames map[string]bool // all package-level type names - imports map[string]string // local name -> import path -} - -// runConfig is the parameterized generator. At defaultConfig() values it emits -// a backend's committed shell byte-for-byte; -pkg/-type/-skip let it emit a -// partial shell for another package (e.g. postgres) that embeds a real store -// alongside the generated one. -func runConfig(cfg genConfig) error { - info, err := parsePackage(cfg.src) - if err != nil { - return err - } - - selected, err := selectTargets(cfg.types) - if err != nil { - return err - } - - var body bytes.Buffer - // Track selector qualifiers actually used across all emitted signatures so - // we can emit exactly the imports needed. - usedQualifiers := map[string]bool{} - // Track which -skip entries actually matched an emitted method, for strict - // post-emission validation. - skipMatched := map[string]bool{} - - for _, tg := range selected { - iface, ok := info.interfaces[tg.iface] - if !ok { - return fmt.Errorf("interface %q not found in package storage", tg.iface) - } - methods, err := flatten(info, iface, tg.iface) - if err != nil { - return err - } - if err := emitTarget(&body, info, tg, methods, usedQualifiers, cfg.skip, skipMatched); err != nil { - return err - } - } - - // Strict skip validation: a -skip entry that matched no emitted method is a - // typo or a drift tripwire (method removed from the interface). Fail loudly. - if unmatched := unmatchedSkips(cfg.skip, skipMatched); len(unmatched) > 0 { - return fmt.Errorf("skip entries matched no emitted method: %s", strings.Join(unmatched, ", ")) - } - - var out bytes.Buffer - fmt.Fprintf(&out, "// Code generated by gen (%s typed-unsupported shell); DO NOT EDIT.\n\n", cfg.pkg) //nolint:gosec // generator emits trusted package names into generated source - fmt.Fprintf(&out, "package %s\n\n", cfg.pkg) //nolint:gosec // generator emits trusted package names into generated source - writeImports(&out, info, usedQualifiers) - out.Write(body.Bytes()) - - formatted, err := format.Source(out.Bytes()) - if err != nil { - return fmt.Errorf("gofmt generated source: %w\n----\n%s", err, out.String()) - } - // #nosec G306 -- generated Go source must be world-readable like the rest of the tree - if err := os.WriteFile(cfg.out, formatted, 0o644); err != nil { - return fmt.Errorf("write %s: %w", cfg.out, err) - } - return nil -} - -// selectTargets returns the targets to emit. An empty names slice selects all -// targets; otherwise each name is validated against the targets table and the -// result is filtered in table order (not flag order) so output is deterministic -// regardless of -type ordering. An unknown name is a fatal error. -func selectTargets(names []string) ([]target, error) { - if len(names) == 0 { - return targets, nil - } - known := map[string]bool{} - for _, tg := range targets { - known[tg.iface] = true - } - want := map[string]bool{} - for _, n := range names { - if !known[n] { - return nil, fmt.Errorf("unknown -type %q (known: %s)", n, knownTargetNames()) - } - want[n] = true - } - var selected []target - for _, tg := range targets { - if want[tg.iface] { - selected = append(selected, tg) - } - } - return selected, nil -} - -func knownTargetNames() string { - names := make([]string, 0, len(targets)) - for _, tg := range targets { - names = append(names, tg.iface) - } - return strings.Join(names, ", ") -} - -// unmatchedSkips returns the sorted -skip entries that never matched an emitted -// method (a nil skip set yields a nil result). -func unmatchedSkips(skip, matched map[string]bool) []string { - var unmatched []string - for k := range skip { - if !matched[k] { - unmatched = append(unmatched, k) - } - } - sort.Strings(unmatched) - return unmatched -} - -func parsePackage(dir string) (*pkgInfo, error) { - fset := token.NewFileSet() - pkgs, err := parser.ParseDir(fset, dir, func(fi os.FileInfo) bool { - return !strings.HasSuffix(fi.Name(), "_test.go") - }, 0) - if err != nil { - return nil, fmt.Errorf("parse dir %s: %w", dir, err) - } - pkg, ok := pkgs["storage"] - if !ok { - return nil, fmt.Errorf("package storage not found in %s", dir) - } - - info := &pkgInfo{ - fset: fset, - interfaces: map[string]*ast.InterfaceType{}, - typeNames: map[string]bool{}, - imports: map[string]string{}, - } - - // Deterministic file order. - names := make([]string, 0, len(pkg.Files)) - for name := range pkg.Files { - names = append(names, name) - } - sort.Strings(names) - - for _, name := range names { - file := pkg.Files[name] - for _, imp := range file.Imports { - path := strings.Trim(imp.Path.Value, `"`) - local := "" - if imp.Name != nil { - local = imp.Name.Name - } else { - local = filepath.Base(path) - } - if local == "_" || local == "." { - continue - } - info.imports[local] = path - } - for _, decl := range file.Decls { - gd, ok := decl.(*ast.GenDecl) - if !ok || gd.Tok != token.TYPE { - continue - } - for _, spec := range gd.Specs { - ts, ok := spec.(*ast.TypeSpec) - if !ok { - continue - } - info.typeNames[ts.Name.Name] = true - if it, ok := ts.Type.(*ast.InterfaceType); ok { - info.interfaces[ts.Name.Name] = it - } - } - } - } - return info, nil -} - -type method struct { - name string - typ *ast.FuncType - comment string // optional NOTE comment for no-error methods -} - -// flatten walks an interface, recursing into embedded local interfaces, and -// returns the deduped method set in declaration order (first-wins, which is -// correct because Go requires identical signatures for duplicate embedded -// method names). -func flatten(info *pkgInfo, iface *ast.InterfaceType, ifaceName string) ([]method, error) { - var out []method - seen := map[string]bool{} - var walk func(it *ast.InterfaceType, owner string) error - walk = func(it *ast.InterfaceType, owner string) error { - if it.Methods == nil { - return nil - } - for _, field := range it.Methods.List { - if ft, ok := field.Type.(*ast.FuncType); ok { - // Named method. - if len(field.Names) != 1 { - return fmt.Errorf("%s: expected exactly one name per method field, got %d", owner, len(field.Names)) - } - name := field.Names[0].Name - if seen[name] { - continue - } - seen[name] = true - out = append(out, method{name: name, typ: ft}) - continue - } - // Embedded interface: must be a local *ast.Ident naming another - // package-level interface in package storage. - id, ok := field.Type.(*ast.Ident) - if !ok { - return fmt.Errorf("%s: embedded field is not a local identifier (kind %T); the stdlib generator only handles same-package embeds", owner, field.Type) - } - embedded, ok := info.interfaces[id.Name] - if !ok { - return fmt.Errorf("%s: embedded interface %q not found in package storage", owner, id.Name) - } - if err := walk(embedded, id.Name); err != nil { - return err - } - } - return nil - } - if err := walk(iface, ifaceName); err != nil { - return nil, err - } - return out, nil -} - -func emitTarget(buf *bytes.Buffer, info *pkgInfo, tg target, methods []method, usedQualifiers, skip, skipMatched map[string]bool) error { - fmt.Fprintf(buf, "// %s is the generated typed-unsupported shell for storage.%s.\n", tg.typeName, tg.iface) //nolint:gosec // generator emits trusted type/interface names into generated source - fmt.Fprintf(buf, "// Every method returns *storage.ErrUnsupported; embed it and override the\n") - fmt.Fprintf(buf, "// real slice. DO NOT hand-edit — regenerate with `go generate ./...`.\n") - fmt.Fprintf(buf, "type %s struct{}\n\n", tg.typeName) //nolint:gosec // generator emits trusted type names into generated source - - skipped := 0 - for _, m := range methods { - op := tg.opPrefix + m.name - // A skipped method is simply not emitted (the embedding concrete store - // implements it itself); no placeholder. Skipping happens before rewrite - // so its qualifiers never enter the import set. - if skip[op] { - skipMatched[op] = true - skipped++ - continue - } - rewritten, err := rewriteFuncType(info, m.typ, usedQualifiers) - if err != nil { - return fmt.Errorf("%s.%s: %w", tg.iface, m.name, err) - } - hasErr := lastResultIsError(rewritten) - params := renderFieldList(info, rewritten.Params, true /*blankNames*/, false /*named*/) - var results string - if rewritten.Results == nil || len(rewritten.Results.List) == 0 { - results = "" - } else { - results = renderFieldList(info, rewritten.Results, false, true /*named results*/) - } - - fmt.Fprintf(buf, "func (%s) %s(%s)", tg.typeName, m.name, params) //nolint:gosec // generator emits trusted type/method names into generated source - if results != "" { - // Named results are always parenthesized (even a single one), which - // is required because we give it a name (_ or err). - fmt.Fprintf(buf, " (%s)", results) //nolint:gosec // generator emits trusted result names into generated source - } - buf.WriteString(" {\n") - if hasErr { - fmt.Fprintf(buf, "\terr = errUnsupported(%q)\n", op) //nolint:gosec // generator emits trusted operation names into generated source - buf.WriteString("\treturn\n") - } else { - buf.WriteString("\t// NOTE: no error channel on this signature; returns the zero value.\n") - buf.WriteString("\treturn\n") - } - buf.WriteString("}\n\n") - } - - if skipped == 0 { - // Full shell: the compile-time completeness assertion, exactly as before. - fmt.Fprintf(buf, "var _ storage.%s = %s{}\n\n", tg.iface, tg.typeName) //nolint:gosec // generator emits trusted interface/type names into generated source - } else { - // Partial shell: it cannot satisfy the interface alone, so the assertion - // moves to the embedding composite's `var _ storage. = (*Store)(nil)`, - // which proves union coverage (real methods + these stubs = full interface). - fmt.Fprintf(buf, "// NOTE: partial shell (%d methods skipped); the embedding composite must assert storage.%s itself.\n\n", skipped, tg.iface) //nolint:gosec // generator emits trusted interface names into generated source - } - return nil -} - -func lastResultIsError(ft *ast.FuncType) bool { - if ft.Results == nil || len(ft.Results.List) == 0 { - return false - } - last := ft.Results.List[len(ft.Results.List)-1] - id, ok := last.Type.(*ast.Ident) - return ok && id.Name == "error" -} - -// renderFieldList renders params or results. For params (blankNames) every -// param name is "_". For named results, each result gets a blanked-or-named -// identifier: the trailing error result is named "err" (so the body can assign -// it); all others are "_". -func renderFieldList(info *pkgInfo, fl *ast.FieldList, blankNames, named bool) string { - if fl == nil { - return "" - } - var parts []string - // Flatten grouped fields into one entry per type occurrence. - type entry struct { - typ ast.Expr - } - var entries []entry - for _, f := range fl.List { - count := len(f.Names) - if count == 0 { - count = 1 - } - for i := 0; i < count; i++ { - entries = append(entries, entry{typ: f.Type}) - } - } - - if blankNames { - for _, e := range entries { - parts = append(parts, "_ "+exprString(info, e.typ)) - } - return strings.Join(parts, ", ") - } - - // Named results. - n := len(entries) - for i, e := range entries { - name := "_" - if named && i == n-1 { - if id, ok := e.typ.(*ast.Ident); ok && id.Name == "error" { - name = "err" - } - } - parts = append(parts, name+" "+exprString(info, e.typ)) - } - return strings.Join(parts, ", ") -} - -// rewriteFuncType returns a copy of ft with every local package-level type name -// (in type position) qualified as storage.. Selector expressions -// (types.Issue) are left untouched. -func rewriteFuncType(info *pkgInfo, ft *ast.FuncType, usedQualifiers map[string]bool) (*ast.FuncType, error) { - out := &ast.FuncType{} - var err error - out.Params, err = rewriteFieldList(info, ft.Params, usedQualifiers) - if err != nil { - return nil, err - } - out.Results, err = rewriteFieldList(info, ft.Results, usedQualifiers) - if err != nil { - return nil, err - } - return out, nil -} - -func rewriteFieldList(info *pkgInfo, fl *ast.FieldList, usedQualifiers map[string]bool) (*ast.FieldList, error) { - if fl == nil { - return nil, nil - } - out := &ast.FieldList{} - for _, f := range fl.List { - nt, err := rewriteType(info, f.Type, usedQualifiers) - if err != nil { - return nil, err - } - out.List = append(out.List, &ast.Field{Names: f.Names, Type: nt}) - } - return out, nil -} - -// rewriteType deep-rewrites a type expression, qualifying local type idents and -// recording selector qualifiers actually used. -func rewriteType(info *pkgInfo, e ast.Expr, usedQualifiers map[string]bool) (ast.Expr, error) { - switch t := e.(type) { - case *ast.Ident: - if info.typeNames[t.Name] { - usedQualifiers["storage"] = true - return &ast.SelectorExpr{X: ast.NewIdent("storage"), Sel: ast.NewIdent(t.Name)}, nil - } - return t, nil // builtin (error, bool, int64, string, ...) or predeclared - case *ast.SelectorExpr: - // e.g. types.Issue — do NOT descend into X; record the qualifier. - if id, ok := t.X.(*ast.Ident); ok { - usedQualifiers[id.Name] = true - } - return t, nil - case *ast.StarExpr: - x, err := rewriteType(info, t.X, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.StarExpr{X: x}, nil - case *ast.ArrayType: - elt, err := rewriteType(info, t.Elt, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.ArrayType{Len: t.Len, Elt: elt}, nil - case *ast.MapType: - k, err := rewriteType(info, t.Key, usedQualifiers) - if err != nil { - return nil, err - } - v, err := rewriteType(info, t.Value, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.MapType{Key: k, Value: v}, nil - case *ast.Ellipsis: - elt, err := rewriteType(info, t.Elt, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.Ellipsis{Elt: elt}, nil - case *ast.FuncType: - return rewriteFuncType(info, t, usedQualifiers) - case *ast.ChanType: - val, err := rewriteType(info, t.Value, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.ChanType{Dir: t.Dir, Value: val}, nil - case *ast.ParenExpr: - x, err := rewriteType(info, t.X, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.ParenExpr{X: x}, nil - case *ast.IndexExpr: - // Generic instantiation with one type arg, e.g. Iter[types.Issue]. - x, err := rewriteType(info, t.X, usedQualifiers) - if err != nil { - return nil, err - } - idx, err := rewriteType(info, t.Index, usedQualifiers) - if err != nil { - return nil, err - } - return &ast.IndexExpr{X: x, Index: idx}, nil - case *ast.IndexListExpr: - x, err := rewriteType(info, t.X, usedQualifiers) - if err != nil { - return nil, err - } - var indices []ast.Expr - for _, i := range t.Indices { - ni, err := rewriteType(info, i, usedQualifiers) - if err != nil { - return nil, err - } - indices = append(indices, ni) - } - return &ast.IndexListExpr{X: x, Indices: indices}, nil - case *ast.InterfaceType: - // Anonymous interface (e.g. interface{}); leave as-is. - return t, nil - default: - return nil, fmt.Errorf("unhandled type node %T in signature", e) - } -} - -func exprString(info *pkgInfo, e ast.Expr) string { - var buf bytes.Buffer - cfg := printer.Config{Mode: printer.RawFormat} - if err := cfg.Fprint(&buf, info.fset, e); err != nil { - return fmt.Sprintf("/*print error: %v*/", err) - } - return buf.String() -} - -func writeImports(out *bytes.Buffer, info *pkgInfo, usedQualifiers map[string]bool) { - // Resolve qualifiers to paths: storage is always the seam type's home; - // others come from the parsed package's import set. - paths := map[string]string{} - for q := range usedQualifiers { - if q == "storage" { - paths[storagePath] = storagePath - continue - } - p, ok := info.imports[q] - if !ok { - // Should never happen: every qualifier came from a selector whose - // package is imported by the storage package files we parsed. - log.Fatalf("gen: unknown import qualifier %q used in a signature", q) - } - paths[p] = p - } - if len(paths) == 0 { - return - } - list := make([]string, 0, len(paths)) - for p := range paths { - list = append(list, p) - } - sort.Strings(list) - out.WriteString("import (\n") - for _, p := range list { - fmt.Fprintf(out, "\t%q\n", p) //nolint:gosec // generator emits trusted import paths into generated source - } - out.WriteString(")\n\n") -} diff --git a/internal/utils/id_parser.go b/internal/utils/id_parser.go index 75aa0c613..c3d8d8d15 100644 --- a/internal/utils/id_parser.go +++ b/internal/utils/id_parser.go @@ -199,11 +199,9 @@ func ResolvePartialID(ctx context.Context, store storage.Storage, input string) return "", fmt.Errorf("no issue found matching %q", input) } - // Sort so the ambiguity error lists IDs deterministically. matches is built - // in SearchIssues return order, whose primary sort is created_at DESC; that - // order is not stable across backends (Postgres timestamp(0) vs Dolt), so an - // unsorted list makes the same ambiguous input print in different orders on - // different storage. Sorting by ID pins the message regardless of backend. + // Sort so the ambiguity error lists IDs deterministically. SearchIssues return + // order is not a contract for ambiguous matches, so sorting by ID pins the same + // message for every storage implementation. sort.Strings(matches) if len(matches) > 1 { diff --git a/open_backend_selection_test.go b/open_backend_selection_test.go new file mode 100644 index 000000000..611e2d775 --- /dev/null +++ b/open_backend_selection_test.go @@ -0,0 +1,122 @@ +package beads_test + +import ( + "context" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/steveyegge/beads" +) + +func writeBackendMetadata(t *testing.T, backend string) string { + t.Helper() + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatalf("create .beads: %v", err) + } + metadata := `{"backend":"` + backend + `"}` + if backend == "sqlite" { + // Workspaces created by the removed SQLite backend carry an explicit + // path marker; a bare backend:"sqlite" can also be stale metadata from + // the earlier SQLite era (see PR #4740). Both must hit the tombstone. + metadata = `{"backend":"sqlite","sqlite_path":"beads.db"}` + } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte(metadata), 0o600); err != nil { + t.Fatalf("write metadata: %v", err) + } + return beadsDir +} + +func TestOpenBestAvailableRejectsSQLite(t *testing.T) { + beadsDir := writeBackendMetadata(t, "sqlite") + store, err := beads.OpenBestAvailable(context.Background(), beadsDir) + if store != nil { + _ = store.Close() + t.Fatal("removed SQLite backend returned a store") + } + if err == nil || !strings.Contains(err.Error(), "no longer supported") { + t.Fatalf("SQLite backend error = %v, want rollback explanation", err) + } + if !strings.Contains(err.Error(), "single engine") || !strings.Contains(err.Error(), "export") { + t.Fatalf("SQLite backend error lacks rationale or migration guidance: %v", err) + } + // The fail-closed guarantee includes never provisioning the SQLite file the + // removed backend would have created. + for _, name := range []string{"embeddeddolt", "dolt", "beads.db"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("removed SQLite backend created %s (stat error: %v)", name, statErr) + } + } +} + +func TestOpenBestAvailableRejectsRemovedBackends(t *testing.T) { + for _, backend := range []string{"postgres", "mysql", "sqlite"} { + t.Run(backend, func(t *testing.T) { + beadsDir := writeBackendMetadata(t, backend) + store, err := beads.OpenBestAvailable(context.Background(), beadsDir) + if store != nil { + _ = store.Close() + t.Fatalf("removed backend %q returned a store", backend) + } + if err == nil || !strings.Contains(err.Error(), "no longer supported") { + t.Fatalf("removed backend error = %v, want rollback explanation", err) + } + rationale := "resource-light" + if backend == "sqlite" { + rationale = "single engine" + } + if !strings.Contains(err.Error(), rationale) || !strings.Contains(err.Error(), "export") { + t.Fatalf("removed backend error lacks rationale or migration guidance: %v", err) + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("removed backend created %s (stat error: %v)", name, statErr) + } + } + }) + } +} + +func TestOpenBestAvailableRejectsUnknownBackend(t *testing.T) { + beadsDir := writeBackendMetadata(t, "mystery") + store, err := beads.OpenBestAvailable(context.Background(), beadsDir) + if store != nil { + _ = store.Close() + t.Fatal("unknown backend returned a store") + } + if err == nil || !strings.Contains(err.Error(), "not recognized") { + t.Fatalf("unknown backend error = %v, want fail-closed metadata guidance", err) + } + if !strings.Contains(err.Error(), "no storage database was opened or modified") { + t.Fatalf("unknown backend error lacks data-safety guarantee: %v", err) + } + for _, name := range []string{"embeddeddolt", "dolt", "beads.db"} { + if _, statErr := os.Stat(filepath.Join(beadsDir, name)); !os.IsNotExist(statErr) { + t.Fatalf("unknown backend created %s (stat error: %v)", name, statErr) + } + } +} + +func TestOpenBestAvailableRejectsCorruptMetadata(t *testing.T) { + beadsDir := filepath.Join(t.TempDir(), ".beads") + if err := os.MkdirAll(beadsDir, 0o750); err != nil { + t.Fatalf("create .beads: %v", err) + } + if err := os.WriteFile(filepath.Join(beadsDir, "metadata.json"), []byte("{"), 0o600); err != nil { + t.Fatalf("write metadata: %v", err) + } + + store, err := beads.OpenBestAvailable(context.Background(), beadsDir) + if store != nil { + _ = store.Close() + t.Fatal("corrupt metadata unexpectedly returned a store") + } + if err == nil || !strings.Contains(err.Error(), "metadata") { + t.Fatalf("corrupt metadata error = %v, want metadata load failure", err) + } + if _, statErr := os.Stat(filepath.Join(beadsDir, "embeddeddolt")); !os.IsNotExist(statErr) { + t.Fatalf("corrupt metadata created embedded Dolt storage (stat error: %v)", statErr) + } +} diff --git a/scripts/conformance.sh b/scripts/conformance.sh index 5937e6450..6114e0eed 100755 --- a/scripts/conformance.sh +++ b/scripts/conformance.sh @@ -4,17 +4,8 @@ # # ./scripts/conformance.sh # -# Two tiers, both reading the backend registry (test/conformance/profiles.go for the -# E2E tier; the per-backend conformance_test.go files for the in-process tier). Add a -# backend = add a profile + a factory; both tiers pick it up. -# -# Backends that need an external service auto-skip when their env is unset: -# BEADS_PG_TEST_URL postgres://user:pass@host:port/db (enables the postgres backend) -# BEADS_PG_PASSWORD optional, if the password is not in the URL -# -# Optional deep gate (bts-rs 523-scenario differential oracle; needs the bts-rs -# checkout + ~50 min, so it is off by default and not part of the per-PR loop): -# CONFORMANCE_DEEP=1 BTS_RS_DIR=/path/to/bts-rs ./scripts/conformance.sh +# Two tiers exercise the storage conformance contract: the in-process storage +# corpus against the embedded-Dolt oracle, then the real-binary CLI corpus. # set -euo pipefail cd "$(dirname "$0")/.." @@ -38,40 +29,9 @@ assert_conformance_passed() { rm -f "$log" } -# require_backend NAME -> success if NAME is listed (comma-separated) in -# BEADS_CONFORMANCE_REQUIRE. CI sets BEADS_CONFORMANCE_REQUIRE=postgres,mysql so a -# backend that self-skips because its BEADS_*_TEST_URL is missing becomes a hard -# failure instead of a silent green; unset locally, the backend self-skips as before. -require_backend() { - local want="$1" tok - local IFS=, - for tok in ${BEADS_CONFORMANCE_REQUIRE:-}; do - [ "$(printf '%s' "$tok" | tr -d '[:space:]')" = "$want" ] && return 0 - done - return 1 -} - -# run_sql_conformance NAME PKG RUN URLVAR -# Run one SQL backend's in-process conformance + wedge gates. When NAME is required -# (see require_backend), run verbose and assert the TestConformance parity oracle -# actually ran and passed — mirroring the embedded-Dolt reference guard so a missing -# BEADS_*_TEST_URL can't silently narrow coverage. Otherwise run plain and let the -# suite self-skip. URLVAR names the env var to set, surfaced in the failure hint. -run_sql_conformance() { - local name="$1" pkg="$2" run="$3" urlvar="$4" - if require_backend "$name"; then - local log - log="$(mktemp)" - CGO_ENABLED=1 go test -tags "$TAGS" -v "$pkg" -run "$run" | tee "$log" - assert_conformance_passed "$log" "$name backend (set $urlvar)" - else - CGO_ENABLED=1 go test -tags "$TAGS" "$pkg" -run "$run" - fi -} - echo "==> Tier 1: in-process store conformance + wedge gates" # The embedded-Dolt backend runs the full backend-agnostic suite (conformance.RunAll) as -# the reference oracle every SQL backend is compared against. BEADS_TEST_EMBEDDED_DOLT=1 +# the reference oracle any future backend is compared against. BEADS_TEST_EMBEDDED_DOLT=1 # is REQUIRED, not optional: without it that suite self-skips # (internal/storage/embeddeddolt/conformance_test.go), which would let this whole # storage-parity gate report success while never running the oracle. Run it with -v and @@ -82,37 +42,7 @@ embedded_dolt_log="$(mktemp)" BEADS_TEST_EMBEDDED_DOLT=1 CGO_ENABLED=1 go test -tags "$TAGS" -v \ ./internal/storage/embeddeddolt/ -run TestConformance | tee "$embedded_dolt_log" assert_conformance_passed "$embedded_dolt_log" "embedded-Dolt reference (need BEADS_TEST_EMBEDDED_DOLT=1)" -# Each SQL backend now passes the FULL in-process store conformance suite (TestConformance -# = conformance.RunAll, the same ~40 behavior subtests the Dolt reference runs) — the only -# methods it does NOT implement are the genuinely-Dolt-only ones (version-control/remote/ -# sync/…), which RunAll does not exercise. Alongside RunAll: live smoke, the -# interface-completeness audit (shell == deferral allowlist — no SILENT unsupported) plus -# its behavioral complement (every allowlisted method returns typed ErrUnsupported), the -# seed-once regression, and the dialect corpus-PREPARE + password-redaction gates. All -# self-skip without BEADS_PG_TEST_URL — or hard-fail when BEADS_CONFORMANCE_REQUIRE -# lists postgres (see run_sql_conformance), so CI can't go green with the wedge absent. -run_sql_conformance postgres ./internal/storage/postgres/ \ - 'TestPGSmoke|TestInterfaceCompleteness|TestUnsupportedContract|TestConformance|TestSeedOnlyOnFirstProvision' \ - BEADS_PG_TEST_URL -CGO_ENABLED=1 go test -tags "$TAGS" ./internal/storage/pgdialect/ -# MySQL wedge gates (self-skip without BEADS_MYSQL_TEST_URL, or hard-fail when -# BEADS_CONFORMANCE_REQUIRE lists mysql); the dialect rewrite test (the is_blocked 1093 -# workaround) always runs. -run_sql_conformance mysql ./internal/storage/mysql/ \ - 'TestInterfaceCompleteness|TestUnsupportedContract|TestConformance|TestSeedOnlyOnFirstProvision' \ - BEADS_MYSQL_TEST_URL -CGO_ENABLED=1 go test -tags "$TAGS" ./internal/storage/mysqldialect/ -# SQLite is embedded (pure-Go), always runs. -CGO_ENABLED=1 go test -tags "$TAGS" ./internal/storage/sqlite/ \ - -run 'TestInterfaceCompleteness|TestUnsupportedContract|TestConformance|TestSeedOnlyOnFirstProvision' -CGO_ENABLED=1 go test -tags "$TAGS" ./internal/storage/sqlitedialect/ - -echo "==> Tier 2: end-to-end 'bd init' + CLI conformance (differential vs Dolt)" +echo "==> Tier 2: end-to-end 'bd init' + CLI conformance (reference round-trip)" CGO_ENABLED=1 go test -tags "$TAGS e2e" ./test/conformance/ -if [[ "${CONFORMANCE_DEEP:-0}" == "1" ]]; then - echo "==> Deep: bts-rs 523-scenario differential oracle" - ./scripts/run-oracle-p.sh -fi - echo "==> conformance OK" diff --git a/scripts/run-oracle-p.sh b/scripts/run-oracle-p.sh deleted file mode 100755 index f4ba3597f..000000000 --- a/scripts/run-oracle-p.sh +++ /dev/null @@ -1,56 +0,0 @@ -#!/usr/bin/env bash -# -# Deep conformance gate: the bts-rs 523-scenario differential oracle, PG-vs-Dolt. -# Reference = bd in Dolt mode; candidate = the SAME bd via a thin flag-injector that -# runs native `bd init --backend=postgres`. On-demand only (needs the bts-rs checkout, -# a live Postgres, and ~50 min); invoked by scripts/conformance.sh when CONFORMANCE_DEEP=1. -# -# Env: -# BTS_RS_DIR path to the bts-rs checkout (required) -# BEADS_PG_TEST_URL postgres URL incl. password (required) -# BD path to a prebuilt bd binary (optional; built if unset) -# -set -euo pipefail -cd "$(dirname "$0")/.." -: "${BTS_RS_DIR:?set BTS_RS_DIR to the bts-rs checkout}" -: "${BEADS_PG_TEST_URL:?set BEADS_PG_TEST_URL (postgres URL incl. password)}" - -BD="${BD:-}" -if [[ -z "$BD" ]]; then - BD="$(mktemp -d)/bd" - echo "### building bd -> $BD" - CGO_ENABLED=1 go build -tags gms_pure_go -o "$BD" ./cmd/bd -fi - -# Thin flag-injector: native `bd init` does the metadata + schema + seeding; this only -# supplies the backend flags the backend-agnostic harness cannot know, plus a -# deterministic per-workspace schema and a default prefix so IDs match the reference. -WRAP="$(mktemp)" -cat > "$WRAP" </dev/null | psql "$BEADS_PG_TEST_URL" >/dev/null 2>&1 || true - -cd "$BTS_RS_DIR" -echo "### capturing goldens from bd-Dolt" -BTS_CATALOG=1 BTS_REFERENCE_BD="$BD" cargo run --release -q -p bts-conformance --bin capture_golden 2>&1 | tail -4 -echo "### scoring native bd-PG against fresh goldens" -BTS_CATALOG=1 BTS_CANDIDATE="$WRAP" BTS_DATABASE_URL="$BEADS_PG_TEST_URL" \ - cargo run --release -q -p bts-conformance --bin scoreboard 2>&1 | tail -30 -git -C "$BTS_RS_DIR" checkout crates/bts-conformance/testdata/golden >/dev/null 2>&1 || true -echo "### DONE" diff --git a/test/conformance/e2e_test.go b/test/conformance/e2e_test.go index 5df2983df..aa1466493 100644 --- a/test/conformance/e2e_test.go +++ b/test/conformance/e2e_test.go @@ -20,11 +20,9 @@ import ( // scenario is a named sequence of bd CLI invocations. IDs are pinned with --id so // they match across backends; only timestamps/paths need normalization. // -// unordered marks a scenario whose JSON-array output has no contractual order: bd -// sorts by priority then created_at, and Postgres's whole-second timestamps tie where -// Dolt's sub-second ones do not, so equal-priority items created in the same second -// can legitimately differ in order. For these, array elements are sorted by id before -// comparison (matching the bts-rs oracle's multiset semantics for list output). +// unordered marks a scenario whose JSON-array output has no contractual order. For +// these, array elements are sorted by id before comparison (matching the bts-rs +// oracle's multiset semantics for list output). type scenario struct { name string steps [][]string @@ -33,7 +31,7 @@ type scenario struct { // corpus is the backend-agnostic CLI surface exercised end-to-end. It is deliberately // compact (the gc lifecycle + config), and grows over time; the bts-rs 523-scenario -// differential oracle (scripts/run-oracle-p.sh) remains the deep gate. +// differential corpus exercises both maintained storage families. var corpus = []scenario{ {name: "create-show", steps: [][]string{ {"create", "First task", "--id", "cf-a1", "-t", "task", "--json"}, @@ -75,8 +73,7 @@ var corpus = []scenario{ {"config", "unset", "custom.foo"}, {"config", "get", "custom.foo"}, }}, - // Deferred surfaces, present to exercise XFail classification against the - // postgres profile's allowlist (the reference passes these). + // Deferred surfaces exercise the typed unsupported-operation contract. {name: "stats", steps: [][]string{ {"create", "s", "--id", "cf-s1", "-t", "task"}, {"stats", "--json"}, @@ -143,12 +140,10 @@ var corpus = []scenario{ // comment UUIDv7 the CLI harness can't normalize, so it is not a CLI-differential.) // Case-variant config key round-trip. `config set` passes the key verbatim to // store.SetConfig (no ToLower) and namespaced keys bypass the recognized-key - // allowlist, so custom.TeamName reaches the store as-is. On the embedded-Dolt - // reference the key column is case-SENSITIVE (verified at the store layer), so + // allowlist, so custom.TeamName reaches the store as-is. On both maintained + // backends the key column is case-sensitive, so // `config get custom.teamname` does NOT see the value set under custom.TeamName, - // while `config get custom.TeamName` does. config set/get/unset all run on SQL - // backends. Divergence suspect: real MySQL's case-insensitive default collation - // would make custom.teamname resolve to the custom.TeamName row. + // while `config get custom.TeamName` does. {name: "config-case-variant-key", steps: [][]string{ {"config", "set", "custom.TeamName", "example-org"}, {"config", "get", "custom.teamname"}, @@ -164,8 +159,8 @@ var corpus = []scenario{ {"create", "childB", "-t", "task", "--parent", "cf-cp1", "--json"}, {"list", "--json"}, }}, - // (bd mol wisp list order is non-contractual for equal-second ties — Dolt/PG vs - // MySQL/SQLite differ on tie order in the nested wisps array, which the harness can't + // (bd mol wisp list order is non-contractual for equal-second ties — backends + // can differ on tie order in the nested wisps array, which the harness can't // normalize; ListWisps is covered as a set at the store level.) // All cli-differential scenarios below were driven end-to-end against the // embedded-Dolt reference (bd built with -tags gms_pure_go, `bd init -p cf`) and @@ -310,35 +305,14 @@ func TestConformanceE2E(t *testing.T) { ref := Reference() cands := Candidates() if len(cands) == 0 { - t.Skip("no candidate backends available (set BEADS_PG_TEST_URL for the postgres profile)") + t.Skip("no candidate backends registered; the differential harness is idle until another backend profile is added") } - // Make coverage visible: sqlite's Available() is always true, so a run with - // BEADS_PG_TEST_URL/BEADS_MYSQL_TEST_URL unset compares only sqlite yet still - // passes green. Log the candidate set, and honor BEADS_CONFORMANCE_REQUIRE - // (comma-separated profile names) so CI hard-fails when an expected backend is - // absent rather than silently narrowing coverage. + // Make coverage visible in test logs. names := make([]string, len(cands)) for i, c := range cands { names[i] = c.Name } t.Logf("E2E differential candidates: %v (reference=%s)", names, ref.Name) - if req := strings.TrimSpace(os.Getenv("BEADS_CONFORMANCE_REQUIRE")); req != "" { - for _, want := range strings.Split(req, ",") { - if want = strings.TrimSpace(want); want == "" { - continue - } - found := false - for _, n := range names { - if n == want { - found = true - break - } - } - if !found { - t.Fatalf("BEADS_CONFORMANCE_REQUIRE lists %q but that candidate is unavailable (set its BEADS_*_TEST_URL)", want) - } - } - } for _, sc := range corpus { sc := sc t.Run(sc.name, func(t *testing.T) { @@ -365,12 +339,6 @@ func TestConformanceE2E(t *testing.T) { func runScenario(t *testing.T, bin string, p BackendProfile, sc scenario) []string { t.Helper() ws := &Workspace{Dir: t.TempDir()} - if p.NewHandle != nil { - ws.Handle = p.NewHandle() - } - if p.Teardown != nil { - t.Cleanup(func() { p.Teardown(ws) }) - } var env []string if p.Env != nil { env = p.Env(ws) @@ -440,13 +408,10 @@ var ( reRoleWarn = regexp.MustCompile(`(?m)^warning: beads\.role not configured \(GH#2950\)\.\n(?:^ (?:Fix|Or): .*\n?)*`) ) -// normalize removes cross-backend and cross-run noise: workspace path, schema handle, -// timestamps, and random tip banners. Pinned IDs need no normalization. +// normalize removes cross-backend and cross-run noise: workspace path, timestamps, +// and random tip banners. Pinned IDs need no normalization. func normalize(s string, ws *Workspace) string { s = strings.ReplaceAll(s, ws.Dir, "") - if ws.Handle != "" { - s = strings.ReplaceAll(s, ws.Handle, "") - } s = reZeroTS.ReplaceAllString(s, "") s = reTimestamp.ReplaceAllString(s, "") s = reTip.ReplaceAllString(s, "") diff --git a/test/conformance/handle.go b/test/conformance/handle.go deleted file mode 100644 index df0b3b685..000000000 --- a/test/conformance/handle.go +++ /dev/null @@ -1,61 +0,0 @@ -package conformance - -import ( - "context" - "database/sql" - "fmt" - "os" - "sync/atomic" - - gomysql "github.com/go-sql-driver/mysql" - "github.com/steveyegge/beads/internal/storage/pgdialect" -) - -var handleSeq int64 - -// freshSchemaName mints a process-unique Postgres schema name. The pid keeps names -// distinct across concurrent runs and after a crashed run; teardown drops them. -func freshSchemaName() string { - return fmt.Sprintf("e2e_%d_%d", os.Getpid(), atomic.AddInt64(&handleSeq, 1)) -} - -// dropPostgresSchema tears down a workspace's schema. Best effort: a failure here -// only leaves a stray schema, which the next run's freshSchemaName avoids colliding -// with. Uses a raw (non-translating) connection since DROP SCHEMA is native DDL. -func dropPostgresSchema(ws *Workspace) { - if ws.Handle == "" { - return - } - url := os.Getenv("BEADS_PG_TEST_URL") - if url == "" { - return - } - raw, err := pgdialect.OpenRaw(url, "public") - if err != nil { - return - } - defer raw.Close() - _, _ = raw.ExecContext(context.Background(), fmt.Sprintf(`DROP SCHEMA IF EXISTS %q CASCADE`, ws.Handle)) -} - -// dropMySQLDatabase tears down a workspace's database. Best effort. -func dropMySQLDatabase(ws *Workspace) { - if ws.Handle == "" { - return - } - url := os.Getenv("BEADS_MYSQL_TEST_URL") - if url == "" { - return - } - cfg, err := gomysql.ParseDSN(url) - if err != nil { - return - } - cfg.DBName = "" - db, err := sql.Open("mysql", cfg.FormatDSN()) - if err != nil { - return - } - defer db.Close() - _, _ = db.ExecContext(context.Background(), "DROP DATABASE IF EXISTS `"+ws.Handle+"`") -} diff --git a/test/conformance/profiles.go b/test/conformance/profiles.go index 626b3296e..27a2fa043 100644 --- a/test/conformance/profiles.go +++ b/test/conformance/profiles.go @@ -1,24 +1,19 @@ // Package conformance is the end-to-end (real `bd` binary) conformance harness. It // complements the in-process store suite (internal/storage/conformance): that one // exercises a store object; this one exercises the whole CLI path — `bd init`, the -// factory, metadata.json, dialect translation over the real binary, and output -// formatting — differentially against the Dolt reference. +// factory, metadata.json, and output formatting — differentially against the Dolt +// reference. // // One declarative registry (Profiles) describes how to create and tear down an // isolated workspace for each backend. Adding a backend is one Profiles entry; the // runner and scripts/conformance.sh pick it up automatically. The suite is behind -// the `e2e` build tag because it shells out to a freshly built bd and needs live -// backends for the non-default profiles. +// the `e2e` build tag because it shells out to a freshly built bd. package conformance -import "os" - // Workspace is one isolated place a backend can be `bd init`-ed. Dir is the working -// directory (its .beads/ is created by init); Handle is a backend-specific isolation -// id (a Postgres schema, a server database, …) used for teardown. +// directory; init creates its .beads directory. type Workspace struct { - Dir string - Handle string + Dir string } // BackendProfile declares everything the E2E runner needs to init and isolate a @@ -37,11 +32,6 @@ type BackendProfile struct { InitArgs func(ws *Workspace) []string // Env returns extra environment (KEY=VALUE) for every bd invocation in ws. Env func(ws *Workspace) []string - // NewHandle mints a fresh isolation id (schema/db name) for a workspace. Empty - // for backends isolated purely by directory (embedded Dolt). - NewHandle func() string - // Teardown releases the isolation (drop schema/db). Best effort; may be nil. - Teardown func(ws *Workspace) // XFail lists scenarios this backend is known not to match the reference on, // each with a reason. They are reported as XFAIL (visible, never masked); an // XFAIL that starts matching is flagged so the list can only shrink. @@ -56,50 +46,6 @@ var Profiles = []BackendProfile{ Available: func() bool { return true }, InitArgs: func(*Workspace) []string { return nil }, }, - { - Name: "postgres", - Available: func() bool { return os.Getenv("BEADS_PG_TEST_URL") != "" }, - NewHandle: freshSchemaName, - InitArgs: func(ws *Workspace) []string { - return []string{ - "--backend=postgres", - "--pg-url=" + os.Getenv("BEADS_PG_TEST_URL"), - "--pg-schema=" + ws.Handle, - } - }, - Env: func(*Workspace) []string { - if pw := os.Getenv("BEADS_PG_PASSWORD"); pw != "" { - return []string{"BEADS_PG_PASSWORD=" + pw} - } - return nil - }, - Teardown: dropPostgresSchema, - }, - { - Name: "mysql", - Available: func() bool { return os.Getenv("BEADS_MYSQL_TEST_URL") != "" }, - NewHandle: freshSchemaName, // a valid MySQL database name - InitArgs: func(ws *Workspace) []string { - return []string{ - "--backend=mysql", - "--mysql-url=" + os.Getenv("BEADS_MYSQL_TEST_URL"), - "--mysql-database=" + ws.Handle, - } - }, - Env: func(*Workspace) []string { - // The server DSN (with password) is used for every command; the - // per-workspace database comes from metadata.json / --mysql-database. - return []string{"BEADS_MYSQL_URL=" + os.Getenv("BEADS_MYSQL_TEST_URL")} - }, - Teardown: dropMySQLDatabase, - }, - { - Name: "sqlite", - Available: func() bool { return true }, // embedded (pure-Go modernc); always runs - // File-based: the default beads.db inside each workspace's .beads dir isolates - // it; the temp workspace dir cleanup removes the file. No handle/env/teardown. - InitArgs: func(*Workspace) []string { return []string{"--backend=sqlite"} }, - }, } // Reference returns the single reference profile. diff --git a/test/conformance/roundtrip_test.go b/test/conformance/roundtrip_test.go index fea1e97a4..0c61a069b 100644 --- a/test/conformance/roundtrip_test.go +++ b/test/conformance/roundtrip_test.go @@ -12,12 +12,10 @@ import ( "testing" ) -// The portable JSONL backup path — `bd export` -> git -> `bd import` — is the only -// backup mechanism the non-Dolt backends have (Dolt-native CALL DOLT_BACKUP is -// unsupported on them, and auto-export is gated to Dolt because its change token is -// the Dolt commit hash). The manual round-trip is already lossless on every backend -// (verified live against real Postgres/MySQL); this test pins that so a regression in -// export or import cannot slip through CI. +// The portable JSONL backup path — `bd export` -> git -> `bd import` — is the +// backend-agnostic backup mechanism for stores without Dolt-native CALL +// DOLT_BACKUP and commit hashes. This test pins the manual round-trip so a +// regression in export or import cannot slip through CI. // // It is a self-consistency (idempotence) check, not a differential one, so it lives // outside the `corpus`: for each backend it seeds a rich fixture, exports, restores @@ -125,18 +123,11 @@ func restoreAndReexport(t *testing.T, bin string, p BackendProfile, exportJSONL return mustRead(t, out) } -// initRoundTripWorkspace mints an isolated workspace for a backend (fresh temp dir plus -// a fresh handle/schema for the server backends) and runs `bd init`. Prefix "rt" matches -// the pinned rt-* ids in the seed. +// initRoundTripWorkspace creates an isolated temporary workspace and runs `bd init`. +// Prefix "rt" matches the pinned rt-* ids in the seed. func initRoundTripWorkspace(t *testing.T, bin string, p BackendProfile) (*Workspace, []string) { t.Helper() ws := &Workspace{Dir: t.TempDir()} - if p.NewHandle != nil { - ws.Handle = p.NewHandle() - } - if p.Teardown != nil { - t.Cleanup(func() { p.Teardown(ws) }) - } var env []string if p.Env != nil { env = p.Env(ws)