From ac23c862cc4cf4c1c0c484f7bc64688a9fc326bc Mon Sep 17 00:00:00 2001 From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:40:43 +0100 Subject: [PATCH 1/3] fix(db): reconcile schema ownership and integrity across engines (WI-2366) Give each PostgreSQL table one authoritative bootstrap definition. The base_tables stub silently won board_configurations, test_folders, test_labels and iteration_types, dropping four cascading foreign keys and relaxing iteration_types; the domain files now own those tables and a migration reconciles orphans and restores the keys. Make configuration_set_item_types the item-type membership source. Workflow resolution goes through the workspace's effective set, and the scalar item_types.configuration_set_id is dropped after backfilling only custom types, preserving the seed's deliberate exclusion of Initiative. Align agent-binding creator deletion: SQLite now allows the creator to be nulled, matching PostgreSQL and the soft-audit model, and the repository reader handles NULL. Enforce exactly one owner and at most one configuration per board owner, reconciling duplicates without losing board columns. Make agent-binding repository replacement atomic with the parent version bump. Cleanup: drop the stale SQLite request_types DDL, the duplicate time-category junction, the unused milestone bootstrap files, duplicate items foreign keys on fresh installs, and the redundant two-column PostgreSQL notification-setting uniqueness. --- internal/database/default_data_seed.go | 7 +- internal/database/migrations.go | 391 +++++++++++++++++- internal/database/schema/agents.sql | 2 +- .../database/schema/base_tables_postgres.sql | 163 +------- internal/database/schema/config_workflows.sql | 4 +- .../schema/config_workflows_postgres.sql | 1 - internal/database/schema/integrations.sql | 8 +- .../database/schema/integrations_postgres.sql | 8 +- internal/database/schema/items.sql | 9 +- internal/database/schema/milestones.sql | 3 +- .../database/schema/milestones_existing.sql | 80 ---- .../schema/milestones_existing_postgres.sql | 78 ---- .../database/schema/milestones_postgres.sql | 4 +- internal/database/schema/notifications.sql | 5 +- .../schema/notifications_postgres.sql | 7 +- internal/database/schema/system.sql | 29 +- internal/database/schema/system_postgres.sql | 12 +- internal/database/schema/time_tracking.sql | 14 +- internal/models/workspace_agent_binding.go | 5 +- .../board_configuration_repository.go | 3 + .../workspace_agent_binding_repository.go | 65 +-- internal/services/agent_profile_service.go | 2 +- internal/services/binding_service.go | 2 +- internal/services/items.go | 41 +- internal/services/submission.go | 2 +- 25 files changed, 532 insertions(+), 413 deletions(-) delete mode 100644 internal/database/schema/milestones_existing.sql delete mode 100644 internal/database/schema/milestones_existing_postgres.sql diff --git a/internal/database/default_data_seed.go b/internal/database/default_data_seed.go index ec5c89e7f..9756b8ff8 100644 --- a/internal/database/default_data_seed.go +++ b/internal/database/default_data_seed.go @@ -232,11 +232,12 @@ func seedDefaultData(w seedWriter) error { } } - // 11. Item types. + // 11. Item types. Membership is recorded only in configuration_set_item_types + // (step 12); the deprecated item_types.configuration_set_id scalar is gone. for _, itemType := range defaultItemTypes { if _, err := w.Exec( - "INSERT INTO item_types (builtin_key, configuration_set_id, name, description, icon, color, hierarchy_level, sort_order, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", - itemType.builtinKey, configSetID, itemType.name, itemType.description, itemType.icon, itemType.color, itemType.hierarchyLevel, itemType.sortOrder, true, + "INSERT INTO item_types (builtin_key, name, description, icon, color, hierarchy_level, sort_order, is_default) VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + itemType.builtinKey, itemType.name, itemType.description, itemType.icon, itemType.color, itemType.hierarchyLevel, itemType.sortOrder, true, ); err != nil { return fmt.Errorf("failed to create default item type %s: %w", itemType.name, err) } diff --git a/internal/database/migrations.go b/internal/database/migrations.go index 2ce3b769c..fddaa590a 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3727,7 +3727,204 @@ END $$; CREATE UNIQUE INDEX IF NOT EXISTS uq_priorities_single_default ON priorities(is_default) WHERE is_default = true; `, }, -} + { + // WI-2366: base_tables_postgres.sql declared these tables before their + // owning domain files, so CREATE TABLE IF NOT EXISTS silently discarded + // four cascading foreign keys and the stricter iteration_types shape on + // PostgreSQL. Reconcile rows whose parents are gone, restore the keys, + // and align iteration_types with the SQLite/Go definition. + Version: "20261205_postgres_schema_authority", + Name: "Restore dropped PostgreSQL cascades and align iteration_types (WI-2366)", + CheckPostgres: `SELECT CASE WHEN + NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='iteration_types' AND column_name='duration_days') + AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='iteration_types' AND column_name='color' AND is_nullable='NO') + AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_workspace_id_fkey') + AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_collection_id_fkey') + AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='test_folders'::regclass AND conname='test_folders_workspace_id_fkey') + AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='test_labels'::regclass AND conname='test_labels_workspace_id_fkey') + THEN 1 ELSE 0 END`, + Postgres: ` + DELETE FROM board_configurations bc + WHERE (bc.workspace_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM workspaces w WHERE w.id = bc.workspace_id)) + OR (bc.collection_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM collections c WHERE c.id = bc.collection_id)); + + DELETE FROM test_folders tf + WHERE NOT EXISTS (SELECT 1 FROM workspaces w WHERE w.id = tf.workspace_id); + + DELETE FROM test_labels tl + WHERE NOT EXISTS (SELECT 1 FROM workspaces w WHERE w.id = tl.workspace_id); + + DO $$ + BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_workspace_id_fkey') THEN + ALTER TABLE board_configurations ADD CONSTRAINT board_configurations_workspace_id_fkey FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE; + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_collection_id_fkey') THEN + ALTER TABLE board_configurations ADD CONSTRAINT board_configurations_collection_id_fkey FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE; + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='test_folders'::regclass AND conname='test_folders_workspace_id_fkey') THEN + ALTER TABLE test_folders ADD CONSTRAINT test_folders_workspace_id_fkey FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE; + END IF; + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='test_labels'::regclass AND conname='test_labels_workspace_id_fkey') THEN + ALTER TABLE test_labels ADD CONSTRAINT test_labels_workspace_id_fkey FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE; + END IF; + END $$; + + UPDATE iteration_types SET color = '#6b7280' WHERE color IS NULL; + ALTER TABLE iteration_types ALTER COLUMN color SET NOT NULL; + ALTER TABLE iteration_types DROP COLUMN IF EXISTS duration_days; + `, + }, + { + // WI-2366: SQLite declared workspace_agent_bindings.created_by_user_id + // NOT NULL while its foreign key was ON DELETE SET NULL, so deleting a + // distinct creator failed on SQLite but succeeded (leaving NULL) on + // PostgreSQL. The creator is a soft audit ref, matching + // workspace_agent_skills and runner_registration_tokens: the binding + // survives and the reference becomes NULL. SQLite cannot drop NOT NULL + // in place, so ApplySQLite rebuilds the table. + Version: "20261206_agent_binding_creator_nullable", + Name: "Let an agent binding outlive its creator on SQLite (WI-2366)", + CheckSQLite: `SELECT CASE WHEN (SELECT "notnull" FROM pragma_table_info('workspace_agent_bindings') WHERE name='created_by_user_id') = 0 THEN 1 ELSE 0 END`, + CheckPostgres: `SELECT CASE WHEN (SELECT is_nullable FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='workspace_agent_bindings' AND column_name='created_by_user_id') = 'YES' THEN 1 ELSE 0 END`, + SQLite: "agent-binding-creator-nullable:v1", + ApplySQLite: applySQLiteBindingCreatorNullable, + Postgres: `ALTER TABLE workspace_agent_bindings ALTER COLUMN created_by_user_id DROP NOT NULL;`, + }, + { + // WI-2366: a board configuration belongs to exactly one workspace or + // collection, but neither engine enforced that, so an ownerless row or + // two rows for one owner made the single-row owner lookup + // nondeterministic. Merge duplicates by moving their columns onto the + // surviving configuration, drop unreachable ownerless rows, then add the + // exactly-one-owner check and one unique key per owner. + Version: "20261207_board_configuration_ownership", + Name: "Enforce one owner and one configuration per board owner (WI-2366)", + CheckSQLite: `SELECT CASE WHEN (SELECT COUNT(*) FROM sqlite_master WHERE type='index' AND name IN ('uq_board_configurations_workspace','uq_board_configurations_collection')) = 2 THEN 1 ELSE 0 END`, + CheckPostgres: `SELECT CASE WHEN (SELECT COUNT(*) FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE c.relkind='i' AND c.relname IN ('uq_board_configurations_workspace','uq_board_configurations_collection') AND n.nspname=current_schema()) = 2 THEN 1 ELSE 0 END`, + SQLite: "board-configuration-ownership:v1", + ApplySQLite: applySQLiteBoardConfigurationOwnership, + Postgres: boardConfigurationOwnershipPostgres, + }, + { + // WI-2366: item type membership lived in two places. The junction + // configuration_set_item_types carries per-set workflow overrides and is + // the intended source of truth; item_types.configuration_set_id was a + // scalar mirror. Backfill the junction only for custom (non-built-in) + // scalar-only rows: built-in membership is defined by the seed, which + // deliberately leaves Initiative out of the simplified default set, so a + // blind backfill would change that. Then drop the scalar and its index. + Version: "20261208_item_type_membership_authority", + Name: "Make configuration_set_item_types the item-type membership source (WI-2366)", + CheckSQLite: `SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM pragma_table_info('item_types') WHERE name='configuration_set_id') THEN 1 ELSE 0 END`, + CheckPostgres: `SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='item_types' AND column_name='configuration_set_id') THEN 1 ELSE 0 END`, + SQLite: ` + INSERT INTO configuration_set_item_types (configuration_set_id, item_type_id) + SELECT it.configuration_set_id, it.id + FROM item_types it + WHERE it.configuration_set_id IS NOT NULL + AND it.builtin_key IS NULL + AND NOT EXISTS ( + SELECT 1 FROM configuration_set_item_types csit + WHERE csit.configuration_set_id = it.configuration_set_id AND csit.item_type_id = it.id + ); + DROP INDEX IF EXISTS idx_item_types_configuration_set_id; + ALTER TABLE item_types DROP COLUMN configuration_set_id; + `, + Postgres: ` + INSERT INTO configuration_set_item_types (configuration_set_id, item_type_id) + SELECT it.configuration_set_id, it.id + FROM item_types it + WHERE it.configuration_set_id IS NOT NULL + AND it.builtin_key IS NULL + AND NOT EXISTS ( + SELECT 1 FROM configuration_set_item_types csit + WHERE csit.configuration_set_id = it.configuration_set_id AND csit.item_type_id = it.id + ); + DROP INDEX IF EXISTS idx_item_types_configuration_set_id; + ALTER TABLE item_types DROP COLUMN configuration_set_id; + `, + }, + { + // WI-2366: PostgreSQL declared both UNIQUE(configuration_set_id, + // notification_setting_id) and a single-column unique index on + // configuration_set_id. The single-column key is the upsert target and + // already rejects everything the two-column rule does. Collapse duplicate + // sets first (the two-column rule allowed them), then drop the constraint. + Version: "20261209_notification_setting_unique", + Name: "Drop the redundant two-column notification-setting uniqueness (WI-2366)", + CheckPostgres: `SELECT CASE WHEN + EXISTS (SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace WHERE c.relkind='i' AND c.relname='uq_config_set_notification_setting_one_per_set' AND n.nspname=current_schema()) + AND NOT EXISTS ( + SELECT 1 FROM pg_constraint c + WHERE c.conrelid='configuration_set_notification_settings'::regclass AND c.contype='u' + AND (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord) JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=k.attnum) = ARRAY['configuration_set_id','notification_setting_id'] + ) + THEN 1 ELSE 0 END`, + Postgres: ` + DELETE FROM configuration_set_notification_settings + WHERE id NOT IN ( + SELECT MIN(id) FROM configuration_set_notification_settings GROUP BY configuration_set_id + ); + CREATE UNIQUE INDEX IF NOT EXISTS uq_config_set_notification_setting_one_per_set + ON configuration_set_notification_settings(configuration_set_id); + DO $$ + DECLARE cname text; + BEGIN + SELECT c.conname INTO cname + FROM pg_constraint c + WHERE c.conrelid='configuration_set_notification_settings'::regclass AND c.contype='u' + AND (SELECT array_agg(a.attname::text ORDER BY k.ord) FROM unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord) JOIN pg_attribute a ON a.attrelid=c.conrelid AND a.attnum=k.attnum) = ARRAY['configuration_set_id','notification_setting_id'] + LIMIT 1; + IF cname IS NOT NULL THEN + EXECUTE format('ALTER TABLE configuration_set_notification_settings DROP CONSTRAINT %I', cname); + END IF; + END $$; + `, + }} + +// boardConfigurationReconcileSQL merges duplicate board configurations onto the +// lowest-id survivor and deletes unreachable ownerless rows. Moving a +// duplicate's board_columns first keeps them; a plain delete would cascade +// them away with the configuration. +const boardConfigurationReconcileSQL = ` +UPDATE board_columns +SET board_configuration_id = ( + SELECT MIN(survivor.id) + FROM board_configurations dup + JOIN board_configurations survivor + ON (dup.workspace_id IS NOT NULL AND survivor.workspace_id = dup.workspace_id) + OR (dup.collection_id IS NOT NULL AND survivor.collection_id = dup.collection_id) + WHERE dup.id = board_columns.board_configuration_id +) +WHERE board_configuration_id IN ( + SELECT dup.id FROM board_configurations dup + WHERE (dup.workspace_id IS NOT NULL AND dup.id <> (SELECT MIN(s.id) FROM board_configurations s WHERE s.workspace_id = dup.workspace_id)) + OR (dup.collection_id IS NOT NULL AND dup.id <> (SELECT MIN(s.id) FROM board_configurations s WHERE s.collection_id = dup.collection_id)) +); + +DELETE FROM board_configurations +WHERE (workspace_id IS NOT NULL AND id <> (SELECT MIN(s.id) FROM board_configurations s WHERE s.workspace_id = board_configurations.workspace_id)) + OR (collection_id IS NOT NULL AND id <> (SELECT MIN(s.id) FROM board_configurations s WHERE s.collection_id = board_configurations.collection_id)) + OR (workspace_id IS NULL AND collection_id IS NULL); +` + +const boardConfigurationOwnershipPostgres = boardConfigurationReconcileSQL + ` +DO $$ +BEGIN + IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_exactly_one_owner') THEN + ALTER TABLE board_configurations ADD CONSTRAINT board_configurations_exactly_one_owner CHECK ( + (workspace_id IS NOT NULL AND collection_id IS NULL) OR + (workspace_id IS NULL AND collection_id IS NOT NULL) + ); + END IF; +END $$; + +DROP INDEX IF EXISTS idx_board_configurations_workspace_id; +DROP INDEX IF EXISTS idx_board_configurations_collection_id; +CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_workspace ON board_configurations(workspace_id) WHERE workspace_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_collection ON board_configurations(collection_id) WHERE collection_id IS NOT NULL; +` // domainEventClaimableIndexMigration adds the partial index the claim query // orders by, and makes next_attempt_at the single eligibility time for leased @@ -6191,3 +6388,195 @@ func applySQLiteActiveTimerNullableProject(db Database) (retErr error) { } return nil } + +// applySQLiteBindingCreatorNullable rebuilds workspace_agent_bindings so +// created_by_user_id accepts NULL. The column's ON DELETE SET NULL foreign key +// and a NOT NULL declaration cannot both hold, so a creator deletion either +// failed or nulled the row depending on the engine. SQLite cannot drop the NOT +// NULL in place; copy the rows into a fresh table and swap it in, recreating +// every index. +func applySQLiteBindingCreatorNullable(db Database) (retErr error) { + sqliteDB, ok := db.(*SQLiteDB) + if !ok { + return fmt.Errorf("expected SQLite database, got %T", db) + } + + ctx := context.Background() + conn, err := sqliteDB.writeConn.Conn(ctx) + if err != nil { + return fmt.Errorf("acquire SQLite write connection: %w", err) + } + defer func() { _ = conn.Close() }() + + var foreignKeysEnabled bool + if err := conn.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&foreignKeysEnabled); err != nil { + return fmt.Errorf("read foreign_keys pragma: %w", err) + } + if foreignKeysEnabled { + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=OFF"); err != nil { + return fmt.Errorf("disable foreign keys: %w", err) + } + defer func() { + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=ON"); retErr == nil && err != nil { + retErr = fmt.Errorf("restore foreign keys: %w", err) + } + }() + } + + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin workspace_agent_bindings rebuild: %w", err) + } + defer func() { _ = tx.Rollback() }() + + statements := []string{ + `CREATE TABLE workspace_agent_bindings_migration ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + workspace_id INTEGER NOT NULL, + acting_user_id INTEGER NOT NULL, + acting_user_kind TEXT NOT NULL + CHECK (acting_user_kind IN ('agent','centralized_service')), + profile_type TEXT NOT NULL DEFAULT 'legacy' + CHECK (profile_type IN ('standard','coding','legacy')), + lifecycle TEXT NOT NULL DEFAULT 'ready' + CHECK (lifecycle IN ('draft','ready','paused','archived')), + profile_version INTEGER NOT NULL DEFAULT 1 CHECK (profile_version > 0), + identity_class TEXT NOT NULL DEFAULT 'centralized_service' + CHECK (identity_class IN ('user_owned','centralized_service','workspace_managed')), + purpose TEXT NOT NULL DEFAULT '', + capability_groups_json TEXT NOT NULL DEFAULT '[]', + archived_at DATETIME, + archived_by_user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + last_known_name TEXT NOT NULL DEFAULT '', + last_known_handle TEXT NOT NULL DEFAULT '', + last_known_avatar TEXT NOT NULL DEFAULT '', + repo_slug TEXT, + repo_base_ref TEXT, + llm_connection_id INTEGER, + token_scopes_json TEXT NOT NULL DEFAULT '[]', + token_ttl_minutes INTEGER NOT NULL DEFAULT 60, + max_runs_per_day INTEGER NOT NULL DEFAULT 0, + scm_connection_id INTEGER REFERENCES workspace_scm_connections(id) ON DELETE SET NULL, + target_pool_id INTEGER, + instructions TEXT NOT NULL DEFAULT '', + runner_image TEXT, + created_by_user_id INTEGER, + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, + FOREIGN KEY (acting_user_id) REFERENCES users(id) ON DELETE CASCADE, + FOREIGN KEY (created_by_user_id) REFERENCES users(id) ON DELETE SET NULL + )`, + `INSERT INTO workspace_agent_bindings_migration ( + id, workspace_id, acting_user_id, acting_user_kind, profile_type, lifecycle, + profile_version, identity_class, purpose, capability_groups_json, archived_at, + archived_by_user_id, last_known_name, last_known_handle, last_known_avatar, + repo_slug, repo_base_ref, llm_connection_id, token_scopes_json, token_ttl_minutes, + max_runs_per_day, scm_connection_id, target_pool_id, instructions, runner_image, + created_by_user_id, created_at, updated_at) + SELECT id, workspace_id, acting_user_id, acting_user_kind, profile_type, lifecycle, + profile_version, identity_class, purpose, capability_groups_json, archived_at, + archived_by_user_id, last_known_name, last_known_handle, last_known_avatar, + repo_slug, repo_base_ref, llm_connection_id, token_scopes_json, token_ttl_minutes, + max_runs_per_day, scm_connection_id, target_pool_id, instructions, runner_image, + created_by_user_id, created_at, updated_at FROM workspace_agent_bindings`, + `DROP TABLE workspace_agent_bindings`, + `ALTER TABLE workspace_agent_bindings_migration RENAME TO workspace_agent_bindings`, + `CREATE UNIQUE INDEX IF NOT EXISTS idx_workspace_agent_bindings_workspace_acting ON workspace_agent_bindings(workspace_id, acting_user_id)`, + `CREATE INDEX IF NOT EXISTS idx_workspace_agent_bindings_workspace ON workspace_agent_bindings(workspace_id)`, + `CREATE INDEX IF NOT EXISTS idx_workspace_agent_bindings_workspace_lifecycle ON workspace_agent_bindings(workspace_id, lifecycle)`, + `CREATE INDEX IF NOT EXISTS idx_workspace_agent_bindings_scm_connection ON workspace_agent_bindings(scm_connection_id)`, + } + for _, statement := range statements { + if _, err := tx.ExecContext(ctx, statement); err != nil { + return fmt.Errorf("rebuild workspace_agent_bindings: %w", err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit workspace_agent_bindings rebuild: %w", err) + } + return nil +} + +// applySQLiteBoardConfigurationOwnership reconciles duplicate and ownerless +// board configurations, then rebuilds the table with the exactly-one-owner +// check the fresh schema declares. SQLite cannot add a CHECK constraint in +// place, so the rows are copied into a fresh table and swapped. +func applySQLiteBoardConfigurationOwnership(db Database) (retErr error) { + sqliteDB, ok := db.(*SQLiteDB) + if !ok { + return fmt.Errorf("expected SQLite database, got %T", db) + } + + ctx := context.Background() + conn, err := sqliteDB.writeConn.Conn(ctx) + if err != nil { + return fmt.Errorf("acquire SQLite write connection: %w", err) + } + defer func() { _ = conn.Close() }() + + var foreignKeysEnabled bool + if err := conn.QueryRowContext(ctx, "PRAGMA foreign_keys").Scan(&foreignKeysEnabled); err != nil { + return fmt.Errorf("read foreign_keys pragma: %w", err) + } + if foreignKeysEnabled { + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=OFF"); err != nil { + return fmt.Errorf("disable foreign keys: %w", err) + } + defer func() { + if _, err := conn.ExecContext(ctx, "PRAGMA foreign_keys=ON"); retErr == nil && err != nil { + retErr = fmt.Errorf("restore foreign keys: %w", err) + } + }() + } + + tx, err := conn.BeginTx(ctx, nil) + if err != nil { + return fmt.Errorf("begin board_configurations rebuild: %w", err) + } + defer func() { _ = tx.Rollback() }() + + statements := []string{ + boardConfigurationReconcileSQL, + `CREATE TABLE board_configurations_migration ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + workspace_id INTEGER, + collection_id INTEGER, + backlog_status_ids TEXT, + list_columns TEXT, + roadmap_config TEXT, + card_fields TEXT, + view_settings TEXT, + show_rightmost_column_last_50 BOOLEAN DEFAULT false, + completed_item_retention_days INTEGER, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, + FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE, + CONSTRAINT board_configurations_exactly_one_owner CHECK ( + (workspace_id IS NOT NULL AND collection_id IS NULL) OR + (workspace_id IS NULL AND collection_id IS NOT NULL) + ) + )`, + `INSERT INTO board_configurations_migration ( + id, workspace_id, collection_id, backlog_status_ids, list_columns, roadmap_config, + card_fields, view_settings, show_rightmost_column_last_50, completed_item_retention_days, + created_at, updated_at) + SELECT id, workspace_id, collection_id, backlog_status_ids, list_columns, roadmap_config, + card_fields, view_settings, show_rightmost_column_last_50, completed_item_retention_days, + created_at, updated_at FROM board_configurations`, + `DROP TABLE board_configurations`, + `ALTER TABLE board_configurations_migration RENAME TO board_configurations`, + `CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_workspace ON board_configurations(workspace_id) WHERE workspace_id IS NOT NULL`, + `CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_collection ON board_configurations(collection_id) WHERE collection_id IS NOT NULL`, + } + for _, statement := range statements { + if _, err := tx.ExecContext(ctx, statement); err != nil { + return fmt.Errorf("rebuild board_configurations: %w", err) + } + } + if err := tx.Commit(); err != nil { + return fmt.Errorf("commit board_configurations rebuild: %w", err) + } + return nil +} diff --git a/internal/database/schema/agents.sql b/internal/database/schema/agents.sql index 4d104b0f4..2f9f2af97 100644 --- a/internal/database/schema/agents.sql +++ b/internal/database/schema/agents.sql @@ -213,7 +213,7 @@ CREATE TABLE IF NOT EXISTS workspace_agent_bindings ( target_pool_id INTEGER, -- soft ref to action_capabilities (runner_pool); NULL = local in-process run (WI-195) instructions TEXT NOT NULL DEFAULT '', -- appended to the run's initial prompt as the agent's role/persona (WI-258) runner_image TEXT, -- custom coding-agent container image for remote (pool) runs; NULL = the runner's default windshift-agent image (WI-450) - created_by_user_id INTEGER NOT NULL, + created_by_user_id INTEGER, -- soft audit ref; NULL once the creator is deleted created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, diff --git a/internal/database/schema/base_tables_postgres.sql b/internal/database/schema/base_tables_postgres.sql index 013217899..f126647e7 100644 --- a/internal/database/schema/base_tables_postgres.sql +++ b/internal/database/schema/base_tables_postgres.sql @@ -231,8 +231,7 @@ CREATE TABLE IF NOT EXISTS priorities ( CREATE TABLE IF NOT EXISTS item_types ( id SERIAL PRIMARY KEY, builtin_key TEXT, - configuration_set_id INTEGER, -- Made nullable for many-to-many relationship - name TEXT NOT NULL UNIQUE, -- Changed to global unique (not per config set) + name TEXT NOT NULL UNIQUE, -- Global unique; set membership lives in configuration_set_item_types description TEXT, is_default BOOLEAN DEFAULT false, icon TEXT DEFAULT 'FileText', @@ -265,117 +264,23 @@ CREATE TABLE IF NOT EXISTS status_categories ( updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP ); --- From milestones_postgres.sql -CREATE TABLE IF NOT EXISTS milestone_categories ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - color TEXT NOT NULL, -- Hex color code (e.g., "#3b82f6") - description TEXT, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - --- From permissions_postgres.sql -CREATE TABLE IF NOT EXISTS permissions ( - id SERIAL PRIMARY KEY, - permission_key TEXT UNIQUE NOT NULL, - permission_name TEXT NOT NULL, - description TEXT, - scope TEXT NOT NULL CHECK (scope IN ('global', 'workspace')), - is_system BOOLEAN DEFAULT false, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); +-- Tables owned by a domain schema file are created there, not here. A +-- duplicate CREATE TABLE IF NOT EXISTS in this file would win the bootstrap +-- race (this file runs first) and silently discard the owner's foreign keys, +-- constraints and column shape. Keep base_tables limited to tables with no +-- foreign-key dependencies. -- workspace_roles is fully defined in permissions_postgres.sql (which runs -- after this file). The previous duplicate definition here was missing the -- permissions_enabled column, and CREATE TABLE IF NOT EXISTS would silently -- skip the proper definition once base_tables had already created the stub. --- From system_postgres.sql -CREATE TABLE IF NOT EXISTS system_settings ( - id SERIAL PRIMARY KEY, - key TEXT NOT NULL UNIQUE, - value TEXT, - value_type TEXT DEFAULT 'string', -- string, boolean, integer, json - description TEXT, - category TEXT DEFAULT 'general', - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX IF NOT EXISTS idx_system_settings_category ON system_settings(category); - -CREATE TABLE IF NOT EXISTS themes ( - id SERIAL PRIMARY KEY, - builtin_key TEXT, - name TEXT NOT NULL, - description TEXT, - is_default BOOLEAN DEFAULT false, - is_active BOOLEAN DEFAULT false, - nav_background_color_light TEXT NOT NULL DEFAULT '#ffffff', - nav_text_color_light TEXT NOT NULL DEFAULT '#374151', - nav_background_color_dark TEXT NOT NULL DEFAULT '#1f2937', - nav_text_color_dark TEXT NOT NULL DEFAULT '#f3f4f6', - logo_url TEXT, - logo_url_dark TEXT, - logo_full_url TEXT, - logo_full_url_dark TEXT, - brand_layout TEXT NOT NULL DEFAULT 'mark_text', - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -CREATE UNIQUE INDEX IF NOT EXISTS uq_themes_builtin_key ON themes(builtin_key) WHERE builtin_key IS NOT NULL; - -CREATE TABLE IF NOT EXISTS board_configurations ( - id SERIAL PRIMARY KEY, - workspace_id INTEGER, - collection_id INTEGER, - backlog_status_ids JSONB, - list_columns JSONB, - roadmap_config JSONB, - card_fields JSONB, - view_settings JSONB, - show_rightmost_column_last_50 BOOLEAN DEFAULT false, - completed_item_retention_days INTEGER, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - --- From content_postgres.sql -CREATE TABLE IF NOT EXISTS attachment_settings ( - id SERIAL PRIMARY KEY, - max_file_size INTEGER NOT NULL DEFAULT 52428800, -- 50MB default - allowed_mime_types TEXT, -- JSON array of allowed MIME types - attachment_path TEXT NOT NULL, - enabled BOOLEAN DEFAULT true, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS link_types ( - id SERIAL PRIMARY KEY, - builtin_key TEXT, - name TEXT NOT NULL UNIQUE, - description TEXT, - forward_label TEXT NOT NULL, - reverse_label TEXT NOT NULL, - color TEXT DEFAULT '#6b7280', - is_system BOOLEAN DEFAULT false, - active BOOLEAN DEFAULT true, - allowed_entity_types TEXT DEFAULT NULL, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -CREATE UNIQUE INDEX IF NOT EXISTS uq_link_types_builtin_key ON link_types(builtin_key) WHERE builtin_key IS NOT NULL; - -- Email templates: per-sender HTML/text/subject Go templates editable from the -- admin UI. `name` is the lookup key consumed by senders (e.g. "magic_link", --- "notification_batch"). The legacy template_type/event_type/template_body/ --- template_variables/channel_type columns are kept for backwards compatibility --- but are no longer read or written by application code. +-- "notification_batch"). template_type still selects rows for the notification +-- cache refresh, so it is not dead. The remaining legacy columns (event_type, +-- template_subject, template_body, template_variables, channel_type) are unread +-- but retained pending a deliberate audit of existing template rows. CREATE TABLE IF NOT EXISTS notification_templates ( id SERIAL PRIMARY KEY, name TEXT NOT NULL UNIQUE, @@ -386,7 +291,7 @@ CREATE TABLE IF NOT EXISTS notification_templates ( is_system BOOLEAN DEFAULT false, is_active BOOLEAN DEFAULT true, is_customized BOOLEAN NOT NULL DEFAULT false, -- true once an admin saves an edit; unmodified seeds fall back to the localized built-in default - template_type TEXT, -- legacy, unused + template_type TEXT, -- read by the notification cache refresh event_type TEXT, -- legacy, unused template_subject TEXT, -- legacy, unused template_body TEXT, -- legacy, unused @@ -412,52 +317,6 @@ CREATE TABLE IF NOT EXISTS notification_template_translations ( FOREIGN KEY (template_id) REFERENCES notification_templates(id) ON DELETE CASCADE ); --- From tests_postgres.sql (simplified for base tables - full definition with FKs in tests_postgres.sql) -CREATE TABLE IF NOT EXISTS test_folders ( - id SERIAL PRIMARY KEY, - workspace_id INTEGER NOT NULL, - parent_id INTEGER REFERENCES test_folders(id) ON DELETE SET NULL, - name TEXT NOT NULL, - description TEXT, - sort_order INTEGER DEFAULT 0, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -CREATE INDEX IF NOT EXISTS idx_test_folders_parent_id ON test_folders(parent_id); - -CREATE TABLE IF NOT EXISTS test_labels ( - id SERIAL PRIMARY KEY, - workspace_id INTEGER NOT NULL, - name TEXT NOT NULL, - color TEXT NOT NULL DEFAULT '#3B82F6', - description TEXT DEFAULT '', - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - UNIQUE(workspace_id, name) -); - --- From iterations_postgres.sql -CREATE TABLE IF NOT EXISTS iteration_types ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - color TEXT DEFAULT '#6b7280', - duration_days INTEGER NOT NULL DEFAULT 14, - description TEXT, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - --- From portal_postgres.sql -CREATE TABLE IF NOT EXISTS contact_roles ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - description TEXT, - is_system BOOLEAN DEFAULT false, - sort_order INTEGER NOT NULL DEFAULT 0, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -- ============================================ -- INDEXES -- ============================================ diff --git a/internal/database/schema/config_workflows.sql b/internal/database/schema/config_workflows.sql index 6a6ab49bd..7b182a2e0 100644 --- a/internal/database/schema/config_workflows.sql +++ b/internal/database/schema/config_workflows.sql @@ -16,8 +16,7 @@ CREATE TABLE IF NOT EXISTS configuration_sets ( CREATE TABLE IF NOT EXISTS item_types ( id INTEGER PRIMARY KEY AUTOINCREMENT, builtin_key TEXT, - configuration_set_id INTEGER, -- Made nullable for many-to-many relationship - name TEXT NOT NULL UNIQUE, -- Changed to global unique (not per config set) + name TEXT NOT NULL UNIQUE, -- Global unique; set membership lives in configuration_set_item_types description TEXT, is_default BOOLEAN DEFAULT false, icon TEXT DEFAULT 'FileText', @@ -127,7 +126,6 @@ CREATE TABLE IF NOT EXISTS screen_system_fields ( ); CREATE INDEX IF NOT EXISTS idx_configuration_sets_workflow_id ON configuration_sets(workflow_id); -CREATE INDEX IF NOT EXISTS idx_item_types_configuration_set_id ON item_types(configuration_set_id); CREATE INDEX IF NOT EXISTS idx_item_types_hierarchy_level ON item_types(hierarchy_level); CREATE INDEX IF NOT EXISTS idx_item_types_sort_order ON item_types(sort_order); CREATE INDEX IF NOT EXISTS idx_screen_fields_screen_id ON screen_fields(screen_id); diff --git a/internal/database/schema/config_workflows_postgres.sql b/internal/database/schema/config_workflows_postgres.sql index ff3bca873..cc5431aa7 100644 --- a/internal/database/schema/config_workflows_postgres.sql +++ b/internal/database/schema/config_workflows_postgres.sql @@ -150,7 +150,6 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_statuses_builtin_key ON statuses(builtin_ke CREATE UNIQUE INDEX IF NOT EXISTS uq_workflows_builtin_key ON workflows(builtin_key) WHERE builtin_key IS NOT NULL; -- Item type indexes (moved to base_tables_postgres.sql) -CREATE INDEX IF NOT EXISTS idx_item_types_configuration_set_id ON item_types(configuration_set_id); -- Screen field indexes CREATE INDEX IF NOT EXISTS idx_screen_fields_screen_id ON screen_fields(screen_id); diff --git a/internal/database/schema/integrations.sql b/internal/database/schema/integrations.sql index f014a086f..77842abfa 100644 --- a/internal/database/schema/integrations.sql +++ b/internal/database/schema/integrations.sql @@ -164,6 +164,10 @@ CREATE TABLE IF NOT EXISTS zammad_connections ( correlation_field TEXT NOT NULL DEFAULT 'windshift_item_key', closed_state_ids TEXT NOT NULL DEFAULT '[]', completion_status_id INTEGER, + -- Legacy connection-level scope. Runtime queries use action_credentials and + -- action_credential_workspaces; migration 20260901_zammad_canonical_workspace_scope + -- reads this state to backfill managed credentials. Retire only after every + -- supported upgrade has run that backfill (WI-2366). -- migration: 20260829_zammad_integration applies_to_all_workspaces BOOLEAN NOT NULL DEFAULT false, last_tested_at DATETIME, @@ -179,7 +183,9 @@ CREATE TABLE IF NOT EXISTS zammad_connections ( CREATE INDEX IF NOT EXISTS idx_zammad_connections_credential ON zammad_connections(credential_id); --- Workspace membership scope for connection-scoped credentials. +-- Legacy workspace membership for connection-scoped credentials. Superseded by +-- action_credential_workspaces; retained only for the 20260901 backfill. Retire +-- once every supported upgrade has run it (WI-2366). -- migration: 20260829_zammad_integration CREATE TABLE IF NOT EXISTS zammad_connection_workspaces ( provider_id TEXT NOT NULL, diff --git a/internal/database/schema/integrations_postgres.sql b/internal/database/schema/integrations_postgres.sql index cdbb28aef..b48fc1d5e 100644 --- a/internal/database/schema/integrations_postgres.sql +++ b/internal/database/schema/integrations_postgres.sql @@ -146,6 +146,10 @@ CREATE TABLE IF NOT EXISTS zammad_connections ( correlation_field TEXT NOT NULL DEFAULT 'windshift_item_key', closed_state_ids TEXT NOT NULL DEFAULT '[]', completion_status_id INTEGER REFERENCES statuses(id) ON DELETE SET NULL, + -- Legacy connection-level scope. Runtime queries use action_credentials and + -- action_credential_workspaces; migration 20260901_zammad_canonical_workspace_scope + -- reads this state to backfill managed credentials. Retire only after every + -- supported upgrade has run that backfill (WI-2366). -- migration: 20260829_zammad_integration applies_to_all_workspaces BOOLEAN NOT NULL DEFAULT false, last_tested_at TIMESTAMPTZ, @@ -157,7 +161,9 @@ CREATE TABLE IF NOT EXISTS zammad_connections ( CREATE INDEX IF NOT EXISTS idx_zammad_connections_credential ON zammad_connections(credential_id); --- Workspace membership scope for connection-scoped credentials. +-- Legacy workspace membership for connection-scoped credentials. Superseded by +-- action_credential_workspaces; retained only for the 20260901 backfill. Retire +-- once every supported upgrade has run it (WI-2366). -- migration: 20260829_zammad_integration CREATE TABLE IF NOT EXISTS zammad_connection_workspaces ( provider_id TEXT NOT NULL REFERENCES zammad_connections(provider_id) ON DELETE CASCADE, diff --git a/internal/database/schema/items.sql b/internal/database/schema/items.sql index 35540e1b4..4f4904154 100644 --- a/internal/database/schema/items.sql +++ b/internal/database/schema/items.sql @@ -67,11 +67,10 @@ CREATE TABLE IF NOT EXISTS items ( FOREIGN KEY (item_type_id) REFERENCES item_types(id) ON DELETE SET NULL, FOREIGN KEY (parent_id) REFERENCES items(id) ON DELETE CASCADE, FOREIGN KEY (iteration_id) REFERENCES iterations(id) ON DELETE SET NULL, - FOREIGN KEY (time_project_id) REFERENCES time_projects(id) ON DELETE SET NULL, - FOREIGN KEY (assignee_id) REFERENCES users(id) ON DELETE SET NULL, - FOREIGN KEY (creator_id) REFERENCES users(id) ON DELETE SET NULL, - FOREIGN KEY (reporter_id) REFERENCES users(id) ON DELETE SET NULL, - FOREIGN KEY (creator_portal_customer_id) REFERENCES portal_customers(id) ON DELETE SET NULL, + -- time_project_id, assignee_id, creator_id, reporter_id and + -- creator_portal_customer_id declare their foreign key inline above. + -- Existing SQLite installs keep the duplicate copies until the planned items + -- rebuild; fresh installs declare each relationship once. UNIQUE(workspace_id, workspace_item_number) ); diff --git a/internal/database/schema/milestones.sql b/internal/database/schema/milestones.sql index 87a7ab034..9d6a45ff3 100644 --- a/internal/database/schema/milestones.sql +++ b/internal/database/schema/milestones.sql @@ -92,8 +92,7 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_milestones_workspace_external_key WHERE external_key IS NOT NULL; -- Composite index supports the per-scope position ordering used by drag-and-drop --- reorder. Existing installs use milestones_existing.sql before catalog --- migrations, so this canonical fresh-install schema can include the index. +-- reorder. CREATE INDEX IF NOT EXISTS idx_milestones_position ON milestones(is_global, workspace_id, category_id, position); -- migration: 20260716_milestone_scope_guard diff --git a/internal/database/schema/milestones_existing.sql b/internal/database/schema/milestones_existing.sql deleted file mode 100644 index 8b158c8da..000000000 --- a/internal/database/schema/milestones_existing.sql +++ /dev/null @@ -1,80 +0,0 @@ --- Existing-install compatibility bootstrap for the milestone tables. --- --- migration: 20260727_milestone_release_attempts --- --- Fresh installs use milestones.sql. This file is replayed before catalog --- migrations on existing installs, so it must contain only the legacy table --- shape and indexes whose columns already existed before those migrations. --- Keep new columns and indexes in milestones.sql and the catalog instead. -CREATE TABLE IF NOT EXISTS milestone_categories ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL UNIQUE, - color TEXT NOT NULL, - description TEXT, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - updated_at DATETIME DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS milestones ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL, - description TEXT, - target_date DATE, - status TEXT NOT NULL DEFAULT 'planning', - category_id INTEGER, - is_global INTEGER NOT NULL DEFAULT 1, - workspace_id INTEGER, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (category_id) REFERENCES milestone_categories(id) ON DELETE SET NULL, - FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, - CONSTRAINT milestones_scope_check CHECK ( - (is_global = TRUE AND workspace_id IS NULL) OR - (is_global = FALSE AND workspace_id IS NOT NULL) - ) -); - -CREATE TABLE IF NOT EXISTS milestone_releases ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - milestone_id INTEGER NOT NULL REFERENCES milestones(id) ON DELETE CASCADE, - tag_name TEXT NOT NULL, - name TEXT, - body TEXT, - is_draft INTEGER NOT NULL DEFAULT 0, - is_prerelease INTEGER NOT NULL DEFAULT 0, - target_commitish TEXT, - workspace_repository_id INTEGER, - tag_url TEXT, - release_status TEXT NOT NULL DEFAULT 'tag_only', - released_at DATETIME, - assets_json TEXT NOT NULL DEFAULT '[]', - last_synced_at DATETIME, - scm_connection_id INTEGER REFERENCES workspace_scm_connections(id) ON DELETE SET NULL, - scm_repository TEXT, - scm_release_id TEXT, - scm_release_url TEXT, - created_by INTEGER REFERENCES users(id) ON DELETE SET NULL, - created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS item_milestones ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - item_id INTEGER NOT NULL, - milestone_id INTEGER NOT NULL, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (item_id) REFERENCES items(id) ON DELETE CASCADE, - FOREIGN KEY (milestone_id) REFERENCES milestones(id) ON DELETE CASCADE, - UNIQUE(item_id, milestone_id) -); - -CREATE INDEX IF NOT EXISTS idx_milestones_category_id ON milestones(category_id); -CREATE INDEX IF NOT EXISTS idx_milestones_status ON milestones(status); -CREATE INDEX IF NOT EXISTS idx_milestones_target_date ON milestones(target_date); -CREATE INDEX IF NOT EXISTS idx_milestones_workspace_id ON milestones(workspace_id); -CREATE INDEX IF NOT EXISTS idx_milestones_is_global ON milestones(is_global); -CREATE INDEX IF NOT EXISTS idx_milestone_releases_milestone_id ON milestone_releases(milestone_id); -CREATE INDEX IF NOT EXISTS idx_item_milestones_item_id ON item_milestones(item_id); -CREATE INDEX IF NOT EXISTS idx_item_milestones_milestone_id ON item_milestones(milestone_id); - --- migration: 20260716_milestone_scope_guard diff --git a/internal/database/schema/milestones_existing_postgres.sql b/internal/database/schema/milestones_existing_postgres.sql deleted file mode 100644 index b75a3882f..000000000 --- a/internal/database/schema/milestones_existing_postgres.sql +++ /dev/null @@ -1,78 +0,0 @@ --- Existing-install compatibility bootstrap for the milestone tables. --- --- migration: 20260727_milestone_release_attempts --- --- Fresh installs use milestones_postgres.sql. This file is replayed before --- catalog migrations on existing installs, so it must contain only the legacy --- table shape and indexes whose columns already existed before those --- migrations. Keep new columns and indexes in the canonical schema and the --- catalog instead. -CREATE TABLE IF NOT EXISTS milestone_categories ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL UNIQUE, - color TEXT NOT NULL, - description TEXT, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS milestones ( - id SERIAL PRIMARY KEY, - name TEXT NOT NULL, - description TEXT, - target_date DATE, - status TEXT NOT NULL DEFAULT 'planning', - category_id INTEGER, - is_global BOOLEAN NOT NULL DEFAULT true, - workspace_id INTEGER, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (category_id) REFERENCES milestone_categories(id) ON DELETE SET NULL, - FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, - CONSTRAINT milestones_scope_check CHECK ( - (is_global = true AND workspace_id IS NULL) OR - (is_global = false AND workspace_id IS NOT NULL) - ) -); - -CREATE TABLE IF NOT EXISTS milestone_releases ( - id SERIAL PRIMARY KEY, - milestone_id INTEGER NOT NULL REFERENCES milestones(id) ON DELETE CASCADE, - tag_name TEXT NOT NULL, - name TEXT, - body TEXT, - is_draft BOOLEAN NOT NULL DEFAULT false, - is_prerelease BOOLEAN NOT NULL DEFAULT false, - target_commitish TEXT, - workspace_repository_id INTEGER, - tag_url TEXT, - release_status TEXT NOT NULL DEFAULT 'tag_only', - released_at TIMESTAMPTZ, - assets_json JSONB NOT NULL DEFAULT '[]'::jsonb, - last_synced_at TIMESTAMPTZ, - scm_connection_id INTEGER, - scm_repository TEXT, - scm_release_id TEXT, - scm_release_url TEXT, - created_by INTEGER REFERENCES users(id) ON DELETE SET NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP -); - -CREATE TABLE IF NOT EXISTS item_milestones ( - id SERIAL PRIMARY KEY, - item_id INTEGER NOT NULL, - milestone_id INTEGER NOT NULL, - created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (milestone_id) REFERENCES milestones(id) ON DELETE CASCADE, - UNIQUE(item_id, milestone_id) -); - -CREATE INDEX IF NOT EXISTS idx_milestones_category_id ON milestones(category_id); -CREATE INDEX IF NOT EXISTS idx_milestones_status ON milestones(status); -CREATE INDEX IF NOT EXISTS idx_milestones_target_date ON milestones(target_date); -CREATE INDEX IF NOT EXISTS idx_milestones_workspace_id ON milestones(workspace_id); -CREATE INDEX IF NOT EXISTS idx_milestones_is_global ON milestones(is_global); -CREATE INDEX IF NOT EXISTS idx_milestone_releases_milestone_id ON milestone_releases(milestone_id); -CREATE INDEX IF NOT EXISTS idx_item_milestones_item_id ON item_milestones(item_id); -CREATE INDEX IF NOT EXISTS idx_item_milestones_milestone_id ON item_milestones(milestone_id); diff --git a/internal/database/schema/milestones_postgres.sql b/internal/database/schema/milestones_postgres.sql index 03523f192..ef3952a5f 100644 --- a/internal/database/schema/milestones_postgres.sql +++ b/internal/database/schema/milestones_postgres.sql @@ -91,7 +91,5 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_milestones_workspace_external_key WHERE external_key IS NOT NULL; -- Composite index supports the per-scope position ordering used by drag-and-drop --- reorder. Existing installs use milestones_existing_postgres.sql before --- catalog migrations, so this canonical fresh-install schema can include the --- index. +-- reorder. CREATE INDEX IF NOT EXISTS idx_milestones_position ON milestones(is_global, workspace_id, category_id, position); diff --git a/internal/database/schema/notifications.sql b/internal/database/schema/notifications.sql index 8b6a02047..d91799da2 100644 --- a/internal/database/schema/notifications.sql +++ b/internal/database/schema/notifications.sql @@ -61,7 +61,8 @@ CREATE UNIQUE INDEX IF NOT EXISTS uq_notifications_delivery_key ON notifications -- Email templates: per-sender HTML/text/subject Go templates editable from the -- admin UI. `name` is the lookup key consumed by senders (e.g. "magic_link", -- "notification_batch"). Default rows are seeded from Go code so the same --- modernized templates ship to both SQLite and Postgres installs. +-- modernized templates ship to both SQLite and Postgres installs. template_type +-- still selects rows for the notification cache refresh, so it is not dead. CREATE TABLE IF NOT EXISTS notification_templates ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL UNIQUE, @@ -72,7 +73,7 @@ CREATE TABLE IF NOT EXISTS notification_templates ( is_system BOOLEAN DEFAULT FALSE, is_active BOOLEAN DEFAULT TRUE, is_customized BOOLEAN NOT NULL DEFAULT FALSE, -- true once an admin saves an edit; unmodified seeds fall back to the localized built-in default - template_type TEXT, -- legacy, unused + template_type TEXT, -- read by the notification cache refresh created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ); diff --git a/internal/database/schema/notifications_postgres.sql b/internal/database/schema/notifications_postgres.sql index 4d17a805d..61a5589a0 100644 --- a/internal/database/schema/notifications_postgres.sql +++ b/internal/database/schema/notifications_postgres.sql @@ -107,15 +107,16 @@ CREATE TABLE IF NOT EXISTS configuration_set_notification_settings ( notification_setting_id INTEGER NOT NULL, created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (configuration_set_id) REFERENCES configuration_sets(id) ON DELETE CASCADE, - FOREIGN KEY (notification_setting_id) REFERENCES notification_settings(id) ON DELETE CASCADE, - UNIQUE(configuration_set_id, notification_setting_id) + FOREIGN KEY (notification_setting_id) REFERENCES notification_settings(id) ON DELETE CASCADE ); CREATE INDEX IF NOT EXISTS idx_config_set_notification_settings_notification ON configuration_set_notification_settings(notification_setting_id); -- One notification setting per configuration set. The column-level UNIQUE on -- SQLite already enforces this, but PostgreSQL needs a single-column unique -- index as the ON CONFLICT(configuration_set_id) target used by --- ConfigurationSetRepository.AssignNotification. +-- ConfigurationSetRepository.AssignNotification. It also subsumes the old +-- UNIQUE(configuration_set_id, notification_setting_id), which the migration +-- 20261209_notification_setting_unique drops. CREATE UNIQUE INDEX IF NOT EXISTS uq_config_set_notification_setting_one_per_set ON configuration_set_notification_settings(configuration_set_id); diff --git a/internal/database/schema/system.sql b/internal/database/schema/system.sql index 459144ed2..9000ccbac 100644 --- a/internal/database/schema/system.sql +++ b/internal/database/schema/system.sql @@ -284,7 +284,11 @@ CREATE TABLE IF NOT EXISTS board_configurations ( created_at DATETIME DEFAULT CURRENT_TIMESTAMP, updated_at DATETIME DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, - FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE + FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE, + CONSTRAINT board_configurations_exactly_one_owner CHECK ( + (workspace_id IS NOT NULL AND collection_id IS NULL) OR + (workspace_id IS NULL AND collection_id IS NOT NULL) + ) ); CREATE TABLE IF NOT EXISTS board_columns ( @@ -309,8 +313,10 @@ CREATE TABLE IF NOT EXISTS board_column_statuses ( UNIQUE(board_column_id, status_id) ); -CREATE INDEX IF NOT EXISTS idx_board_configurations_workspace_id ON board_configurations(workspace_id); -CREATE INDEX IF NOT EXISTS idx_board_configurations_collection_id ON board_configurations(collection_id); +-- One configuration per owner. Partial unique indexes also back the +-- workspace/collection lookups, so no separate plain index is needed. +CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_workspace ON board_configurations(workspace_id) WHERE workspace_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_collection ON board_configurations(collection_id) WHERE collection_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_board_columns_board_configuration_id ON board_columns(board_configuration_id); CREATE INDEX IF NOT EXISTS idx_board_columns_display_order ON board_columns(display_order); CREATE INDEX IF NOT EXISTS idx_board_column_statuses_board_column_id ON board_column_statuses(board_column_id); @@ -408,19 +414,10 @@ CREATE INDEX IF NOT EXISTS idx_item_watches_item_id ON item_watches(item_id); CREATE INDEX IF NOT EXISTS idx_item_watches_user_id ON item_watches(user_id); CREATE INDEX IF NOT EXISTS idx_item_watches_user_active ON item_watches(user_id, is_active); --- Request types and fields for portal/channel routing -CREATE TABLE IF NOT EXISTS request_types ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - name TEXT NOT NULL UNIQUE, - description TEXT, - icon TEXT DEFAULT 'MessageSquare', - color TEXT DEFAULT '#3B82F6', - is_default BOOLEAN DEFAULT false, - display_order INTEGER DEFAULT 0, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - updated_at DATETIME DEFAULT CURRENT_TIMESTAMP -); - +-- request_type_fields for portal/channel routing. request_types itself is +-- created by request_types.sql (channel-scoped and per item type); the old +-- globally-unique declaration that lived here never applied because that file +-- loads first, so it has been removed. CREATE TABLE IF NOT EXISTS request_type_fields ( id INTEGER PRIMARY KEY AUTOINCREMENT, request_type_id INTEGER NOT NULL, diff --git a/internal/database/schema/system_postgres.sql b/internal/database/schema/system_postgres.sql index f0a34276e..17bf5ad50 100644 --- a/internal/database/schema/system_postgres.sql +++ b/internal/database/schema/system_postgres.sql @@ -296,7 +296,11 @@ CREATE TABLE IF NOT EXISTS board_configurations ( created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, - FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE + FOREIGN KEY (collection_id) REFERENCES collections(id) ON DELETE CASCADE, + CONSTRAINT board_configurations_exactly_one_owner CHECK ( + (workspace_id IS NOT NULL AND collection_id IS NULL) OR + (workspace_id IS NULL AND collection_id IS NOT NULL) + ) ); CREATE TABLE IF NOT EXISTS board_columns ( @@ -321,8 +325,10 @@ CREATE TABLE IF NOT EXISTS board_column_statuses ( UNIQUE(board_column_id, status_id) ); -CREATE INDEX IF NOT EXISTS idx_board_configurations_workspace_id ON board_configurations(workspace_id); -CREATE INDEX IF NOT EXISTS idx_board_configurations_collection_id ON board_configurations(collection_id); +-- One configuration per owner. Partial unique indexes also back the +-- workspace/collection lookups, so no separate plain index is needed. +CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_workspace ON board_configurations(workspace_id) WHERE workspace_id IS NOT NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_collection ON board_configurations(collection_id) WHERE collection_id IS NOT NULL; CREATE INDEX IF NOT EXISTS idx_board_columns_board_configuration_id ON board_columns(board_configuration_id); CREATE INDEX IF NOT EXISTS idx_board_columns_display_order ON board_columns(display_order); CREATE INDEX IF NOT EXISTS idx_board_column_statuses_board_column_id ON board_column_statuses(board_column_id); diff --git a/internal/database/schema/time_tracking.sql b/internal/database/schema/time_tracking.sql index b96932957..568408a89 100644 --- a/internal/database/schema/time_tracking.sql +++ b/internal/database/schema/time_tracking.sql @@ -47,15 +47,9 @@ CREATE TABLE IF NOT EXISTS time_projects ( FOREIGN KEY (category_id) REFERENCES time_project_categories(id) ON DELETE SET NULL ); -CREATE TABLE IF NOT EXISTS workspace_time_project_categories ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - workspace_id INTEGER NOT NULL, - time_project_category_id INTEGER NOT NULL, - created_at DATETIME DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (workspace_id) REFERENCES workspaces(id) ON DELETE CASCADE, - FOREIGN KEY (time_project_category_id) REFERENCES time_project_categories(id) ON DELETE CASCADE, - UNIQUE(workspace_id, time_project_category_id) -); +-- workspace_time_project_categories is created by workspace.sql (it depends on +-- workspaces). The duplicate declaration and indexes that lived here never +-- applied because workspace.sql loads first, so they have been removed. CREATE TABLE IF NOT EXISTS time_worklogs ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -75,8 +69,6 @@ CREATE TABLE IF NOT EXISTS time_worklogs ( CREATE INDEX IF NOT EXISTS idx_time_projects_customer_id ON time_projects(customer_id); CREATE INDEX IF NOT EXISTS idx_time_projects_category_id ON time_projects(category_id); CREATE INDEX IF NOT EXISTS idx_time_projects_status ON time_projects(status); -CREATE INDEX IF NOT EXISTS idx_workspace_time_project_categories_workspace_id ON workspace_time_project_categories(workspace_id); -CREATE INDEX IF NOT EXISTS idx_workspace_time_project_categories_category_id ON workspace_time_project_categories(time_project_category_id); CREATE INDEX IF NOT EXISTS idx_time_worklogs_project_id ON time_worklogs(project_id); CREATE INDEX IF NOT EXISTS idx_time_worklogs_date ON time_worklogs(date); CREATE INDEX IF NOT EXISTS idx_time_worklogs_item_id ON time_worklogs(item_id); diff --git a/internal/models/workspace_agent_binding.go b/internal/models/workspace_agent_binding.go index 12732f82a..9c24abe10 100644 --- a/internal/models/workspace_agent_binding.go +++ b/internal/models/workspace_agent_binding.go @@ -91,8 +91,9 @@ type WorkspaceAgentBinding struct { // Instructions is the binding's persona/specialization, appended to the // run's standard initial prompt as a "Your role" section (WI-258). It // never replaces the operational prompt. - Instructions string `json:"instructions,omitempty"` - CreatedByUserID int `json:"created_by_user_id"` + Instructions string `json:"instructions,omitempty"` + // CreatedByUserID is a soft audit ref; nil once the creator is deleted. + CreatedByUserID *int `json:"created_by_user_id,omitempty"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` diff --git a/internal/repository/board_configuration_repository.go b/internal/repository/board_configuration_repository.go index 8a1d789d0..0591f5bec 100644 --- a/internal/repository/board_configuration_repository.go +++ b/internal/repository/board_configuration_repository.go @@ -99,6 +99,9 @@ func (r *BoardConfigurationRepository) getConfig(where string, arg any) (*models // workspace (exactly one of the two must be non-nil), plus its columns and // status mappings, in a single transaction. Returns the new configuration id. func (r *BoardConfigurationRepository) Create(collectionID, workspaceID *int, req *models.BoardConfigurationRequest) (int, error) { + if (collectionID == nil) == (workspaceID == nil) { + return 0, fmt.Errorf("board configuration requires exactly one owner") + } configBytes, err := marshalBoardConfigFields(req) if err != nil { return 0, err diff --git a/internal/repository/workspace_agent_binding_repository.go b/internal/repository/workspace_agent_binding_repository.go index f6967cdd5..9c772b85e 100644 --- a/internal/repository/workspace_agent_binding_repository.go +++ b/internal/repository/workspace_agent_binding_repository.go @@ -137,7 +137,7 @@ func (r *WorkspaceAgentBindingRepository) Insert(ctx context.Context, b *models. nullStringArg(b.RepoSlug), nullStringArg(b.RepoBaseRef), nullIntArg(b.LLMConnectionID), nullIntArg(b.SCMConnectionID), nullIntArg(b.TargetPoolID), string(scopesJSON), b.TokenTTLMinutes, b.MaxRunsPerDay, - b.Instructions, nullStringArg(b.RunnerImage), b.CreatedByUserID, + b.Instructions, nullStringArg(b.RunnerImage), nullIntArg(b.CreatedByUserID), ).Scan(&id) if err != nil { if database.IsUniqueConstraintError(err) { @@ -400,8 +400,16 @@ func (r *WorkspaceAgentBindingRepository) UpdateAgentConfig(ctx context.Context, // instructions, and the repository set. The acting identity, workspace, target // pool, and runner image are NOT touched here (identity is immutable; runner // image has its own presence-aware setter). The primary repo is mirrored onto -// the deprecated scalar columns, matching Insert (WI-450). +// the deprecated scalar columns, matching Insert (WI-450). The parent version +// bump and the repository replacement share one transaction so a failure can +// never publish a new profile_version with the old or a partial repository list. +// Retiring the scalar mirror (deriving the legacy fields from the primary child +// instead) is deferred until its rollback window closes (WI-2366). func (r *WorkspaceAgentBindingRepository) UpdateConfig(ctx context.Context, b *models.WorkspaceAgentBinding) error { + db, ok := r.db.(database.Database) + if !ok { + return fmt.Errorf("update binding config: repository is not bound to a database") + } scopesJSON, err := json.Marshal(b.TokenScopes) if err != nil { return fmt.Errorf("marshal token scopes: %w", err) @@ -418,25 +426,27 @@ func (r *WorkspaceAgentBindingRepository) UpdateConfig(ctx context.Context, b *m b.RepoBaseRef = p.RepoBaseRef b.SCMConnectionID = p.SCMConnectionID } - if _, err := r.db.ExecWriteContext(ctx, ` - UPDATE workspace_agent_bindings - SET llm_connection_id = ?, scm_connection_id = ?, repo_slug = ?, repo_base_ref = ?, - token_scopes_json = ?, token_ttl_minutes = ?, max_runs_per_day = ?, - instructions = ?, capability_groups_json = ?, - lifecycle = CASE WHEN lifecycle = 'archived' THEN lifecycle ELSE 'draft' END, - profile_version = profile_version + 1, - updated_at = CURRENT_TIMESTAMP - WHERE id = ? AND workspace_id = ? - `, - nullIntArg(b.LLMConnectionID), nullIntArg(b.SCMConnectionID), - nullStringArg(b.RepoSlug), nullStringArg(b.RepoBaseRef), - string(scopesJSON), b.TokenTTLMinutes, b.MaxRunsPerDay, - b.Instructions, string(capabilitiesJSON), b.ID, b.WorkspaceID, - ); err != nil { - return fmt.Errorf("update binding config: %w", err) - } - if err := r.ReplaceBindingRepos(ctx, b.ID, repos); err != nil { - return fmt.Errorf("replace binding repos: %w", err) + if err := database.WithTx(db, func(tx database.Tx) error { + if _, err := tx.ExecWriteContext(ctx, ` + UPDATE workspace_agent_bindings + SET llm_connection_id = ?, scm_connection_id = ?, repo_slug = ?, repo_base_ref = ?, + token_scopes_json = ?, token_ttl_minutes = ?, max_runs_per_day = ?, + instructions = ?, capability_groups_json = ?, + lifecycle = CASE WHEN lifecycle = 'archived' THEN lifecycle ELSE 'draft' END, + profile_version = profile_version + 1, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? AND workspace_id = ? + `, + nullIntArg(b.LLMConnectionID), nullIntArg(b.SCMConnectionID), + nullStringArg(b.RepoSlug), nullStringArg(b.RepoBaseRef), + string(scopesJSON), b.TokenTTLMinutes, b.MaxRunsPerDay, + b.Instructions, string(capabilitiesJSON), b.ID, b.WorkspaceID, + ); err != nil { + return fmt.Errorf("update binding config: %w", err) + } + return NewWorkspaceAgentBindingRepositoryTx(tx).ReplaceBindingRepos(ctx, b.ID, repos) + }); err != nil { + return err } b.Repos = repos return nil @@ -476,8 +486,9 @@ func (r *WorkspaceAgentBindingRepository) Delete(ctx context.Context, id, worksp // responsible for validating the repos (slug shape, one primary, no dupes) // before calling — the partial unique index on is_primary and the // (binding_id, repo_slug) unique index are the last line of defense and -// surface as a generic error. Like ReplaceBindingSkills this is not wrapped -// in an explicit tx; on create the service deletes the binding if this fails. +// surface as a generic error. It runs against whatever store the repository was +// built with; UpdateConfig passes a transaction so the delete and inserts land +// with the parent version bump, and Insert deletes the binding if this fails. func (r *WorkspaceAgentBindingRepository) ReplaceBindingRepos(ctx context.Context, bindingID int, repos []models.BindingRepo) error { if _, err := r.db.ExecWriteContext(ctx, `DELETE FROM workspace_agent_binding_repos WHERE binding_id = ?`, bindingID); err != nil { return fmt.Errorf("clear binding repos: %w", err) @@ -636,7 +647,7 @@ func scanBindingRows(rows *sql.Rows) (*models.WorkspaceAgentBinding, error) { func scanBindingFrom(scanner bindingRowScanner) (*models.WorkspaceAgentBinding, error) { b := &models.WorkspaceAgentBinding{} var repoSlug, repoBaseRef, runnerImage sql.NullString - var llmConn, scmConn, targetPool, archivedBy sql.NullInt64 + var llmConn, scmConn, targetPool, archivedBy, createdBy sql.NullInt64 var archivedAt sql.NullTime var scopesJSON, capabilityGroupsJSON string if err := scanner.Scan( @@ -645,7 +656,7 @@ func scanBindingFrom(scanner bindingRowScanner) (*models.WorkspaceAgentBinding, &b.Purpose, &capabilityGroupsJSON, &repoSlug, &repoBaseRef, &llmConn, &scmConn, &targetPool, &scopesJSON, &b.TokenTTLMinutes, &b.MaxRunsPerDay, - &b.Instructions, &runnerImage, &b.CreatedByUserID, + &b.Instructions, &runnerImage, &createdBy, &archivedAt, &archivedBy, &b.LastKnownName, &b.LastKnownHandle, &b.LastKnownAvatar, &b.DisplayName, &b.Handle, &b.AvatarURL, @@ -674,6 +685,10 @@ func scanBindingFrom(scanner bindingRowScanner) (*models.WorkspaceAgentBinding, v := int(targetPool.Int64) b.TargetPoolID = &v } + if createdBy.Valid { + v := int(createdBy.Int64) + b.CreatedByUserID = &v + } if scopesJSON != "" { _ = json.Unmarshal([]byte(scopesJSON), &b.TokenScopes) } diff --git a/internal/services/agent_profile_service.go b/internal/services/agent_profile_service.go index f0c41b843..b6e90ace2 100644 --- a/internal/services/agent_profile_service.go +++ b/internal/services/agent_profile_service.go @@ -413,7 +413,7 @@ func (s *BindingService) CreateStudioProfile(ctx context.Context, req CreateStud TokenTTLMinutes: req.TokenTTLMinutes, MaxRunsPerDay: req.MaxRunsPerDay, Instructions: *req.Instructions, - CreatedByUserID: req.CreatedByUserID, + CreatedByUserID: &req.CreatedByUserID, Repos: repos, } txBindings := repository.NewWorkspaceAgentBindingRepositoryTx(tx) diff --git a/internal/services/binding_service.go b/internal/services/binding_service.go index b5ae644fd..8fdfeb186 100644 --- a/internal/services/binding_service.go +++ b/internal/services/binding_service.go @@ -485,7 +485,7 @@ func (s *BindingService) Create(ctx context.Context, req CreateBindingRequest) ( TokenTTLMinutes: req.TokenTTLMinutes, MaxRunsPerDay: req.MaxRunsPerDay, Instructions: req.Instructions, - CreatedByUserID: req.CreatedByUserID, + CreatedByUserID: &req.CreatedByUserID, Repos: repos, } // Persist the binding and repository rows atomically. diff --git a/internal/services/items.go b/internal/services/items.go index 4aec0a502..342ba1bc6 100644 --- a/internal/services/items.go +++ b/internal/services/items.go @@ -312,30 +312,37 @@ func createItemWithSnapshot(ctx context.Context, db database.Database, params It return int64(itemID), creation.snapshot, nil } -// GetInitialStatusForItemType determines the initial status for an item type -// by querying the workflow assigned to the item type. Uses a two-tier override system: -// 1. First checks if there's a workflow override for this specific item type +// GetInitialStatusForItemType determines the initial status for an item type in +// a workspace by resolving the workspace's effective configuration set and then +// the item type's workflow inside that set. Uses a two-tier override system: +// 1. First checks for a workflow override on the set's configuration_set_item_types row // 2. Falls back to the configuration set's default workflow if no override exists -// Returns the status name of the first status in the workflow (where from_status_id IS NULL). -// Returns an error if the item type, configuration set, workflow, or initial status cannot be found. -func GetInitialStatusForItemType(db database.Database, itemTypeID int) (string, error) { - // First, get the workflow ID with fallback logic: - // 1. Check for item-type-specific override in configuration_set_item_types - // 2. If NULL, use configuration set default workflow +// The junction is authoritative: a type the set deliberately excludes (for +// example Initiative in the simplified default set) resolves to the set default +// rather than to another set's workflow. Returns the status name of the first +// status in the workflow (where from_status_id IS NULL). Returns an error if the +// workspace, configuration set, workflow, or initial status cannot be found. +func GetInitialStatusForItemType(db database.Database, workspaceID, itemTypeID int) (string, error) { + // Resolve the effective set the same way ItemTypeRepository.ListForWorkspace + // does (assigned set, else the global default), then the item type's override. workflowQuery := ` - SELECT COALESCE(csit.workflow_id, cs.workflow_id) as workflow_id - FROM item_types it - LEFT JOIN configuration_set_item_types csit ON it.id = csit.item_type_id - JOIN configuration_sets cs ON ( - csit.configuration_set_id = cs.id OR - (csit.configuration_set_id IS NULL AND it.configuration_set_id = cs.id) + WITH effective AS ( + SELECT COALESCE(wcs.configuration_set_id, + (SELECT id FROM configuration_sets WHERE is_default = true ORDER BY id LIMIT 1)) AS configuration_set_id + FROM workspaces w + LEFT JOIN workspace_configuration_sets wcs ON wcs.workspace_id = w.id + WHERE w.id = ? ) - WHERE it.id = ? + SELECT COALESCE(csit.workflow_id, cs.workflow_id) as workflow_id + FROM effective e + LEFT JOIN configuration_sets cs ON cs.id = e.configuration_set_id + LEFT JOIN configuration_set_item_types csit + ON csit.configuration_set_id = cs.id AND csit.item_type_id = ? LIMIT 1 ` var workflowID *int - err := db.QueryRow(workflowQuery, itemTypeID).Scan(&workflowID) + err := db.QueryRow(workflowQuery, workspaceID, itemTypeID).Scan(&workflowID) if errors.Is(err, sql.ErrNoRows) { return "", fmt.Errorf("no configuration set or workflow found for item type %d", itemTypeID) } diff --git a/internal/services/submission.go b/internal/services/submission.go index 11b3c1932..7d5afdfcd 100644 --- a/internal/services/submission.go +++ b/internal/services/submission.go @@ -41,7 +41,7 @@ type SubmittedItemInput struct { func CreateSubmittedItem(db database.Database, in SubmittedItemInput) (int64, error) { initialStatus := defaultSubmittedItemStatus if in.ValidationResult.ItemTypeID != nil { - status, err := GetInitialStatusForItemType(db, *in.ValidationResult.ItemTypeID) + status, err := GetInitialStatusForItemType(db, in.WorkspaceID, *in.ValidationResult.ItemTypeID) if err != nil { slog.Warn("could not determine initial status for item type", slog.String("component", in.LogComponent), slog.Int("item_type_id", *in.ValidationResult.ItemTypeID), slog.Any("error", err)) } else { From 908f5a0d9d13cd0d5b7f326c5432e98fccab1b04 Mon Sep 17 00:00:00 2001 From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com> Date: Tue, 24 Nov 2026 20:55:19 +0100 Subject: [PATCH 2/3] fix(db): harden WI-2366 upgrade reconciliation Address the upgrade-path review findings: - Normalize dual-owner board configurations to their workspace owner before the exactly-one-owner check, so such a row no longer blocks startup. - Remove board columns (and their status mappings) left without a configuration. The SQLite rebuild runs with foreign keys off, so the ownerless-configuration delete did not cascade and a later board could inherit a deleted board's column. - Preserve the sqlite_sequence high-water mark across the binding and board table rebuilds. A deleted binding's id is still referenced by historical agent runs and must not be reused. - Backfill item-type membership only for custom types with no junction membership at all, and join configuration_sets so a scalar pointing at a deleted set cannot fail the foreign key. --- internal/database/migrations.go | 64 ++++++++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 8 deletions(-) diff --git a/internal/database/migrations.go b/internal/database/migrations.go index fddaa590a..d7e1d52bb 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3822,11 +3822,11 @@ END $$; INSERT INTO configuration_set_item_types (configuration_set_id, item_type_id) SELECT it.configuration_set_id, it.id FROM item_types it + JOIN configuration_sets cs ON cs.id = it.configuration_set_id WHERE it.configuration_set_id IS NOT NULL AND it.builtin_key IS NULL AND NOT EXISTS ( - SELECT 1 FROM configuration_set_item_types csit - WHERE csit.configuration_set_id = it.configuration_set_id AND csit.item_type_id = it.id + SELECT 1 FROM configuration_set_item_types csit WHERE csit.item_type_id = it.id ); DROP INDEX IF EXISTS idx_item_types_configuration_set_id; ALTER TABLE item_types DROP COLUMN configuration_set_id; @@ -3835,11 +3835,11 @@ END $$; INSERT INTO configuration_set_item_types (configuration_set_id, item_type_id) SELECT it.configuration_set_id, it.id FROM item_types it + JOIN configuration_sets cs ON cs.id = it.configuration_set_id WHERE it.configuration_set_id IS NOT NULL AND it.builtin_key IS NULL AND NOT EXISTS ( - SELECT 1 FROM configuration_set_item_types csit - WHERE csit.configuration_set_id = it.configuration_set_id AND csit.item_type_id = it.id + SELECT 1 FROM configuration_set_item_types csit WHERE csit.item_type_id = it.id ); DROP INDEX IF EXISTS idx_item_types_configuration_set_id; ALTER TABLE item_types DROP COLUMN configuration_set_id; @@ -3883,11 +3883,17 @@ END $$; `, }} -// boardConfigurationReconcileSQL merges duplicate board configurations onto the -// lowest-id survivor and deletes unreachable ownerless rows. Moving a -// duplicate's board_columns first keeps them; a plain delete would cascade -// them away with the configuration. +// boardConfigurationReconcileSQL normalizes board configurations to exactly one +// owner, merges duplicates onto the lowest-id survivor, and deletes unreachable +// ownerless rows. Moving a duplicate's board_columns first keeps them; a plain +// delete would cascade them away with the configuration. const boardConfigurationReconcileSQL = ` +-- A dual-owner row is invalid. Keep the workspace owner (the repository's +-- create precedence) and drop the collection owner so the exactly-one-owner +-- check can hold. +UPDATE board_configurations SET collection_id = NULL +WHERE workspace_id IS NOT NULL AND collection_id IS NOT NULL; + UPDATE board_columns SET board_configuration_id = ( SELECT MIN(survivor.id) @@ -3907,6 +3913,15 @@ DELETE FROM board_configurations WHERE (workspace_id IS NOT NULL AND id <> (SELECT MIN(s.id) FROM board_configurations s WHERE s.workspace_id = board_configurations.workspace_id)) OR (collection_id IS NOT NULL AND id <> (SELECT MIN(s.id) FROM board_configurations s WHERE s.collection_id = board_configurations.collection_id)) OR (workspace_id IS NULL AND collection_id IS NULL); + +-- SQLite runs this with foreign keys off, so the deletes above do not cascade. +-- Remove columns (and their status mappings) left without a configuration so a +-- later board that reuses the freed id cannot inherit them. +DELETE FROM board_columns +WHERE NOT EXISTS (SELECT 1 FROM board_configurations cfg WHERE cfg.id = board_columns.board_configuration_id); + +DELETE FROM board_column_statuses +WHERE NOT EXISTS (SELECT 1 FROM board_columns bc WHERE bc.id = board_column_statuses.board_column_id); ` const boardConfigurationOwnershipPostgres = boardConfigurationReconcileSQL + ` @@ -6389,6 +6404,29 @@ func applySQLiteActiveTimerNullableProject(db Database) (retErr error) { return nil } +// readSQLiteSequence returns the AUTOINCREMENT high-water mark for table. It +// reports false when the table has no sqlite_sequence row (never inserted, or +// the sequence table is absent). +func readSQLiteSequence(ctx context.Context, conn *sql.Conn, table string) (int64, bool) { + var seq int64 + if err := conn.QueryRowContext(ctx, "SELECT seq FROM sqlite_sequence WHERE name = ?", table).Scan(&seq); err != nil { + return 0, false + } + return seq, true +} + +// sqliteSequenceFloorStatements keep a rebuilt AUTOINCREMENT table's rowid +// high-water mark at least floor. A DROP+RENAME rebuild only reflects the +// copied rows in sqlite_sequence, so without this a later insert can reuse the +// id of a row deleted before the migration. Historical references such as +// agent_runs.binding_id would then count against an unrelated new row. +func sqliteSequenceFloorStatements(table string, floor int64) []string { + return []string{ + fmt.Sprintf("UPDATE sqlite_sequence SET seq = %d WHERE name = '%s' AND seq < %d", floor, table, floor), + fmt.Sprintf("INSERT INTO sqlite_sequence(name, seq) SELECT '%s', %d WHERE NOT EXISTS (SELECT 1 FROM sqlite_sequence WHERE name = '%s')", table, floor, table), + } +} + // applySQLiteBindingCreatorNullable rebuilds workspace_agent_bindings so // created_by_user_id accepts NULL. The column's ON DELETE SET NULL foreign key // and a NOT NULL declaration cannot both hold, so a creator deletion either @@ -6423,6 +6461,8 @@ func applySQLiteBindingCreatorNullable(db Database) (retErr error) { }() } + bindingSeq, hasBindingSeq := readSQLiteSequence(ctx, conn, "workspace_agent_bindings") + tx, err := conn.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("begin workspace_agent_bindings rebuild: %w", err) @@ -6487,6 +6527,9 @@ func applySQLiteBindingCreatorNullable(db Database) (retErr error) { `CREATE INDEX IF NOT EXISTS idx_workspace_agent_bindings_workspace_lifecycle ON workspace_agent_bindings(workspace_id, lifecycle)`, `CREATE INDEX IF NOT EXISTS idx_workspace_agent_bindings_scm_connection ON workspace_agent_bindings(scm_connection_id)`, } + if hasBindingSeq { + statements = append(statements, sqliteSequenceFloorStatements("workspace_agent_bindings", bindingSeq)...) + } for _, statement := range statements { if _, err := tx.ExecContext(ctx, statement); err != nil { return fmt.Errorf("rebuild workspace_agent_bindings: %w", err) @@ -6530,6 +6573,8 @@ func applySQLiteBoardConfigurationOwnership(db Database) (retErr error) { }() } + boardSeq, hasBoardSeq := readSQLiteSequence(ctx, conn, "board_configurations") + tx, err := conn.BeginTx(ctx, nil) if err != nil { return fmt.Errorf("begin board_configurations rebuild: %w", err) @@ -6570,6 +6615,9 @@ func applySQLiteBoardConfigurationOwnership(db Database) (retErr error) { `CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_workspace ON board_configurations(workspace_id) WHERE workspace_id IS NOT NULL`, `CREATE UNIQUE INDEX IF NOT EXISTS uq_board_configurations_collection ON board_configurations(collection_id) WHERE collection_id IS NOT NULL`, } + if hasBoardSeq { + statements = append(statements, sqliteSequenceFloorStatements("board_configurations", boardSeq)...) + } for _, statement := range statements { if _, err := tx.ExecContext(ctx, statement); err != nil { return fmt.Errorf("rebuild board_configurations: %w", err) From 07a9be89f9344762135441186db887d33d9a7809 Mon Sep 17 00:00:00 2001 From: Stefan Ernst <24554551+stefan-ernst@users.noreply.github.com> Date: Tue, 24 Nov 2026 21:24:29 +0100 Subject: [PATCH 3/3] fix(db): drop the legacy iteration_types color default on upgrade The base_tables stub defaulted iteration_types.color to '#6b7280' while the fresh schema requires an explicit color. The alignment migration set NOT NULL but left the default, so an upgraded PostgreSQL database accepted a colorless insert that a fresh one rejects. Drop the default and require column_default IS NULL in the migration check. --- internal/database/migrations.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/internal/database/migrations.go b/internal/database/migrations.go index d7e1d52bb..673ce4b6d 100644 --- a/internal/database/migrations.go +++ b/internal/database/migrations.go @@ -3737,7 +3737,7 @@ END $$; Name: "Restore dropped PostgreSQL cascades and align iteration_types (WI-2366)", CheckPostgres: `SELECT CASE WHEN NOT EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='iteration_types' AND column_name='duration_days') - AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='iteration_types' AND column_name='color' AND is_nullable='NO') + AND EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='iteration_types' AND column_name='color' AND is_nullable='NO' AND column_default IS NULL) AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_workspace_id_fkey') AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='board_configurations'::regclass AND conname='board_configurations_collection_id_fkey') AND EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='test_folders'::regclass AND conname='test_folders_workspace_id_fkey') @@ -3772,6 +3772,9 @@ END $$; UPDATE iteration_types SET color = '#6b7280' WHERE color IS NULL; ALTER TABLE iteration_types ALTER COLUMN color SET NOT NULL; + -- The old base_tables stub defaulted color; the fresh schema requires an + -- explicit value, so drop it to keep both paths identical. + ALTER TABLE iteration_types ALTER COLUMN color DROP DEFAULT; ALTER TABLE iteration_types DROP COLUMN IF EXISTS duration_days; `, },