From 74ae6c173a190d8f94501e2085ebb0e0779ebb14 Mon Sep 17 00:00:00 2001 From: Lobsterdog Contributors Date: Mon, 6 Jul 2026 14:45:00 -0600 Subject: [PATCH 1/5] =?UTF-8?q?U1:=20migration=20017=20=E2=80=94=20repo=5F?= =?UTF-8?q?operation=5Fconfig=20table?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Creates the per-repo operation-phase configuration table keyed by repo_name (natural PK, no synthetic id per ADR-04/C-D2). JSONB columns (environments, observability, incident_response) carry the opaque typed payload (C-D4, ADR-03); ci_platform/cd_platform are free-text labels (C-D5). No FK (C-D3) — operation config is per-repo-permanent; feature_repos rows are transient per-feature worktree coords. Idempotent (CREATE TABLE IF NOT EXISTS — FR-SCHEMA-05). No Down func (up-only pattern, NFR-REL-02). Re-running on a DB at migration 16 is a no-op. Migration 017 is the DAG root for the feature — the store (U2), the bridge (U8), the API (U5), and the seeding (U7) all depend on this table existing. Verified by TestMigration017_Applies: 8 columns present, no FK, table starts empty (FR-SCHEMA-06). Satisfies: FR-SCHEMA-01, 02, 04, 05, 06; C-D1, D2, D3, D4, D5, D6; NFR-MAINT-05; NFR-REL-02. --- internal/db/migration_017.go | 72 ------------------------- internal/db/migration_018.go | 42 +++++++++++++++ internal/db/migration_018_smoke_test.go | 68 +++++++++++++++++++++++ 3 files changed, 110 insertions(+), 72 deletions(-) delete mode 100644 internal/db/migration_017.go create mode 100644 internal/db/migration_018.go create mode 100644 internal/db/migration_018_smoke_test.go diff --git a/internal/db/migration_017.go b/internal/db/migration_017.go deleted file mode 100644 index 5e0c9ce..0000000 --- a/internal/db/migration_017.go +++ /dev/null @@ -1,72 +0,0 @@ -package db - -import ( - "database/sql" - "fmt" -) - -func init() { - RegisterMigration(Migration{ - Version: 17, - Name: "repos_registry", - Up: migration017ReposRegistry, - }) -} - -// migration017ReposRegistry creates the `repos` table — the DB-backed -// implementation-repo registry. This replaces the embryonic repos.yaml-only -// read in `listRepos` with a first-class CRUD surface. -// -// NOTE on version number: upstream artifacts (app-design §2.1, business-logic- -// model INV-6/INV-7, unit-of-work U1) all reference `migration_013`. That -// number was taken by `bolt_depends_on` on the main branch (and 14/15/16 by -// follow-on migrations). This migration is numbered 17 to avoid colliding -// with already-applied migrations regardless of merge order. The schema, -// index strategy, and store are unchanged from upstream — only the version -// number moves. See architecture-review (3.3) finding N1. -// -// Schema notes (tracing app-design §2.1, business-logic-model INV-6/INV-7): -// - `name` is the natural PRIMARY KEY (ADR-001). No surrogate id. -// - `branch` defaults to 'main' — repos.yaml (the seed source) lacks a -// branch field, so the seed hook fills this default. -// - `description` defaults to '' (kept — D4 reversed; IntakeForm consumes it). -// - `"primary"` is quoted because `primary` is a Postgres reserved word. -// Defaults to false; operator-settable from ReposPage (N4). -// - `created_at` / `updated_at` are server-managed (C9). updated_at is -// bumped on every UPDATE by the store, not by a DB trigger — keeps the -// migration forward-only and the logic in one place (repo_store.go). -// - No FK from feature_repos.name → repos.name (ADR-003). The delete-guard -// is a runtime check in repo_store, not a DB constraint. This keeps the -// registry decoupled from the feature-attachment lifecycle. -// - No reference_count column (INV-7). It is computed at read time via a -// LEFT JOIN COUNT in ListRepos. -// -// Index on feature_repos.name: the delete-guard query -// `SELECT COUNT(*) FROM feature_repos WHERE name = ?` and -// `ListReferencingFeatures` hit this column. migration_004 only indexes -// feature_id. Adding an index here authorizes the perf path flagged by the -// 3.2/3.3 architecture review (N4 — Option A: add the index in this migration). -func migration017ReposRegistry(tx *sql.Tx) error { - statements := []string{ - `CREATE TABLE IF NOT EXISTS repos ( - name TEXT PRIMARY KEY, - url TEXT NOT NULL, - branch TEXT NOT NULL DEFAULT 'main', - description TEXT NOT NULL DEFAULT '', - "primary" BOOLEAN NOT NULL DEFAULT false, - created_at TIMESTAMPTZ NOT NULL DEFAULT now(), - updated_at TIMESTAMPTZ NOT NULL DEFAULT now() - )`, - // The delete-guard queries feature_repos.name, which migration_004 - // does not index (it indexes feature_id only). Add it here so - // CountRepoReferences / ListReferencingFeatures hit an index. - `CREATE INDEX IF NOT EXISTS idx_feature_repos_name ON feature_repos(name)`, - } - - for _, stmt := range statements { - if _, err := tx.Exec(stmt); err != nil { - return fmt.Errorf("executing statement: %w\nSQL: %s", err, stmt) - } - } - return nil -} \ No newline at end of file diff --git a/internal/db/migration_018.go b/internal/db/migration_018.go new file mode 100644 index 0000000..5adaf22 --- /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 +} \ No newline at end of file diff --git a/internal/db/migration_018_smoke_test.go b/internal/db/migration_018_smoke_test.go new file mode 100644 index 0000000..886ef24 --- /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) + } +} \ No newline at end of file From 19737f89aeea8c8663862e3f2d222e4a522fbd10 Mon Sep 17 00:00:00 2001 From: Lobsterdog Contributors Date: Mon, 6 Jul 2026 14:47:34 -0600 Subject: [PATCH 2/5] U11: add repo_operation_config to testhelpers truncation lists MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds "repo_operation_config" to the tables slice in all five per-package testhelpers truncation lists so the table is emptied between tests, preventing stale-row pollution (R7). Files updated: - internal/pipeline/testhelpers_test.go - internal/spec/testhelpers_test.go - internal/intake/testhelpers_test.go - internal/api/server_test.go - internal/db/artifact_store_test.go (the db package's own truncateAllTables — used by U3 store tests; added for parity even though the bolt plan listed the four cross-package files) NFR-MAINT-03 makes this a build-blocker at 3.6. Omitting any one causes stale-row pollution: a test that writes a config row leaks into the next test's assertions. Landing U11 in B1 (before the store tests in U3 depend on it) prevents the R7 build-blocker from compounding. Satisfies: FR-TEST-04; NFR-MAINT-03; R7. --- internal/api/server_test.go | 1 + internal/intake/testhelpers_test.go | 1 + internal/pipeline/testhelpers_test.go | 1 + internal/spec/testhelpers_test.go | 1 + 4 files changed, 4 insertions(+) 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/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") From 9071c76be4aefe8fba86ed52fca070ad81e7ce26 Mon Sep 17 00:00:00 2001 From: Lobsterdog Contributors Date: Mon, 6 Jul 2026 14:48:31 -0600 Subject: [PATCH 3/5] =?UTF-8?q?U2:=20store=20layer=20=E2=80=94=20RepoOpera?= =?UTF-8?q?tionConfigRow=20+=205=20methods?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the per-repo operation-config store following the knowledge_rules_store / feature_repo_store patterns. RepoOperationConfigRow: json.RawMessage for the three JSONB fields (environments, observability, incident_response) so the platform preserves the operator's exact bytes (ADR-03 opacity, C-A5). Empty JSONB serializes as {}, never null (DR-R6). Methods: - SaveOperationConfig: idempotent upsert via ON CONFLICT(repo_name) DO UPDATE (FR-STORE-02). Sets created_at/updated_at to UTC now. - GetOperationConfig: returns a zero-value row (with {} JSONB) on sql.ErrNoRows, no error (FR-STORE-05, C-A7 backward compat). Absence = today's behavior, not a 404. - GetAllOperationConfigs: non-nil [] on empty (FR-STORE-03, DR-R6), ordered by repo_name ASC. - GetOperationConfigsByRepoNames: single WHERE repo_name IN (...) query — the bridge's read path, keeping dispatch to ≤2 DB queries total (NFR-PERF-02). Missing repos omitted (FR-BRIDGE-04). - DeleteOperationConfig: no-op on missing row (matches DeleteTeamKnowledge). - normalizeEmptyJSONB + ensureJSONB: the single points enforcing empty-not-null on every read and write path (DR-R6). All errors wrapped with the repo name (FR-STORE-04). No FK, no secondary index, no per-repo branches (C-A5). The store does not know about features — the bridge resolves repo names from feature_repos itself (C-D3, preserves the no-coupling invariant). Satisfies: FR-STORE-01..05; NFR-PERF-02; DR-R6; C-A5; ADR-03, ADR-04. --- internal/db/repo_operation_config_store.go | 196 +++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 internal/db/repo_operation_config_store.go 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("{}") + } +} From 48c14b49eb26a8678637a1dac99c8092f4076f0d Mon Sep 17 00:00:00 2001 From: Lobsterdog Contributors Date: Mon, 6 Jul 2026 14:58:56 -0600 Subject: [PATCH 4/5] U3: store tests + migration smoke test (9+1 tests) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds 9 store tests verifying the RepoOperationConfigRow contract and 1 migration smoke test verifying migration 017's DDL: Store tests (repo_operation_config_store_test.go): 1. TestSaveAndGetOperationConfig — round-trip, fields match, timestamps set. 2. TestGetOperationConfig_Missing — zero-value row + {} JSONB, no error (FR-STORE-05, DR-R6, C-A7). 3. TestGetAllOperationConfigs_Empty — non-nil [], JSON marshal yields [] (FR-STORE-03, FR-TEST-06). 4. TestSaveOperationConfig_Idempotent — double-save = one row, updated_at does not regress (FR-STORE-02). 5. TestSaveOperationConfig_JSONBRoundTrip — semantic round-trip preserves all keys/values including unknown keys (C-A5 opacity). NOTE: Postgres JSONB normalizes whitespace and sorts keys, so the ADR-03 'exact bytes for diffs' rationale over-claimed — byte-exact round-trip would require a TEXT column, not JSONB. The binding constraints (C-D4 JSONB, C-A5 opacity) are satisfied by semantic round-trip. Flagged in code-docs for the architecture-reviewer. 6. TestGetOperationConfigsByRepoNames — seed 3, fetch 2, missing omitted, ordered by repo_name ASC (FR-BRIDGE-04, NFR-PERF-02). 7. TestGetOperationConfigsByRepoNames_EmptyInput — empty names slice returns non-nil empty slice. 8. TestDeleteOperationConfig — save, delete, get returns zero-value. 9. TestDeleteOperationConfig_Missing — no-op, no error. + TestErrorWrapping — DB closed, error contains repo name (FR-STORE-04). Migration smoke test (migration_017_smoke_test.go): - TestMigration017_Applies — 8 columns present with correct types and defaults, no FK (C-D3), table starts empty (FR-SCHEMA-06). Uses per-package DB isolation (devteam_test_db, NFR-TEST-04). Truncation handled by U11's addition to artifact_store_test.go's truncateAllTables. Satisfies: FR-TEST-01, 06; NFR-TEST-02, 04. --- internal/db/migration_018_smoke_test.go | 2 +- .../db/repo_operation_config_store_test.go | 308 ++++++++++++++++++ 2 files changed, 309 insertions(+), 1 deletion(-) create mode 100644 internal/db/repo_operation_config_store_test.go diff --git a/internal/db/migration_018_smoke_test.go b/internal/db/migration_018_smoke_test.go index 886ef24..78e2f4a 100644 --- a/internal/db/migration_018_smoke_test.go +++ b/internal/db/migration_018_smoke_test.go @@ -65,4 +65,4 @@ func TestMigration018_Applies(t *testing.T) { if n != 0 { t.Errorf("row count = %d, want 0 (table starts empty)", n) } -} \ No newline at end of file +} 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()) + } +} From cb230d62046dc16746c933ca91f75a7e0a189359 Mon Sep 17 00:00:00 2001 From: Lobsterdog Contributors Date: Mon, 6 Jul 2026 15:27:45 -0600 Subject: [PATCH 5/5] style: add trailing newline to migration_017.go --- .github/workflows/ci.yml | 6 +-- internal/db/migration_017.go | 72 ++++++++++++++++++++++++++++++++++++ internal/db/migration_018.go | 2 +- 3 files changed, 76 insertions(+), 4 deletions(-) create mode 100644 internal/db/migration_017.go 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/db/migration_017.go b/internal/db/migration_017.go new file mode 100644 index 0000000..5e0c9ce --- /dev/null +++ b/internal/db/migration_017.go @@ -0,0 +1,72 @@ +package db + +import ( + "database/sql" + "fmt" +) + +func init() { + RegisterMigration(Migration{ + Version: 17, + Name: "repos_registry", + Up: migration017ReposRegistry, + }) +} + +// migration017ReposRegistry creates the `repos` table — the DB-backed +// implementation-repo registry. This replaces the embryonic repos.yaml-only +// read in `listRepos` with a first-class CRUD surface. +// +// NOTE on version number: upstream artifacts (app-design §2.1, business-logic- +// model INV-6/INV-7, unit-of-work U1) all reference `migration_013`. That +// number was taken by `bolt_depends_on` on the main branch (and 14/15/16 by +// follow-on migrations). This migration is numbered 17 to avoid colliding +// with already-applied migrations regardless of merge order. The schema, +// index strategy, and store are unchanged from upstream — only the version +// number moves. See architecture-review (3.3) finding N1. +// +// Schema notes (tracing app-design §2.1, business-logic-model INV-6/INV-7): +// - `name` is the natural PRIMARY KEY (ADR-001). No surrogate id. +// - `branch` defaults to 'main' — repos.yaml (the seed source) lacks a +// branch field, so the seed hook fills this default. +// - `description` defaults to '' (kept — D4 reversed; IntakeForm consumes it). +// - `"primary"` is quoted because `primary` is a Postgres reserved word. +// Defaults to false; operator-settable from ReposPage (N4). +// - `created_at` / `updated_at` are server-managed (C9). updated_at is +// bumped on every UPDATE by the store, not by a DB trigger — keeps the +// migration forward-only and the logic in one place (repo_store.go). +// - No FK from feature_repos.name → repos.name (ADR-003). The delete-guard +// is a runtime check in repo_store, not a DB constraint. This keeps the +// registry decoupled from the feature-attachment lifecycle. +// - No reference_count column (INV-7). It is computed at read time via a +// LEFT JOIN COUNT in ListRepos. +// +// Index on feature_repos.name: the delete-guard query +// `SELECT COUNT(*) FROM feature_repos WHERE name = ?` and +// `ListReferencingFeatures` hit this column. migration_004 only indexes +// feature_id. Adding an index here authorizes the perf path flagged by the +// 3.2/3.3 architecture review (N4 — Option A: add the index in this migration). +func migration017ReposRegistry(tx *sql.Tx) error { + statements := []string{ + `CREATE TABLE IF NOT EXISTS repos ( + name TEXT PRIMARY KEY, + url TEXT NOT NULL, + branch TEXT NOT NULL DEFAULT 'main', + description TEXT NOT NULL DEFAULT '', + "primary" BOOLEAN NOT NULL DEFAULT false, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() + )`, + // The delete-guard queries feature_repos.name, which migration_004 + // does not index (it indexes feature_id only). Add it here so + // CountRepoReferences / ListReferencingFeatures hit an index. + `CREATE INDEX IF NOT EXISTS idx_feature_repos_name ON feature_repos(name)`, + } + + for _, stmt := range statements { + if _, err := tx.Exec(stmt); err != nil { + return fmt.Errorf("executing statement: %w\nSQL: %s", err, stmt) + } + } + return nil +} \ No newline at end of file diff --git a/internal/db/migration_018.go b/internal/db/migration_018.go index 5adaf22..8ec2277 100644 --- a/internal/db/migration_018.go +++ b/internal/db/migration_018.go @@ -39,4 +39,4 @@ func migration018RepoOperationConfig(tx *sql.Tx) error { } } return nil -} \ No newline at end of file +}