ALTER TABLE spec_events ADD COLUMN IF NOT EXISTS prompt_version UUID ALTER TABLE spec_events ADD COLUMN IF NOT EXISTS source_document_id UUID ALTER TABLE spec_events ADD COLUMN IF NOT EXISTS raw_llm_response JSONB SELECT COUNT(*) as cnt FROM spec_events WHERE supplement_id = SELECT pg_advisory_xact_lock(hashtext()) SELECT COALESCE(MAX(seq), 0) as m FROM spec_events WHERE contract_id = INSERT INTO spec_events (contract_id, supplement_id, seq, action, target_hash, comment, status, prompt_version, source_document_id, raw_llm_response) SELECT , , + ROW_NUMBER() OVER (), 'DELETE', name_hash, 'full_replace', 'applied', ::uuidNULL, ::uuidNULL, ::jsonbNULL FROM spec_current WHERE contract_id = SELECT COUNT(*) as cnt FROM spec_current WHERE contract_id = DELETE FROM spec_current WHERE contract_id = SELECT name_hash, price, qty, sum, date_start FROM spec_current WHERE contract_id = AND name_hash IN (,) INSERT INTO spec_events (contract_id, supplement_id, seq, action, new_values, comment, status, prompt_version, source_document_id, raw_llm_response) VALUES ( , , , 'ADD', ::jsonb, , 'applied', ::uuidNULL, ::uuidNULL, ::jsonbNULL ) RETURNING id INSERT INTO spec_current (contract_id, name_hash, name, price, qty, sum, date_start, last_event_id) VALUES ( , md5(lower(trim(regexp_replace(translate(normalize(, NFKC), '–—‑−«»""', '------""'), '\s+', ' ', 'g'))) || coalesce(, '')), , , , , , ) INSERT INTO spec_events (contract_id, supplement_id, seq, action, new_values, comment, status, prompt_version, source_document_id, raw_llm_response) VALUES ( , , , 'UNRESOLVED', ::jsonb, , 'pending', ::uuidNULL, ::uuidNULL, ::jsonbNULL ) INSERT INTO spec_events (contract_id, supplement_id, seq, action, target_hash, new_values, comment, status, prompt_version, source_document_id, raw_llm_response) VALUES ( , , , 'UPDATE', , ::jsonb, , 'applied', ::uuidNULL, ::uuidNULL, ::jsonbNULL ) RETURNING id UPDATE spec_current SET price = , qty = , sum = , date_start = , last_event_id = , updated_at = now() WHERE contract_id = AND name_hash = INSERT INTO spec_events (contract_id, supplement_id, seq, action, target_hash, comment, status, prompt_version, source_document_id, raw_llm_response) VALUES ( , , , 'DELETE', , , 'applied', ::uuidNULL, ::uuidNULL, ::jsonbNULL ) DELETE FROM spec_current WHERE contract_id = AND name_hash = INSERT INTO spec_events (contract_id, supplement_id, seq, action, new_values, comment, status, prompt_version, source_document_id, raw_llm_response) VALUES ( , , , 'UNRESOLVED', ::jsonb, , 'pending', ::uuidNULL, ::uuidNULL, ::jsonbNULL ) #serializeJSON(result)#