diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 955545b..e861902 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -82,7 +82,7 @@ jobs: # devteam_test_pipeline, devteam_test_chat). The postgres service # container only creates the default DB, so create the rest here. run: | - for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat; do + for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat devteam_test_config devteam_test_defaults; do PGPASSWORD=devteam psql -h localhost -U devteam -d devteam -c "CREATE DATABASE $db;" || true done @@ -159,7 +159,7 @@ jobs: - name: Create test databases run: | - for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat; do + for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat devteam_test_config devteam_test_defaults; do PGPASSWORD=devteam psql -h localhost -U devteam -d devteam -c "CREATE DATABASE $db;" || true done @@ -249,7 +249,7 @@ jobs: # The full test suite exercises every package, each with its own # isolated test DB. Create them all here. run: | - for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat; do + for db in devteam_test_db devteam_test_api devteam_test_spec devteam_test_intake devteam_test_pipeline devteam_test_chat devteam_test_config devteam_test_defaults; do PGPASSWORD=devteam psql -h localhost -U devteam -d devteam -c "CREATE DATABASE $db;" || true done diff --git a/internal/api/server_test.go b/internal/api/server_test.go index 698e782..d9e1f62 100644 --- a/internal/api/server_test.go +++ b/internal/api/server_test.go @@ -77,6 +77,7 @@ func truncateTables(database *db.DB) { "phase_states", "gate_results", "recirculations", "features", "repos", "stage_logs", + "repo_operation_config", } for _, table := range tables { database.Conn().Exec("TRUNCATE TABLE " + table + " CASCADE") diff --git a/internal/db/migration_018.go b/internal/db/migration_018.go new file mode 100644 index 0000000..8ec2277 --- /dev/null +++ b/internal/db/migration_018.go @@ -0,0 +1,42 @@ +package db + +import ( + "database/sql" + "fmt" +) + +func init() { + RegisterMigration(Migration{ + Version: 18, + Name: "repo_operation_config", + Up: migration018RepoOperationConfig, + }) +} + +// migration018RepoOperationConfig creates the per-repo operation-phase +// configuration table. It is keyed by repo_name (the same identifier used in +// feature_repos and repos.yaml) but is NOT foreign-keyed to feature_repos — +// operation config is a permanent per-repo fact; feature_repos rows are +// transient per-feature worktree coords (C-D3). JSONB columns carry the typed +// payload so schema evolution is a shape change, not ALTER TABLE (C-D4). +// ci_platform / cd_platform are free-text labels, not an enum (C-D5). +func migration018RepoOperationConfig(tx *sql.Tx) error { + statements := []string{ + `CREATE TABLE IF NOT EXISTS repo_operation_config ( + repo_name TEXT PRIMARY KEY, + ci_platform TEXT DEFAULT '', + cd_platform TEXT DEFAULT '', + environments JSONB DEFAULT '{}', + observability JSONB DEFAULT '{}', + incident_response JSONB DEFAULT '{}', + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL + )`, + } + for _, stmt := range statements { + if _, err := tx.Exec(stmt); err != nil { + return fmt.Errorf("executing statement: %w\nSQL: %s", err, stmt) + } + } + return nil +} diff --git a/internal/db/migration_018_smoke_test.go b/internal/db/migration_018_smoke_test.go new file mode 100644 index 0000000..78e2f4a --- /dev/null +++ b/internal/db/migration_018_smoke_test.go @@ -0,0 +1,68 @@ +package db + +import ( + "fmt" + "testing" +) + +// TestMigration018_Applies verifies migration 018 creates the +// repo_operation_config table with the correct columns and no FK. +func TestMigration018_Applies(t *testing.T) { + d := setupTestDB(t) + // setupTestDB already ran migrations (including 018) on connect. + // Verify columns. + rows, err := d.Conn().Query(`SELECT column_name, data_type, column_default FROM information_schema.columns WHERE table_name = 'repo_operation_config' ORDER BY ordinal_position`) + if err != nil { + t.Fatalf("query columns: %v", err) + } + defer rows.Close() + + type col struct { + name, dtype, def string + } + got := []col{} + for rows.Next() { + var c col + var def any + if err := rows.Scan(&c.name, &c.dtype, &def); err != nil { + t.Fatalf("scan: %v", err) + } + if def != nil { + c.def = fmt.Sprintf("%v", def) + } + got = append(got, c) + } + want := []col{ + {"repo_name", "text", ""}, + {"ci_platform", "text", "''::text"}, + {"cd_platform", "text", "''::text"}, + {"environments", "jsonb", "'{}'::jsonb"}, + {"observability", "jsonb", "'{}'::jsonb"}, + {"incident_response", "jsonb", "'{}'::jsonb"}, + {"created_at", "timestamp with time zone", ""}, + {"updated_at", "timestamp with time zone", ""}, + } + if len(got) != len(want) { + t.Fatalf("columns: got %d, want %d — %+v", len(got), len(want), got) + } + for i, w := range want { + if got[i].name != w.name { + t.Errorf("col[%d] name = %q, want %q", i, got[i].name, w.name) + } + if got[i].dtype != w.dtype { + t.Errorf("col[%d] type = %q, want %q", i, got[i].dtype, w.dtype) + } + } + // Verify no FK. + var fkCount int + d.Conn().QueryRow(`SELECT COUNT(*) FROM information_schema.table_constraints WHERE table_name = 'repo_operation_config' AND constraint_type = 'FOREIGN KEY'`).Scan(&fkCount) + if fkCount != 0 { + t.Errorf("FK count = %d, want 0 (C-D3)", fkCount) + } + // Verify row count is 0 (FR-SCHEMA-06). + var n int + d.Conn().QueryRow(`SELECT count(*) FROM repo_operation_config`).Scan(&n) + if n != 0 { + t.Errorf("row count = %d, want 0 (table starts empty)", n) + } +} diff --git a/internal/db/repo_operation_config_store.go b/internal/db/repo_operation_config_store.go new file mode 100644 index 0000000..574af8a --- /dev/null +++ b/internal/db/repo_operation_config_store.go @@ -0,0 +1,196 @@ +package db + +import ( + "database/sql" + "encoding/json" + "fmt" + "strings" + "time" +) + +// RepoOperationConfigRow is a per-repo operation-phase configuration record. +// JSONB fields are json.RawMessage to preserve the operator's exact bytes +// (unknown keys, nested shapes, key ordering for human-readable diffs). The +// platform treats JSONB as opaque (C-A5, ADR-03) — it never unmarshals these +// fields except the API's one-time "is valid JSON" check. Empty JSONB +// serializes as {}, never null (DR-R6, Agent Failure Mode Awareness). +type RepoOperationConfigRow struct { + RepoName string `json:"repo_name"` + CiPlatform string `json:"ci_platform"` + CdPlatform string `json:"cd_platform"` + Environments json.RawMessage `json:"environments"` + Observability json.RawMessage `json:"observability"` + IncidentResponse json.RawMessage `json:"incident_response"` + CreatedAt time.Time `json:"created_at"` + UpdatedAt time.Time `json:"updated_at"` +} + +// SaveOperationConfig upserts a per-repo operation config row. +// Idempotent: re-saving the same row advances updated_at but does not +// duplicate (ON CONFLICT(repo_name) DO UPDATE — FR-STORE-02). created_at is +// set on insert and left unchanged on update (excluded.created_at re-writes +// it, but since we pass `now` for both, the row's created_at only differs +// from updated_at on the first insert when the table sets it via DEFAULT; +// here we pass now for both columns, so on insert both equal now, on update +// updated_at advances and created_at is overwritten with the same now — +// which is acceptable since the store is the only writer and the operator +// does not rely on created_at being immutable across upserts for this +// single-writer table). +func (db *DB) SaveOperationConfig(row RepoOperationConfigRow) error { + now := time.Now().UTC() + _, err := db.Exec( + `INSERT INTO repo_operation_config + (repo_name, ci_platform, cd_platform, environments, + observability, incident_response, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_name) DO UPDATE SET + ci_platform = excluded.ci_platform, + cd_platform = excluded.cd_platform, + environments = excluded.environments, + observability = excluded.observability, + incident_response = excluded.incident_response, + updated_at = excluded.updated_at`, + row.RepoName, row.CiPlatform, row.CdPlatform, + ensureJSONB(row.Environments), ensureJSONB(row.Observability), ensureJSONB(row.IncidentResponse), + now, now, + ) + if err != nil { + return fmt.Errorf("saving operation config for %s: %w", row.RepoName, err) + } + return nil +} + +// GetOperationConfig returns the config for a single repo. +// If no row exists, returns a zero-value row (not an error) — C-A7 backward +// compat / FR-STORE-05. Empty JSONB columns are normalized to []byte("{}") so +// the caller never sees null (DR-R6). +func (db *DB) GetOperationConfig(repoName string) (RepoOperationConfigRow, error) { + row := RepoOperationConfigRow{ + RepoName: repoName, + Environments: []byte("{}"), + Observability: []byte("{}"), + IncidentResponse: []byte("{}"), + } + err := db.QueryRow( + `SELECT ci_platform, cd_platform, environments, observability, + incident_response, created_at, updated_at + FROM repo_operation_config WHERE repo_name = ?`, + repoName, + ).Scan(&row.CiPlatform, &row.CdPlatform, &row.Environments, + &row.Observability, &row.IncidentResponse, + &row.CreatedAt, &row.UpdatedAt) + if err == sql.ErrNoRows { + return row, nil // zero-value, no error (FR-STORE-05) + } + if err != nil { + return row, fmt.Errorf("getting operation config for %s: %w", repoName, err) + } + normalizeEmptyJSONB(&row.Environments) + normalizeEmptyJSONB(&row.Observability) + normalizeEmptyJSONB(&row.IncidentResponse) + return row, nil +} + +// GetAllOperationConfigs returns all configured repos ordered by repo_name. +// Empty table → non-nil, zero-length slice (FR-STORE-03, DR-R6 — never null). +func (db *DB) GetAllOperationConfigs() ([]RepoOperationConfigRow, error) { + rows, err := db.Query( + `SELECT repo_name, ci_platform, cd_platform, environments, + observability, incident_response, created_at, updated_at + FROM repo_operation_config ORDER BY repo_name ASC`) + if err != nil { + return nil, fmt.Errorf("getting all operation configs: %w", err) + } + defer rows.Close() + + out := []RepoOperationConfigRow{} // EMPTY, not nil (DR-R6) + for rows.Next() { + var r RepoOperationConfigRow + if err := rows.Scan(&r.RepoName, &r.CiPlatform, &r.CdPlatform, + &r.Environments, &r.Observability, &r.IncidentResponse, + &r.CreatedAt, &r.UpdatedAt); err != nil { + return nil, fmt.Errorf("scanning operation config: %w", err) + } + normalizeEmptyJSONB(&r.Environments) + normalizeEmptyJSONB(&r.Observability) + normalizeEmptyJSONB(&r.IncidentResponse) + out = append(out, r) + } + return out, nil +} + +// GetOperationConfigsByRepoNames returns configs for the named repos in a +// single query. Used by the dispatch bridge to avoid N+1 (NFR-PERF-02 — the +// bridge makes one GetFeatureRepos query + this one query = ≤2 total). Repos +// with no row are omitted from the result; the caller treats absence as "no +// config" (FR-BRIDGE-04). +func (db *DB) GetOperationConfigsByRepoNames(names []string) ([]RepoOperationConfigRow, error) { + if len(names) == 0 { + return []RepoOperationConfigRow{}, nil + } + placeholders := make([]string, len(names)) + args := make([]any, len(names)) + for i, n := range names { + placeholders[i] = "?" + args[i] = n + } + query := `SELECT repo_name, ci_platform, cd_platform, environments, + observability, incident_response, created_at, updated_at + FROM repo_operation_config WHERE repo_name IN (` + + strings.Join(placeholders, ", ") + `) ORDER BY repo_name ASC` + rows, err := db.Query(query, args...) + if err != nil { + return nil, fmt.Errorf("getting operation configs by repo names: %w", err) + } + defer rows.Close() + + out := []RepoOperationConfigRow{} + for rows.Next() { + var r RepoOperationConfigRow + if err := rows.Scan(&r.RepoName, &r.CiPlatform, &r.CdPlatform, + &r.Environments, &r.Observability, &r.IncidentResponse, + &r.CreatedAt, &r.UpdatedAt); err != nil { + return nil, fmt.Errorf("scanning operation config: %w", err) + } + normalizeEmptyJSONB(&r.Environments) + normalizeEmptyJSONB(&r.Observability) + normalizeEmptyJSONB(&r.IncidentResponse) + out = append(out, r) + } + return out, nil +} + +// DeleteOperationConfig removes a repo's config row. Deleting a non-existent +// row is a no-op (not an error) — matches DeleteTeamKnowledge semantics. +func (db *DB) DeleteOperationConfig(repoName string) error { + _, err := db.Exec(`DELETE FROM repo_operation_config WHERE repo_name = ?`, repoName) + if err != nil { + return fmt.Errorf("deleting operation config for %s: %w", repoName, err) + } + return nil +} + +// ensureJSONB normalizes the incoming JSONB bytes for a save: nil/empty/null +// becomes {} so the DB never stores NULL and the API never returns null +// (DR-R6). Valid JSON passes through unchanged. +func ensureJSONB(b json.RawMessage) json.RawMessage { + if len(b) == 0 { + return json.RawMessage("{}") + } + // Postgres JSONB does not accept the literal Go "null" as a column + // default replacement cleanly across all driver versions; normalize + // to {} for storage consistency. + if string(b) == "null" { + return json.RawMessage("{}") + } + return b +} + +// normalizeEmptyJSONB replaces nil/empty/`null` json.RawMessage with {} so +// the caller never serializes null (DR-R6 / empty-not-null contract). This is +// the single point that enforces empty-not-null on every read path. +func normalizeEmptyJSONB(b *json.RawMessage) { + if b == nil || len(*b) == 0 || string(*b) == "null" { + *b = json.RawMessage("{}") + } +} diff --git a/internal/db/repo_operation_config_store_test.go b/internal/db/repo_operation_config_store_test.go new file mode 100644 index 0000000..e913330 --- /dev/null +++ b/internal/db/repo_operation_config_store_test.go @@ -0,0 +1,308 @@ +package db + +import ( + "encoding/json" + "reflect" + "strings" + "testing" +) + +// sampleRow builds a RepoOperationConfigRow with representative JSONB payloads +// for round-trip and upsert tests. +func sampleRow(name string) RepoOperationConfigRow { + return RepoOperationConfigRow{ + RepoName: name, + CiPlatform: "github-actions", + CdPlatform: "argocd", + Environments: json.RawMessage(`{"staging":{"cd_platform":"argocd"},"prod":{"cd_platform":"argocd","observability":{"prometheus":true}}}`), + Observability: json.RawMessage(`{"prometheus":true,"grafana":true,"loki":false}`), + IncidentResponse: json.RawMessage(`{"oncall_rotation":"primary","pagerduty":true}`), + } +} + +func TestSaveAndGetOperationConfig(t *testing.T) { + d := setupTestDB(t) + row := sampleRow("repo-a") + if err := d.SaveOperationConfig(row); err != nil { + t.Fatalf("SaveOperationConfig: %v", err) + } + got, err := d.GetOperationConfig("repo-a") + if err != nil { + t.Fatalf("GetOperationConfig: %v", err) + } + if got.RepoName != "repo-a" { + t.Errorf("RepoName = %q, want repo-a", got.RepoName) + } + if got.CiPlatform != "github-actions" { + t.Errorf("CiPlatform = %q, want github-actions", got.CiPlatform) + } + if got.CdPlatform != "argocd" { + t.Errorf("CdPlatform = %q, want argocd", got.CdPlatform) + } + // JSONB semantic round-trip (C-A5 opacity): Postgres JSONB normalizes + // whitespace and sorts keys, so we compare semantic content, not bytes. + assertJSONBSemanticEqual(t, "Environments", got.Environments, row.Environments) + assertJSONBSemanticEqual(t, "Observability", got.Observability, row.Observability) + assertJSONBSemanticEqual(t, "IncidentResponse", got.IncidentResponse, row.IncidentResponse) + if got.CreatedAt.IsZero() { + t.Error("CreatedAt should be set by the store on insert") + } + if got.UpdatedAt.IsZero() { + t.Error("UpdatedAt should be set by the store on insert") + } +} + +// assertJSONBSemanticEqual compares two json.RawMessage by semantic content +// (unmarshal to map[string]any and compare). Postgres JSONB normalizes +// whitespace and key order on storage, so byte-exact comparison would fail +// even when the content is identical. The opacity contract (C-A5) requires +// that every key and value the operator wrote is preserved — semantic +// equality is the correct assertion. +func assertJSONBSemanticEqual(t *testing.T, field string, got, want json.RawMessage) { + t.Helper() + var gotMap, wantMap map[string]any + if err := json.Unmarshal(got, &gotMap); err != nil { + t.Fatalf("%s: unmarshal got: %v (raw=%s)", field, err, got) + } + if err := json.Unmarshal(want, &wantMap); err != nil { + t.Fatalf("%s: unmarshal want: %v (raw=%s)", field, err, want) + } + if len(gotMap) != len(wantMap) { + t.Errorf("%s: key count changed (opacity — got %d, want %d)", field, len(gotMap), len(wantMap)) + return + } + for k, wantVal := range wantMap { + gotVal, ok := gotMap[k] + if !ok { + t.Errorf("%s: key %q lost in round-trip (opacity violated — C-A5)", field, k) + continue + } + if !reflect.DeepEqual(gotVal, wantVal) { + t.Errorf("%s: key %q value changed: got %v, want %v", field, k, gotVal, wantVal) + } + } +} + +func TestGetOperationConfig_Missing(t *testing.T) { + d := setupTestDB(t) + got, err := d.GetOperationConfig("nonexistent-repo") + if err != nil { + t.Fatalf("GetOperationConfig missing row should not error, got: %v", err) + } + if got.RepoName != "nonexistent-repo" { + t.Errorf("RepoName = %q, want nonexistent-repo (caller's name echoed)", got.RepoName) + } + if got.CiPlatform != "" { + t.Errorf("CiPlatform = %q, want empty (zero-value)", got.CiPlatform) + } + if got.CdPlatform != "" { + t.Errorf("CdPlatform = %q, want empty (zero-value)", got.CdPlatform) + } + // Empty-not-null (DR-R6): JSONB fields must be {} not null. + if string(got.Environments) != "{}" { + t.Errorf("Environments = %s, want {} (DR-R6 empty-not-null)", got.Environments) + } + if string(got.Observability) != "{}" { + t.Errorf("Observability = %s, want {} (DR-R6 empty-not-null)", got.Observability) + } + if string(got.IncidentResponse) != "{}" { + t.Errorf("IncidentResponse = %s, want {} (DR-R6 empty-not-null)", got.IncidentResponse) + } + if !got.CreatedAt.IsZero() { + t.Errorf("CreatedAt = %v, want zero for a missing row", got.CreatedAt) + } +} + +func TestGetAllOperationConfigs_Empty(t *testing.T) { + d := setupTestDB(t) + got, err := d.GetAllOperationConfigs() + if err != nil { + t.Fatalf("GetAllOperationConfigs: %v", err) + } + if got == nil { + t.Fatal("got nil slice, want non-nil empty slice (DR-R6 / FR-STORE-03)") + } + if len(got) != 0 { + t.Errorf("len = %d, want 0 on empty table", len(got)) + } + // JSON marshal must yield [], not null (FR-TEST-06). + b, _ := json.Marshal(got) + if string(b) != "[]" { + t.Errorf("JSON marshal of empty slice = %s, want [] (FR-TEST-06)", b) + } +} + +func TestSaveOperationConfig_Idempotent(t *testing.T) { + d := setupTestDB(t) + row := sampleRow("repo-idem") + if err := d.SaveOperationConfig(row); err != nil { + t.Fatalf("first save: %v", err) + } + first, err := d.GetOperationConfig("repo-idem") + if err != nil { + t.Fatalf("first get: %v", err) + } + // Save again — must not duplicate, must not error. + if err := d.SaveOperationConfig(row); err != nil { + t.Fatalf("second save: %v", err) + } + second, err := d.GetOperationConfig("repo-idem") + if err != nil { + t.Fatalf("second get: %v", err) + } + // Still exactly one row (FR-STORE-02). + all, _ := d.GetAllOperationConfigs() + if len(all) != 1 { + t.Errorf("after double-save, row count = %d, want 1 (FR-STORE-02 idempotent upsert)", len(all)) + } + // updated_at should advance (or at least not regress). + if second.UpdatedAt.Before(first.UpdatedAt) { + t.Errorf("UpdatedAt went backwards: first=%v second=%v", first.UpdatedAt, second.UpdatedAt) + } + // JSONB bytes preserved across upsert. + if string(second.Observability) != string(first.Observability) { + t.Errorf("Observability bytes changed across idempotent upsert (ADR-03)") + } +} + +func TestSaveOperationConfig_JSONBRoundTrip(t *testing.T) { + d := setupTestDB(t) + // Operator's payload includes unknown keys, booleans, nested structure, + // and a notes string. The platform must round-trip the *semantic* + // content (all keys and values present) — that is the opacity contract + // (C-A5): the platform does not interpret the shape, so every key the + // operator wrote must come back. + // + // NOTE: Postgres JSONB normalizes whitespace and sorts keys on storage, + // so byte-exact round-trip is NOT guaranteed by JSONB (the ADR-03 + // rationale point about "exact bytes for diffs" over-claimed — that + // would require a TEXT column, not JSONB). The binding constraints + // (C-D4 JSONB, C-A5 opacity) are satisfied by semantic round-trip: + // every key and value the operator wrote is preserved. + originalObs := json.RawMessage(`{"loki":true,"prometheus":false,"grafana":true,"notes":"order matters","datadog":false}`) + row := RepoOperationConfigRow{ + RepoName: "repo-jsonb", + CiPlatform: "gitlab-ci", + Observability: originalObs, + } + if err := d.SaveOperationConfig(row); err != nil { + t.Fatalf("SaveOperationConfig: %v", err) + } + got, err := d.GetOperationConfig("repo-jsonb") + if err != nil { + t.Fatalf("GetOperationConfig: %v", err) + } + // Semantic equality: unmarshal both to map[string]any and compare. + var wantMap, gotMap map[string]any + if err := json.Unmarshal(originalObs, &wantMap); err != nil { + t.Fatalf("unmarshal original: %v", err) + } + if err := json.Unmarshal(got.Observability, &gotMap); err != nil { + t.Fatalf("unmarshal got: %v", err) + } + if len(gotMap) != len(wantMap) { + t.Fatalf("key count changed: got %d, want %d (opacity — unknown keys must be preserved)", len(gotMap), len(wantMap)) + } + for k, wantVal := range wantMap { + gotVal, ok := gotMap[k] + if !ok { + t.Errorf("key %q lost in round-trip (opacity violated — C-A5)", k) + continue + } + if !reflect.DeepEqual(gotVal, wantVal) { + t.Errorf("key %q value changed: got %v, want %v", k, gotVal, wantVal) + } + } + // The result must be valid JSON (FR-API-07 relies on this). + if !json.Valid(got.Observability) { + t.Errorf("returned JSONB is not valid JSON: %s", got.Observability) + } +} + +func TestGetOperationConfigsByRepoNames(t *testing.T) { + d := setupTestDB(t) + // Seed 3 repos. + for _, n := range []string{"repo-1", "repo-2", "repo-3"} { + if err := d.SaveOperationConfig(sampleRow(n)); err != nil { + t.Fatalf("SaveOperationConfig %s: %v", n, err) + } + } + // Fetch 2 by name — repo-2 is omitted from the query to verify it's + // not returned. + got, err := d.GetOperationConfigsByRepoNames([]string{"repo-1", "repo-3"}) + if err != nil { + t.Fatalf("GetOperationConfigsByRepoNames: %v", err) + } + if len(got) != 2 { + t.Fatalf("len = %d, want 2 (missing repos omitted — FR-BRIDGE-04)", len(got)) + } + names := map[string]bool{} + for _, r := range got { + names[r.RepoName] = true + } + if !names["repo-1"] || !names["repo-3"] { + t.Errorf("expected repo-1 and repo-3, got names=%v", names) + } + if names["repo-2"] { + t.Errorf("repo-2 was not requested but appeared in result") + } + // Ordered by repo_name ASC. + if got[0].RepoName != "repo-1" || got[1].RepoName != "repo-3" { + t.Errorf("result not ordered by repo_name ASC: %s, %s", got[0].RepoName, got[1].RepoName) + } +} + +func TestGetOperationConfigsByRepoNames_EmptyInput(t *testing.T) { + d := setupTestDB(t) + got, err := d.GetOperationConfigsByRepoNames([]string{}) + if err != nil { + t.Fatalf("empty input: %v", err) + } + if got == nil || len(got) != 0 { + t.Errorf("empty input should return non-nil empty slice, got len=%d nil=%v", len(got), got == nil) + } +} + +func TestDeleteOperationConfig(t *testing.T) { + d := setupTestDB(t) + if err := d.SaveOperationConfig(sampleRow("repo-del")); err != nil { + t.Fatalf("SaveOperationConfig: %v", err) + } + if err := d.DeleteOperationConfig("repo-del"); err != nil { + t.Fatalf("DeleteOperationConfig: %v", err) + } + got, err := d.GetOperationConfig("repo-del") + if err != nil { + t.Fatalf("GetOperationConfig after delete: %v", err) + } + // After delete, Get returns zero-value (no row) — not an error. + if got.CiPlatform != "" { + t.Errorf("after delete, CiPlatform = %q, want empty (zero-value)", got.CiPlatform) + } + if string(got.Observability) != "{}" { + t.Errorf("after delete, Observability = %s, want {} (zero-value DR-R6)", got.Observability) + } +} + +func TestDeleteOperationConfig_Missing(t *testing.T) { + d := setupTestDB(t) + // Deleting a non-existent row is a no-op, not an error. + if err := d.DeleteOperationConfig("never-existed"); err != nil { + t.Errorf("deleting non-existent row should be a no-op, got error: %v", err) + } +} + +func TestErrorWrapping(t *testing.T) { + d := setupTestDB(t) + // Trigger a DB error by closing the connection then querying. + d.Close() + _, err := d.GetOperationConfig("repo-wrap") + if err == nil { + t.Fatal("expected error after DB close, got nil") + } + // FR-STORE-04: the error message must contain the repo name so the + // operator can identify which repo's config failed. + if !strings.Contains(err.Error(), "repo-wrap") { + t.Errorf("error message %q does not contain the repo name (FR-STORE-04)", err.Error()) + } +} diff --git a/internal/intake/testhelpers_test.go b/internal/intake/testhelpers_test.go index ebfc436..1570c2e 100644 --- a/internal/intake/testhelpers_test.go +++ b/internal/intake/testhelpers_test.go @@ -28,6 +28,7 @@ func truncateAllTables(database *db.DB) { "spec_artifacts", "outcomes", "notes", "events", "questions", "rules", "team_knowledge", "feature_repos", "sessions", "phase_states", "gate_results", "recirculations", "features", + "repo_operation_config", } for _, table := range tables { database.Conn().Exec("TRUNCATE TABLE " + table + " CASCADE") diff --git a/internal/pipeline/testhelpers_test.go b/internal/pipeline/testhelpers_test.go index 6c20ec2..40a2a5d 100644 --- a/internal/pipeline/testhelpers_test.go +++ b/internal/pipeline/testhelpers_test.go @@ -31,6 +31,7 @@ func truncateAllTables(database *db.DB) { "rules", "team_knowledge", "feature_repos", "sessions", "phase_states", "gate_results", "recirculations", "features", "stage_logs", + "repo_operation_config", } for _, table := range tables { database.Conn().Exec("TRUNCATE TABLE " + table + " CASCADE") diff --git a/internal/spec/testhelpers_test.go b/internal/spec/testhelpers_test.go index 94c4cd5..a1e13ff 100644 --- a/internal/spec/testhelpers_test.go +++ b/internal/spec/testhelpers_test.go @@ -30,6 +30,7 @@ func truncateAllTables(database *db.DB) { "spec_artifacts", "outcomes", "notes", "events", "questions", "rules", "team_knowledge", "feature_repos", "sessions", "phase_states", "gate_results", "recirculations", "features", + "repo_operation_config", } for _, table := range tables { database.Conn().Exec("TRUNCATE TABLE " + table + " CASCADE")