@@ -7,6 +7,16 @@ CREATE INDEX IF NOT EXISTS idx_vault_docs_team_chat
77 ON vault_documents(team_id, chat_id)
88 WHERE team_id IS NOT NULL ;
99
10+ -- Drop scope-consistency CHECK before backfill UPDATEs. Constraint was added
11+ -- NOT VALID in migration 55, which skips existing rows but still re-checks
12+ -- on every UPDATE. Legacy data (pre-M46 when agent_id was NOT NULL, pre-M43
13+ -- before team_id existed) often has rows that violate the invariant, causing
14+ -- the backfill UPDATEs below to abort and leave migration 56 in a dirty
15+ -- state (issue #1035). Drop now, re-add at end so fresh installs proceed
16+ -- cleanly. Constraint stays NOT VALID — legacy bad rows still tolerated;
17+ -- a future migration can clean + VALIDATE.
18+ ALTER TABLE vault_documents DROP CONSTRAINT IF EXISTS vault_documents_scope_consistency;
19+
1020-- -----------------------------------------------------------------------------
1121-- Backfill 1: team-scoped docs (scope='team', team_id set).
1222-- Two path layouts:
@@ -69,3 +79,15 @@ WHERE chat_id IS NULL
6979 OR path ~ ' ^group_[^/]+_-?[0-9]+/'
7080 OR path ~ ' ^[^/]+/[^/]+/(group_[^/]+_-?[0-9]+|[0-9]+)/'
7181 );
82+
83+ -- Re-add the scope-consistency constraint dropped above. NOT VALID matches
84+ -- migration 55's original semantics — existing rows pass without validation,
85+ -- new INSERT/UPDATE are checked. Run `VALIDATE CONSTRAINT` after audit cleanup.
86+ ALTER TABLE vault_documents
87+ ADD CONSTRAINT vault_documents_scope_consistency
88+ CHECK (
89+ (scope = ' personal' AND agent_id IS NOT NULL AND team_id IS NULL ) OR
90+ (scope = ' team' AND team_id IS NOT NULL AND agent_id IS NULL ) OR
91+ (scope = ' shared' AND agent_id IS NULL AND team_id IS NULL ) OR
92+ scope = ' custom'
93+ ) NOT VALID;
0 commit comments