@miniaxolotl/grove-server 1.11.24 → 1.11.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/migrate.js CHANGED
@@ -4,6 +4,663 @@ import { createRequire as __groveCreateRequire } from "node:module"; const requi
4
4
  import knex from "knex";
5
5
  import { Model, knexSnakeCaseMappers } from "objection";
6
6
 
7
+ // lib/database/src/lifecycle-migration.ts
8
+ var lifecycleReconciliation = {
9
+ name: "20261119_048_lifecycle_reconciliation",
10
+ async up(db2) {
11
+ await db2.raw(`
12
+ -- No admission row is installed by migration or runtime. The separately
13
+ -- approved operator must bind the new immutable source and phase receipt.
14
+ CREATE TABLE lifecycle_release_control (
15
+ singleton boolean PRIMARY KEY DEFAULT true CHECK(singleton),
16
+ release_hash text NOT NULL CHECK(release_hash ~ '^[a-f0-9]{64}$'),
17
+ receipt_hash text NOT NULL CHECK(receipt_hash ~ '^[a-f0-9]{64}$'),
18
+ generation bigint NOT NULL DEFAULT 0 CHECK(generation>=0),
19
+ phase text NOT NULL DEFAULT 'reconcile' CHECK(phase IN ('reconcile','handoff','released','public')),
20
+ approval_hash text CHECK(approval_hash ~ '^[a-f0-9]{64}$'), approved_generation bigint,
21
+ approved_at timestamptz, handoff_evidence jsonb,
22
+ public_hash text CHECK(public_hash ~ '^[a-f0-9]{64}$'), public_evidence jsonb,
23
+ CHECK((approval_hash IS NULL)=(approved_generation IS NULL))
24
+ );
25
+ CREATE TABLE lifecycle_events (
26
+ provider text NOT NULL CHECK(provider IN ('clerk','stripe')),
27
+ event_id text CHECK(length(event_id) BETWEEN 1 AND 255),
28
+ event_hash text NOT NULL CHECK(event_hash ~ '^[a-f0-9]{64}$'),
29
+ account_id uuid REFERENCES accounts(id),
30
+ fingerprint text NOT NULL CHECK(fingerprint ~ '^[a-f0-9]{64}$'),
31
+ event_type text NOT NULL CHECK(length(event_type) BETWEEN 1 AND 100),
32
+ event_at bigint NOT NULL CHECK(event_at>0),
33
+ received_at timestamptz NOT NULL DEFAULT now(),
34
+ PRIMARY KEY(provider,event_hash)
35
+ );
36
+ -- Only versions and scoped IDs are staged; no customer body, address,
37
+ -- subscription metadata or credential is copied into the inbox/outbox.
38
+ CREATE TABLE lifecycle_billing_state (
39
+ account_id uuid PRIMARY KEY REFERENCES accounts(id),
40
+ generation bigint NOT NULL DEFAULT 0 CHECK(generation>=0),
41
+ reconciled_generation bigint NOT NULL DEFAULT 0 CHECK(reconciled_generation>=0),
42
+ remote_hash text CHECK(remote_hash ~ '^[a-f0-9]{64}$'), observed_at timestamptz,
43
+ customer_hash text CHECK(customer_hash ~ '^[a-f0-9]{64}$'), authority_status text,
44
+ verified_release text, verified_receipt text
45
+ );
46
+ ALTER TABLE lifecycle_events ENABLE ROW LEVEL SECURITY;
47
+ ALTER TABLE lifecycle_billing_state ENABLE ROW LEVEL SECURITY;
48
+ ALTER TABLE lifecycle_release_control ENABLE ROW LEVEL SECURITY;
49
+ CREATE TABLE lifecycle_billing_effects (
50
+ account_id uuid NOT NULL REFERENCES accounts(id),
51
+ operation text NOT NULL CHECK(operation IN ('cancel','expire')),
52
+ remote_id text CHECK(remote_id ~ '^[a-zA-Z0-9_-]{1,255}$'),
53
+ target_hash text NOT NULL CHECK(target_hash ~ '^[a-f0-9]{64}$'),
54
+ state text NOT NULL DEFAULT 'uncertain' CHECK(state IN ('uncertain','confirmed')),
55
+ created_at timestamptz NOT NULL DEFAULT now(), confirmed_at timestamptz,
56
+ PRIMARY KEY(account_id,operation,target_hash),
57
+ CHECK(state='confirmed' OR remote_id IS NOT NULL)
58
+ );
59
+ ALTER TABLE lifecycle_billing_effects ENABLE ROW LEVEL SECURITY;
60
+ CREATE INDEX lifecycle_events_retention ON lifecycle_events(received_at) WHERE event_id IS NOT NULL;
61
+ CREATE INDEX lifecycle_events_erasure ON lifecycle_events(account_id) WHERE event_id IS NOT NULL;
62
+ CREATE INDEX lifecycle_effects_retention ON lifecycle_billing_effects(confirmed_at) WHERE state='confirmed' AND remote_id IS NOT NULL;
63
+ ALTER TABLE background_tasks DROP CONSTRAINT background_tasks_kind_check;
64
+ ALTER TABLE background_tasks ADD CONSTRAINT background_tasks_kind_check CHECK(kind IN
65
+ ('export','account_cleanup','retention_cleanup','artifact_cleanup','model_backfill','import','connector_sync',
66
+ 'document_prepare','document_import','conversation_document','speech_transcribe','speech_synthesize','sentence_rewrite','billing_reconcile'));
67
+
68
+ -- Keep this kind out of the ordinary task runner. A dedicated *mode* on
69
+ -- the existing worker/queue stack owns its narrow fenced claim path.
70
+ ALTER FUNCTION grove_task_allowed(background_tasks) RENAME TO grove_task_allowed_before_lifecycle;
71
+ CREATE FUNCTION grove_task_allowed(t background_tasks) RETURNS boolean LANGUAGE sql STABLE
72
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
73
+ SELECT t.kind<>'billing_reconcile' AND grove_task_allowed_before_lifecycle(t)
74
+ $$;
75
+ REVOKE ALL ON FUNCTION grove_task_allowed(background_tasks) FROM PUBLIC;
76
+
77
+ CREATE FUNCTION grove_lifecycle_work_allowed(release_key text,receipt_key text) RETURNS boolean LANGUAGE sql STABLE
78
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
79
+ SELECT EXISTS(SELECT 1 FROM lifecycle_release_control WHERE singleton AND phase IN ('reconcile','released','public')
80
+ AND ((release_hash=release_key AND receipt_hash=receipt_key) OR (phase IN ('released','public') AND release_key=repeat('0',64) AND receipt_key=repeat('0',64))))
81
+ OR (release_key=repeat('0',64) AND receipt_key=repeat('0',64) AND NOT EXISTS(SELECT 1 FROM lifecycle_release_control))
82
+ $$;
83
+ REVOKE ALL ON FUNCTION grove_lifecycle_work_allowed(text,text) FROM PUBLIC;
84
+
85
+ CREATE FUNCTION grove_lifecycle_accept(release_key text, receipt_key text, provider_name text,
86
+ event_key text, body_fingerprint text, event_kind text, subject_key text, occurred_at bigint, disabled_value boolean)
87
+ RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
88
+ DECLARE control lifecycle_release_control; prior lifecycle_events; owner_id uuid; version bigint;
89
+ previous_scope text; old_authority subject_authority;
90
+ BEGIN
91
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
92
+ IF NOT (grove_lifecycle_work_allowed(release_key,receipt_key) OR coalesce(
93
+ (control.phase='handoff' AND control.release_hash=release_key AND control.receipt_hash=receipt_key),false)) THEN
94
+ RAISE EXCEPTION 'lifecycle release fence';
95
+ END IF;
96
+ IF provider_name NOT IN ('clerk','stripe') OR body_fingerprint !~ '^[a-f0-9]{64}$'
97
+ OR length(event_key) NOT BETWEEN 1 AND 255 OR length(subject_key) NOT BETWEEN 1 AND 255
98
+ OR occurred_at<=0 OR occurred_at>extract(epoch FROM clock_timestamp())*1000+300000
99
+ OR disabled_value IS NULL THEN RAISE EXCEPTION 'invalid lifecycle command'; END IF;
100
+ SELECT * INTO prior FROM lifecycle_events WHERE provider=provider_name AND event_hash=encode(sha256(convert_to(event_key,'UTF8')),'hex');
101
+ IF FOUND THEN
102
+ IF prior.fingerprint<>body_fingerprint OR prior.event_type<>event_kind OR prior.event_at<>occurred_at THEN
103
+ RAISE EXCEPTION 'lifecycle replay conflict';
104
+ END IF;
105
+ RETURN false;
106
+ END IF;
107
+ IF provider_name='clerk' THEN
108
+ IF event_kind NOT IN ('user.created','user.updated','user.deleted','session.revoked','session.ended','session.removed') THEN
109
+ RAISE EXCEPTION 'invalid lifecycle command'; END IF;
110
+ -- Serialize with ordinary identity authorization and preserve deletion
111
+ -- forever; at an equal timestamp disabled wins over reactivation.
112
+ PERFORM pg_advisory_xact_lock(hashtextextended(subject_key,1));
113
+ SELECT * INTO old_authority FROM subject_authority WHERE subject=subject_key;
114
+ PERFORM grove_webhook(event_key,event_kind,subject_key,occurred_at);
115
+ IF event_kind IN ('user.created','user.updated') AND (old_authority.subject IS NULL
116
+ OR old_authority.event_at<occurred_at OR (old_authority.event_at=occurred_at AND disabled_value)) THEN
117
+ PERFORM grove_user_state(subject_key,occurred_at,disabled_value);
118
+ END IF;
119
+ IF event_kind LIKE 'user.%' THEN SELECT id INTO owner_id FROM accounts WHERE clerk_subject=subject_key FOR UPDATE; END IF;
120
+ ELSE
121
+ IF event_kind !~ '^(customer\\.subscription\\.(created|updated|deleted)|checkout\\.session\\.(completed|async_payment_succeeded|async_payment_failed)|invoice\\.(paid|payment_failed))$'
122
+ THEN RAISE EXCEPTION 'invalid lifecycle command'; END IF;
123
+ SELECT a.id INTO owner_id FROM accounts a JOIN billing_customers c ON c.account_id=a.id
124
+ WHERE c.customer_id=subject_key FOR UPDATE OF a;
125
+ IF NOT FOUND THEN RAISE EXCEPTION 'unknown billing tenant'; END IF;
126
+ END IF;
127
+ IF owner_id IS NOT NULL AND EXISTS(SELECT 1 FROM billing_customers WHERE account_id=owner_id AND customer_id IS NOT NULL) THEN
128
+ INSERT INTO lifecycle_billing_state(account_id,generation) VALUES(owner_id,1)
129
+ ON CONFLICT(account_id) DO UPDATE SET generation=lifecycle_billing_state.generation+1 RETURNING generation INTO version;
130
+ previous_scope:=current_setting('grove.account_id',true);
131
+ PERFORM set_config('grove.account_id',owner_id::text,true);
132
+ INSERT INTO background_tasks(account_id,kind,dedupe_key,payload)
133
+ VALUES(owner_id,'billing_reconcile','lifecycle:'||version::text,jsonb_build_object('generation',version,'authorityStatus',(SELECT status FROM accounts WHERE id=owner_id)));
134
+ IF provider_name='stripe' THEN INSERT INTO billing_events(id,account_id) VALUES(event_key,owner_id) ON CONFLICT DO NOTHING; END IF;
135
+ PERFORM set_config('grove.account_id',coalesce(previous_scope,''),true);
136
+ END IF;
137
+ INSERT INTO lifecycle_events(provider,event_id,event_hash,account_id,fingerprint,event_type,event_at)
138
+ VALUES(provider_name,CASE WHEN EXISTS(SELECT 1 FROM accounts WHERE id=owner_id AND status='deleted') THEN NULL ELSE event_key END,
139
+ encode(sha256(convert_to(event_key,'UTF8')),'hex'),owner_id,body_fingerprint,event_kind,occurred_at);
140
+ UPDATE lifecycle_release_control SET generation=generation+1,
141
+ phase=CASE WHEN phase='handoff' THEN 'reconcile' ELSE phase END,
142
+ approval_hash=CASE WHEN phase='handoff' THEN NULL ELSE approval_hash END,
143
+ approved_generation=CASE WHEN phase='handoff' THEN NULL ELSE approved_generation END,
144
+ approved_at=CASE WHEN phase='handoff' THEN NULL ELSE approved_at END,
145
+ handoff_evidence=CASE WHEN phase='handoff' THEN NULL ELSE handoff_evidence END WHERE singleton;
146
+ RETURN true;
147
+ END $$;
148
+ REVOKE ALL ON FUNCTION grove_lifecycle_accept(text,text,text,text,text,text,text,bigint,boolean) FROM PUBLIC;
149
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_accept(text,text,text,text,text,text,text,bigint,boolean) TO grove_runtime;
150
+
151
+ CREATE FUNCTION grove_lifecycle_notify(provider_name text,event_key text,body_fingerprint text,event_kind text,subject_key text,occurred_at bigint,disabled_value boolean)
152
+ RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
153
+ DECLARE control lifecycle_release_control;
154
+ BEGIN
155
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
156
+ IF FOUND AND control.phase NOT IN ('released','public') THEN RAISE EXCEPTION 'lifecycle release fence'; END IF;
157
+ RETURN grove_lifecycle_accept(coalesce(control.release_hash,repeat('0',64)),coalesce(control.receipt_hash,repeat('0',64)),
158
+ provider_name,event_key,body_fingerprint,event_kind,subject_key,occurred_at,disabled_value);
159
+ END $$;
160
+ REVOKE ALL ON FUNCTION grove_lifecycle_notify(text,text,text,text,text,bigint,boolean) FROM PUBLIC;
161
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_notify(text,text,text,text,text,bigint,boolean) TO grove_runtime;
162
+
163
+ CREATE FUNCTION grove_lifecycle_valid(release_key text, receipt_key text, wanted uuid, token uuid, expected_status text)
164
+ RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
165
+ SELECT EXISTS(SELECT 1 FROM background_tasks t
166
+ JOIN accounts a ON a.id=t.account_id JOIN lifecycle_billing_state s ON s.account_id=a.id
167
+ WHERE grove_lifecycle_work_allowed(release_key,receipt_key)
168
+ AND t.id=wanted AND t.kind='billing_reconcile' AND t.status='running' AND t.lease_id=token AND t.lease_until>clock_timestamp()
169
+ AND t.created_at>clock_timestamp()-interval '23 hours' AND s.generation=(t.payload->>'generation')::bigint
170
+ AND a.status=expected_status AND (expected_status<>'active' OR (a.deleted_at IS NULL AND NOT EXISTS
171
+ (SELECT 1 FROM subject_authority sa WHERE sa.subject=a.clerk_subject AND (sa.deleted OR sa.disabled))))
172
+ AND EXISTS(SELECT 1 FROM billing_customers b WHERE b.account_id=a.id AND b.customer_id IS NOT NULL
173
+ AND t.cursor->>'customerHash'=encode(sha256(convert_to(b.customer_id,'UTF8')),'hex')))
174
+ $$;
175
+ CREATE FUNCTION grove_lifecycle_claim(release_key text, receipt_key text, wanted uuid DEFAULT NULL)
176
+ RETURNS TABLE(task_id uuid,account_id uuid,lease_id uuid,generation bigint,customer_id text,account_status text)
177
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
178
+ DECLARE control lifecycle_release_control; selected background_tasks; owner_status text;
179
+ BEGIN
180
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
181
+ IF NOT grove_lifecycle_work_allowed(release_key,receipt_key) THEN
182
+ IF control.phase='handoff' AND control.release_hash=release_key AND control.receipt_hash=receipt_key THEN RETURN; END IF;
183
+ RAISE EXCEPTION 'lifecycle release fence'; END IF;
184
+ IF control.singleton IS NULL THEN PERFORM pg_advisory_xact_lock(hashtextextended('lifecycle-claim',68142020)); END IF;
185
+ IF control.phase NOT IN ('reconcile','released','public') THEN RETURN; END IF;
186
+ UPDATE background_tasks SET status='failed',error_code='lifecycle_exhausted',finished_at=clock_timestamp(),updated_at=clock_timestamp(),
187
+ lease_id=NULL,lease_until=NULL,dispatch_id=NULL,dispatch_until=NULL WHERE id IN(
188
+ SELECT t.id FROM background_tasks t WHERE t.kind='billing_reconcile' AND t.status IN ('pending','running')
189
+ AND (t.attempts>=5 OR t.created_at<=clock_timestamp()-interval '23 hours')
190
+ AND (t.lease_until IS NULL OR t.lease_until<clock_timestamp()) ORDER BY t.created_at LIMIT 1000 FOR UPDATE SKIP LOCKED);
191
+ IF (SELECT count(*) FROM background_tasks WHERE kind='billing_reconcile' AND lease_until>clock_timestamp())>=8 THEN RETURN; END IF;
192
+ SELECT t.* INTO selected FROM background_tasks t JOIN lifecycle_billing_state s ON s.account_id=t.account_id
193
+ WHERE t.kind='billing_reconcile' AND (wanted IS NULL OR t.id=wanted) AND t.status IN ('pending','running')
194
+ AND t.attempts<5 AND t.created_at>clock_timestamp()-interval '23 hours' AND t.due_at<=clock_timestamp()
195
+ AND (t.lease_until IS NULL OR t.lease_until<clock_timestamp()) AND s.generation=(t.payload->>'generation')::bigint
196
+ AND NOT EXISTS(SELECT 1 FROM background_tasks busy WHERE busy.account_id=t.account_id AND busy.kind='billing_reconcile' AND busy.lease_until>clock_timestamp())
197
+ ORDER BY t.due_at,t.id LIMIT 1;
198
+ IF NOT FOUND THEN RETURN; END IF;
199
+ SELECT status INTO owner_status FROM accounts WHERE id=selected.account_id FOR UPDATE;
200
+ -- Match ingress lock order: control -> account -> task. No lock or SQL
201
+ -- transaction survives the claim, preflight or provider I/O boundary.
202
+ PERFORM 1 FROM background_tasks t WHERE t.id=selected.id AND t.status IN ('pending','running')
203
+ AND (t.lease_until IS NULL OR t.lease_until<clock_timestamp()) FOR UPDATE;
204
+ IF NOT FOUND THEN RETURN; END IF;
205
+ RETURN QUERY WITH leased AS (
206
+ UPDATE background_tasks SET status='running',lease_id=gen_random_uuid(),lease_until=clock_timestamp()+interval '120 seconds',
207
+ attempts=attempts+1,claimed_at=clock_timestamp(),updated_at=clock_timestamp(),
208
+ cursor=jsonb_build_object('customerHash',(SELECT encode(sha256(convert_to(bc.customer_id,'UTF8')),'hex') FROM billing_customers bc WHERE bc.account_id=selected.account_id))
209
+ WHERE id=selected.id RETURNING *
210
+ ) SELECT l.id,l.account_id,l.lease_id,(l.payload->>'generation')::bigint,b.customer_id,owner_status
211
+ FROM leased l JOIN billing_customers b ON b.account_id=l.account_id WHERE b.customer_id IS NOT NULL;
212
+ END $$;
213
+ REVOKE ALL ON FUNCTION grove_lifecycle_valid(text,text,uuid,uuid,text),grove_lifecycle_claim(text,text,uuid) FROM PUBLIC;
214
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_valid(text,text,uuid,uuid,text),grove_lifecycle_claim(text,text,uuid) TO grove_worker;
215
+
216
+ CREATE FUNCTION grove_lifecycle_complete(release_key text, receipt_key text, wanted uuid, token uuid, expected_status text, subscriptions jsonb, remote_fingerprint text, open_sessions integer)
217
+ RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
218
+ DECLARE selected background_tasks; previous_scope text; control lifecycle_release_control;
219
+ BEGIN
220
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
221
+ SELECT * INTO selected FROM background_tasks WHERE id=wanted;
222
+ IF NOT FOUND THEN RETURN false; END IF;
223
+ PERFORM 1 FROM accounts WHERE id=selected.account_id FOR UPDATE;
224
+ PERFORM 1 FROM background_tasks WHERE id=wanted FOR UPDATE;
225
+ IF NOT grove_lifecycle_valid(release_key,receipt_key,wanted,token,expected_status) THEN RETURN false; END IF;
226
+ IF remote_fingerprint !~ '^[a-f0-9]{64}$'
227
+ OR jsonb_typeof(subscriptions)<>'array' OR jsonb_array_length(subscriptions)>1000 THEN RETURN false; END IF;
228
+ IF expected_status IN ('deleting','deleted') AND (open_sessions<>0 OR EXISTS(SELECT 1 FROM jsonb_array_elements(subscriptions) e
229
+ WHERE e->>'status' NOT IN ('canceled','incomplete_expired'))) THEN RETURN false; END IF;
230
+ IF EXISTS(SELECT 1 FROM lifecycle_billing_effects WHERE account_id=selected.account_id AND state='uncertain') THEN RETURN false; END IF;
231
+ IF EXISTS(SELECT 1 FROM jsonb_array_elements(subscriptions) e WHERE e->>'customer' IS DISTINCT FROM
232
+ (SELECT customer_id FROM billing_customers WHERE account_id=selected.account_id)) THEN RETURN false; END IF;
233
+ previous_scope:=current_setting('grove.account_id',true);
234
+ PERFORM set_config('grove.account_id',selected.account_id::text,true);
235
+ IF EXISTS(SELECT 1 FROM jsonb_array_elements(subscriptions) e JOIN billing_subscriptions b ON b.id=e->>'id'
236
+ WHERE b.account_id<>selected.account_id OR b.customer_id<>e->>'customer') THEN RAISE EXCEPTION 'foreign billing evidence'; END IF;
237
+ INSERT INTO billing_subscriptions(id,account_id,customer_id,price_id,product_id,status,period_end,cancel_at_period_end)
238
+ SELECT e->>'id',selected.account_id,e->>'customer',e->>'price',e->>'product',e->>'status',
239
+ to_timestamp((e->>'periodEnd')::double precision),(e->>'cancelAtPeriodEnd')::boolean FROM jsonb_array_elements(subscriptions) e
240
+ ON CONFLICT(id) DO UPDATE SET price_id=EXCLUDED.price_id,product_id=EXCLUDED.product_id,status=EXCLUDED.status,
241
+ period_end=EXCLUDED.period_end,cancel_at_period_end=EXCLUDED.cancel_at_period_end,updated_at=clock_timestamp();
242
+ UPDATE billing_subscriptions SET status='canceled',updated_at=clock_timestamp()
243
+ WHERE account_id=selected.account_id AND customer_id=(SELECT customer_id FROM billing_customers WHERE account_id=selected.account_id)
244
+ AND id NOT IN(SELECT e->>'id' FROM jsonb_array_elements(subscriptions) e);
245
+ UPDATE billing_trials SET subscription_id=(SELECT e->>'id' FROM jsonb_array_elements(subscriptions) e WHERE e->>'status'='trialing' ORDER BY e->>'id' LIMIT 1)
246
+ WHERE account_id=selected.account_id AND subscription_id IS NULL AND EXISTS(SELECT 1 FROM jsonb_array_elements(subscriptions) e WHERE e->>'status'='trialing');
247
+ UPDATE lifecycle_billing_state SET reconciled_generation=generation,remote_hash=remote_fingerprint,observed_at=clock_timestamp(),
248
+ customer_hash=selected.cursor->>'customerHash',authority_status=expected_status,
249
+ verified_release=coalesce(control.release_hash,release_key),verified_receipt=coalesce(control.receipt_hash,receipt_key) WHERE account_id=selected.account_id;
250
+ UPDATE background_tasks SET status='succeeded',finished_at=clock_timestamp(),updated_at=clock_timestamp(),lease_id=NULL,lease_until=NULL,
251
+ result=jsonb_build_object('generation',payload->'generation','remoteHash',remote_fingerprint),error_code=NULL WHERE id=wanted;
252
+ UPDATE background_tasks SET status='cancelled',finished_at=clock_timestamp(),lease_id=NULL,lease_until=NULL WHERE account_id=selected.account_id AND kind='billing_reconcile'
253
+ AND status IN ('pending','running') AND (payload->>'generation')::bigint<(selected.payload->>'generation')::bigint;
254
+ PERFORM set_config('grove.account_id',coalesce(previous_scope,''),true);
255
+ RETURN true;
256
+ END $$;
257
+ CREATE FUNCTION grove_lifecycle_failure(release_key text, receipt_key text, wanted uuid, token uuid)
258
+ RETURNS void LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
259
+ UPDATE background_tasks t SET status=CASE WHEN attempts>=5 OR created_at<=clock_timestamp()-interval '23 hours' THEN 'failed' ELSE 'pending' END,
260
+ error_code='lifecycle_reconciliation_failed',lease_id=NULL,lease_until=NULL,dispatch_id=NULL,dispatch_until=NULL,dispatched_at=NULL,
261
+ due_at=clock_timestamp()+least(3600,5*power(2,attempts)) * interval '1 second',updated_at=clock_timestamp()
262
+ WHERE t.id=wanted AND t.kind='billing_reconcile' AND t.lease_id=token AND t.lease_until>clock_timestamp()
263
+ AND grove_lifecycle_work_allowed(release_key,receipt_key)
264
+ $$;
265
+ REVOKE ALL ON FUNCTION grove_lifecycle_complete(text,text,uuid,uuid,text,jsonb,text,integer),grove_lifecycle_failure(text,text,uuid,uuid) FROM PUBLIC;
266
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_complete(text,text,uuid,uuid,text,jsonb,text,integer),grove_lifecycle_failure(text,text,uuid,uuid) TO grove_worker;
267
+
268
+ CREATE FUNCTION grove_lifecycle_effects(release_key text,receipt_key text,wanted uuid,token uuid,expected_status text)
269
+ RETURNS TABLE(operation text,remote_id text,state text) LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
270
+ SELECT e.operation,e.remote_id,e.state FROM lifecycle_billing_effects e JOIN background_tasks t ON t.account_id=e.account_id
271
+ WHERE t.id=wanted AND grove_lifecycle_valid(release_key,receipt_key,wanted,token,expected_status)
272
+ $$;
273
+ CREATE FUNCTION grove_lifecycle_effect(release_key text,receipt_key text,wanted uuid,token uuid,expected_status text,effect_kind text,target text,confirmed boolean)
274
+ RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
275
+ DECLARE selected background_tasks;
276
+ BEGIN
277
+ PERFORM 1 FROM lifecycle_release_control WHERE singleton FOR UPDATE;
278
+ SELECT * INTO selected FROM background_tasks WHERE id=wanted;
279
+ IF NOT FOUND THEN RETURN false; END IF;
280
+ PERFORM 1 FROM accounts WHERE id=selected.account_id FOR UPDATE;
281
+ PERFORM 1 FROM background_tasks WHERE id=wanted FOR UPDATE;
282
+ IF NOT grove_lifecycle_valid(release_key,receipt_key,wanted,token,expected_status)
283
+ OR expected_status NOT IN ('deleting','deleted') OR effect_kind NOT IN ('cancel','expire')
284
+ OR target !~ '^[a-zA-Z0-9_-]{1,255}$' THEN RETURN false; END IF;
285
+ IF confirmed THEN
286
+ UPDATE lifecycle_billing_effects SET state='confirmed',confirmed_at=clock_timestamp()
287
+ WHERE account_id=selected.account_id AND operation=effect_kind AND target_hash=encode(sha256(convert_to(target,'UTF8')),'hex');
288
+ RETURN FOUND;
289
+ END IF;
290
+ -- This marker commits BEFORE the remote call. A crash at either side of
291
+ -- the boundary demands read-only reconciliation, not a second cancel.
292
+ INSERT INTO lifecycle_billing_effects(account_id,operation,remote_id,target_hash) VALUES(selected.account_id,effect_kind,target,encode(sha256(convert_to(target,'UTF8')),'hex')) ON CONFLICT DO NOTHING;
293
+ RETURN FOUND;
294
+ END $$;
295
+ REVOKE ALL ON FUNCTION grove_lifecycle_effects(text,text,uuid,uuid,text),grove_lifecycle_effect(text,text,uuid,uuid,text,text,text,boolean) FROM PUBLIC;
296
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_effects(text,text,uuid,uuid,text),grove_lifecycle_effect(text,text,uuid,uuid,text,text,text,boolean) TO grove_worker;
297
+
298
+ CREATE FUNCTION grove_lifecycle_status(release_key text,receipt_key text) RETURNS jsonb LANGUAGE sql STABLE
299
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
300
+ WITH control AS (SELECT * FROM lifecycle_release_control WHERE singleton AND release_hash=release_key AND receipt_hash=receipt_key),
301
+ customers AS (SELECT b.account_id,s.generation,s.reconciled_generation,s.remote_hash,s.observed_at,
302
+ s.customer_hash=encode(sha256(convert_to(b.customer_id,'UTF8')),'hex') AND s.authority_status=a.status
303
+ AND s.verified_release=release_key AND s.verified_receipt=receipt_key
304
+ AND (a.status<>'active' OR (a.deleted_at IS NULL AND NOT EXISTS(SELECT 1 FROM subject_authority sa WHERE sa.subject=a.clerk_subject AND (sa.deleted OR sa.disabled)))) AS scoped
305
+ FROM billing_customers b JOIN accounts a ON a.id=b.account_id
306
+ LEFT JOIN lifecycle_billing_state s ON s.account_id=b.account_id WHERE b.customer_id IS NOT NULL),
307
+ counts AS (SELECT count(*) AS customers,count(*) FILTER(WHERE generation=reconciled_generation AND remote_hash IS NOT NULL
308
+ AND scoped AND observed_at>clock_timestamp()-interval '10 minutes') AS verified FROM customers),
309
+ pending AS (SELECT count(*) AS count FROM background_tasks t JOIN lifecycle_billing_state s ON s.account_id=t.account_id
310
+ WHERE t.kind='billing_reconcile' AND t.status<>'succeeded' AND (t.payload->>'generation')::bigint=s.generation),
311
+ uncertain AS (SELECT count(*) AS count FROM lifecycle_billing_effects WHERE state='uncertain')
312
+ SELECT jsonb_build_object('release',release_hash,'receipt',receipt_hash,'generation',control.generation::text,
313
+ 'customers',counts.customers,'remoteVerified',counts.verified,'pending',pending.count,'uncertain',uncertain.count,
314
+ 'caughtUp',counts.customers=counts.verified AND pending.count=0 AND uncertain.count=0,
315
+ 'authorityHash',encode(sha256(convert_to(jsonb_build_object(
316
+ 'accounts',(SELECT coalesce(jsonb_agg(jsonb_build_array(id,status,deleted_at,provider_deleted_at) ORDER BY id),'[]') FROM accounts),
317
+ 'subjects',(SELECT coalesce(jsonb_agg(to_jsonb(s) ORDER BY subject),'[]') FROM subject_authority s),
318
+ 'sessions',(SELECT coalesce(jsonb_agg(to_jsonb(r) ORDER BY id),'[]') FROM session_revocations r),
319
+ 'events',(SELECT coalesce(jsonb_agg(to_jsonb(e) ORDER BY provider,event_hash),'[]') FROM lifecycle_events e))::text,'UTF8')),'hex'),
320
+ 'remoteHash',encode(sha256(convert_to((SELECT coalesce(jsonb_agg(to_jsonb(s) ORDER BY account_id),'[]') FROM lifecycle_billing_state s)::text,'UTF8')),'hex'))
321
+ FROM control,counts,pending,uncertain
322
+ $$;
323
+ CREATE FUNCTION grove_lifecycle_proof(release_key text,receipt_key text) RETURNS jsonb LANGUAGE sql STABLE
324
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
325
+ SELECT grove_lifecycle_status(release_key,receipt_key) || jsonb_build_object('control',jsonb_build_object(
326
+ 'phase',phase,'approvalHash',approval_hash,'publicHash',public_hash)) FROM lifecycle_release_control
327
+ WHERE singleton AND release_hash=release_key AND receipt_hash=receipt_key
328
+ $$;
329
+ REVOKE ALL ON FUNCTION grove_lifecycle_proof(text,text) FROM PUBLIC;
330
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_proof(text,text) TO grove_runtime,grove_worker;
331
+ CREATE FUNCTION grove_lifecycle_handoff(release_key text,receipt_key text,expected_generation bigint,approval_key text)
332
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
333
+ DECLARE control lifecycle_release_control; evidence jsonb;
334
+ BEGIN
335
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
336
+ IF NOT FOUND OR control.release_hash<>release_key OR control.receipt_hash<>receipt_key
337
+ OR control.generation<>expected_generation THEN RAISE EXCEPTION 'lifecycle generation fence'; END IF;
338
+ IF approval_key !~ '^[a-f0-9]{64}$' OR control.phase<>'reconcile' THEN RAISE EXCEPTION 'lifecycle approval fence'; END IF;
339
+ evidence:=grove_lifecycle_status(release_key,receipt_key);
340
+ IF evidence->>'caughtUp' IS DISTINCT FROM 'true' THEN RAISE EXCEPTION 'lifecycle not reconciled'; END IF;
341
+ UPDATE lifecycle_release_control SET phase='handoff',approval_hash=approval_key,approved_generation=generation,
342
+ approved_at=clock_timestamp(),handoff_evidence=evidence WHERE singleton;
343
+ RETURN evidence;
344
+ END $$;
345
+ CREATE FUNCTION grove_lifecycle_release(release_key text,receipt_key text,approval_key text)
346
+ RETURNS boolean LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
347
+ DECLARE control lifecycle_release_control; evidence jsonb;
348
+ BEGIN
349
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
350
+ IF NOT FOUND OR control.release_hash<>release_key OR control.receipt_hash<>receipt_key
351
+ OR control.approval_hash IS DISTINCT FROM approval_key THEN RETURN false; END IF;
352
+ IF control.phase IN ('released','public') THEN RETURN true; END IF;
353
+ IF control.phase<>'handoff' OR control.approved_generation IS DISTINCT FROM control.generation
354
+ OR control.approved_at<clock_timestamp()-interval '10 minutes' OR control.approved_at IS NULL THEN RETURN false; END IF;
355
+ evidence:=grove_lifecycle_status(release_key,receipt_key);
356
+ IF evidence IS DISTINCT FROM control.handoff_evidence OR evidence->>'caughtUp' IS DISTINCT FROM 'true' THEN RETURN false; END IF;
357
+ -- This commit is the release linearization point, before runtime import.
358
+ -- Events before it invalidate handoff; events after it use ordinary
359
+ -- authority/deletion fences and the same durable reconciliation path.
360
+ UPDATE lifecycle_release_control SET phase='released' WHERE singleton;
361
+ RETURN true;
362
+ END $$;
363
+ REVOKE ALL ON FUNCTION grove_lifecycle_status(text,text),grove_lifecycle_handoff(text,text,bigint,text),grove_lifecycle_release(text,text,text) FROM PUBLIC;
364
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_status(text,text),grove_lifecycle_release(text,text,text) TO grove_runtime,grove_worker;
365
+ -- handoff intentionally remains migration/operator-owner only.
366
+ CREATE FUNCTION grove_lifecycle_approve(release_key text,receipt_key text,expected_generation bigint,approval_key text,expected_evidence jsonb)
367
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
368
+ DECLARE control lifecycle_release_control;
369
+ BEGIN
370
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
371
+ IF NOT FOUND OR control.release_hash<>release_key OR control.receipt_hash<>receipt_key THEN RAISE EXCEPTION 'lifecycle release fence'; END IF;
372
+ IF control.phase IN ('handoff','released','public') AND control.approval_hash=approval_key
373
+ AND control.handoff_evidence=expected_evidence THEN RETURN control.handoff_evidence; END IF;
374
+ IF grove_lifecycle_status(release_key,receipt_key) IS DISTINCT FROM expected_evidence THEN RAISE EXCEPTION 'lifecycle evidence fence'; END IF;
375
+ RETURN grove_lifecycle_handoff(release_key,receipt_key,expected_generation,approval_key);
376
+ END $$;
377
+ REVOKE ALL ON FUNCTION grove_lifecycle_approve(text,text,bigint,text,jsonb) FROM PUBLIC;
378
+
379
+ CREATE FUNCTION grove_lifecycle_bound(release_key text,receipt_key text) RETURNS boolean LANGUAGE sql STABLE
380
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
381
+ SELECT EXISTS(SELECT 1 FROM lifecycle_release_control WHERE singleton AND release_hash=release_key AND receipt_hash=receipt_key)
382
+ $$;
383
+ CREATE FUNCTION grove_lifecycle_release_approved(release_key text,approval_key text) RETURNS boolean LANGUAGE plpgsql
384
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
385
+ DECLARE receipt_key text;
386
+ BEGIN
387
+ SELECT receipt_hash INTO receipt_key FROM lifecycle_release_control WHERE singleton AND release_hash=release_key AND approval_hash=approval_key FOR UPDATE;
388
+ IF NOT FOUND THEN RETURN false; END IF;
389
+ RETURN grove_lifecycle_release(release_key,receipt_key,approval_key);
390
+ END $$;
391
+ CREATE FUNCTION grove_lifecycle_dispatch(release_key text,receipt_key text) RETURNS TABLE(id uuid,dispatch_id uuid)
392
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
393
+ BEGIN
394
+ IF NOT grove_lifecycle_work_allowed(release_key,receipt_key) THEN RETURN; END IF;
395
+ RETURN QUERY UPDATE background_tasks t SET dispatch_id=gen_random_uuid(),dispatch_until=clock_timestamp()+interval '30 seconds'
396
+ WHERE t.id IN(SELECT q.id FROM background_tasks q JOIN lifecycle_billing_state s ON s.account_id=q.account_id
397
+ WHERE q.kind='billing_reconcile' AND q.status IN ('pending','running') AND q.attempts<5
398
+ AND (q.payload->>'generation')::bigint=s.generation AND q.due_at<=clock_timestamp()
399
+ AND q.created_at>clock_timestamp()-interval '23 hours' AND (q.lease_until IS NULL OR q.lease_until<clock_timestamp())
400
+ AND (q.dispatch_until IS NULL OR q.dispatch_until<clock_timestamp())
401
+ AND (q.dispatched_at IS NULL OR q.dispatched_at<clock_timestamp()-interval '15 seconds')
402
+ ORDER BY q.due_at,q.id LIMIT 32 FOR UPDATE OF q SKIP LOCKED) RETURNING t.id,t.dispatch_id;
403
+ END $$;
404
+ REVOKE ALL ON FUNCTION grove_lifecycle_bound(text,text),grove_lifecycle_release_approved(text,text),grove_lifecycle_dispatch(text,text) FROM PUBLIC;
405
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_bound(text,text),grove_lifecycle_release_approved(text,text) TO grove_runtime,grove_worker;
406
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_dispatch(text,text) TO grove_worker;
407
+
408
+ CREATE FUNCTION grove_lifecycle_enroll(release_key text,receipt_key text) RETURNS integer
409
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
410
+ DECLARE control lifecycle_release_control; owner_id uuid; queued integer:=0; previous_scope text; version bigint;
411
+ BEGIN
412
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
413
+ IF NOT grove_lifecycle_work_allowed(release_key,receipt_key) THEN
414
+ IF control.phase='handoff' THEN RETURN 0; END IF;
415
+ RAISE EXCEPTION 'lifecycle release fence'; END IF;
416
+ IF control.phase NOT IN ('reconcile','released','public') THEN RETURN 0; END IF;
417
+ previous_scope:=current_setting('grove.account_id',true);
418
+ -- Restored mappings are discovered in bounded worker batches, not by
419
+ -- remote I/O or a bulk import inside an HTTP request/operator transaction.
420
+ FOR owner_id IN SELECT b.account_id FROM billing_customers b JOIN accounts a ON a.id=b.account_id
421
+ LEFT JOIN lifecycle_billing_state s ON s.account_id=b.account_id
422
+ WHERE b.customer_id IS NOT NULL AND (s.account_id IS NULL OR (s.generation=s.reconciled_generation AND (
423
+ s.observed_at<clock_timestamp()-interval '8 minutes' OR s.customer_hash IS DISTINCT FROM encode(sha256(convert_to(b.customer_id,'UTF8')),'hex')
424
+ OR s.authority_status IS DISTINCT FROM a.status OR s.verified_release IS DISTINCT FROM coalesce(control.release_hash,release_key)
425
+ OR s.verified_receipt IS DISTINCT FROM coalesce(control.receipt_hash,receipt_key))))
426
+ ORDER BY b.account_id LIMIT 32 FOR UPDATE OF a
427
+ LOOP
428
+ INSERT INTO lifecycle_billing_state(account_id,generation) VALUES(owner_id,1) ON CONFLICT(account_id)
429
+ DO UPDATE SET generation=lifecycle_billing_state.generation+1 RETURNING generation INTO version;
430
+ PERFORM set_config('grove.account_id',owner_id::text,true);
431
+ INSERT INTO background_tasks(account_id,kind,dedupe_key,payload) VALUES(owner_id,'billing_reconcile','lifecycle:'||version::text,jsonb_build_object('generation',version,'authorityStatus',(SELECT status FROM accounts WHERE id=owner_id)));
432
+ queued:=queued+1;
433
+ END LOOP;
434
+ PERFORM set_config('grove.account_id',coalesce(previous_scope,''),true);
435
+ IF queued>0 THEN UPDATE lifecycle_release_control SET generation=generation+1 WHERE singleton; END IF;
436
+ RETURN queued;
437
+ END $$;
438
+ REVOKE ALL ON FUNCTION grove_lifecycle_enroll(text,text) FROM PUBLIC;
439
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_enroll(text,text) TO grove_worker;
440
+
441
+ CREATE FUNCTION grove_lifecycle_request(owner_id uuid) RETURNS boolean LANGUAGE plpgsql
442
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
443
+ DECLARE customer text; owner_status text; state lifecycle_billing_state; version bigint; latest background_tasks;
444
+ BEGIN
445
+ IF owner_id::text IS DISTINCT FROM current_setting('grove.account_id',true) THEN RAISE EXCEPTION 'lifecycle tenant fence'; END IF;
446
+ SELECT a.status,b.customer_id INTO owner_status,customer FROM accounts a LEFT JOIN billing_customers b ON b.account_id=a.id WHERE a.id=owner_id FOR UPDATE OF a;
447
+ IF NOT FOUND OR owner_status NOT IN ('deleting','deleted') THEN RAISE EXCEPTION 'deletion authority required'; END IF;
448
+ IF customer IS NULL THEN RETURN true; END IF;
449
+ SELECT * INTO state FROM lifecycle_billing_state WHERE account_id=owner_id;
450
+ IF FOUND THEN
451
+ IF state.generation=state.reconciled_generation AND state.authority_status IN ('deleting','deleted')
452
+ AND state.customer_hash=encode(sha256(convert_to(customer,'UTF8')),'hex')
453
+ AND NOT EXISTS(SELECT 1 FROM lifecycle_billing_effects e WHERE e.account_id=owner_id AND e.state='uncertain') THEN RETURN true; END IF;
454
+ SELECT * INTO latest FROM background_tasks WHERE account_id=owner_id AND kind='billing_reconcile' AND (payload->>'generation')::bigint=state.generation;
455
+ IF FOUND AND latest.payload->>'authorityStatus'=owner_status AND latest.status IN ('pending','running','failed') THEN RETURN false; END IF;
456
+ END IF;
457
+ INSERT INTO lifecycle_billing_state(account_id,generation) VALUES(owner_id,1) ON CONFLICT(account_id)
458
+ DO UPDATE SET generation=lifecycle_billing_state.generation+1 RETURNING generation INTO version;
459
+ INSERT INTO background_tasks(account_id,kind,dedupe_key,payload) VALUES(owner_id,'billing_reconcile','lifecycle:'||version::text,jsonb_build_object('generation',version,'authorityStatus',owner_status));
460
+ RETURN false;
461
+ END $$;
462
+ REVOKE ALL ON FUNCTION grove_lifecycle_request(uuid) FROM PUBLIC;
463
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_request(uuid) TO grove_runtime,grove_worker;
464
+
465
+ CREATE FUNCTION grove_lifecycle_retry(wanted uuid,operation_id uuid) RETURNS uuid LANGUAGE plpgsql
466
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
467
+ DECLARE owner_id uuid; prior background_tasks; created background_tasks; version bigint; owner_status text;
468
+ BEGIN
469
+ owner_id:=nullif(current_setting('grove.account_id',true),'')::uuid;
470
+ SELECT * INTO prior FROM background_tasks WHERE id=wanted AND account_id=owner_id AND kind='billing_reconcile';
471
+ IF NOT FOUND OR operation_id IS NULL THEN RAISE EXCEPTION 'lifecycle tenant fence'; END IF;
472
+ SELECT status INTO owner_status FROM accounts WHERE id=owner_id FOR UPDATE;
473
+ SELECT * INTO created FROM background_tasks WHERE account_id=owner_id AND kind='billing_reconcile' AND dedupe_key='retry:'||operation_id::text;
474
+ IF FOUND THEN
475
+ IF created.payload->>'retryOf' IS DISTINCT FROM wanted::text THEN RAISE EXCEPTION 'lifecycle operation conflict'; END IF;
476
+ RETURN created.id;
477
+ END IF;
478
+ IF prior.status<>'failed' OR prior.lease_until>clock_timestamp() OR NOT EXISTS(SELECT 1 FROM lifecycle_billing_state s
479
+ WHERE s.account_id=owner_id AND s.generation=(prior.payload->>'generation')::bigint) THEN RAISE EXCEPTION 'lifecycle generation fence'; END IF;
480
+ UPDATE lifecycle_billing_state SET generation=generation+1 WHERE account_id=owner_id RETURNING generation INTO version;
481
+ INSERT INTO background_tasks(account_id,kind,dedupe_key,payload) VALUES(owner_id,'billing_reconcile','retry:'||operation_id::text,
482
+ jsonb_build_object('generation',version,'authorityStatus',owner_status,'retryOf',wanted)) RETURNING * INTO created;
483
+ RETURN created.id;
484
+ END $$;
485
+ REVOKE ALL ON FUNCTION grove_lifecycle_retry(uuid,uuid) FROM PUBLIC;
486
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_retry(uuid,uuid) TO grove_runtime,grove_worker;
487
+
488
+ CREATE FUNCTION grove_lifecycle_retention(release_key text,receipt_key text) RETURNS integer LANGUAGE plpgsql
489
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
490
+ DECLARE total integer:=0; changed integer;
491
+ BEGIN
492
+ IF NOT grove_lifecycle_work_allowed(release_key,receipt_key) THEN RETURN 0; END IF;
493
+ UPDATE lifecycle_events SET event_id=NULL WHERE (provider,event_hash) IN(SELECT provider,event_hash FROM lifecycle_events
494
+ WHERE event_id IS NOT NULL AND received_at<clock_timestamp()-interval '30 days' ORDER BY received_at LIMIT 1000 FOR UPDATE SKIP LOCKED);
495
+ GET DIAGNOSTICS total=ROW_COUNT;
496
+ UPDATE lifecycle_billing_effects e SET remote_id=NULL WHERE (e.account_id,e.operation,e.target_hash) IN(
497
+ SELECT r.account_id,r.operation,r.target_hash FROM lifecycle_billing_effects r JOIN lifecycle_billing_state s ON s.account_id=r.account_id
498
+ WHERE r.state='confirmed' AND r.remote_id IS NOT NULL AND r.confirmed_at<clock_timestamp()-interval '30 days'
499
+ AND s.generation=s.reconciled_generation AND NOT EXISTS(SELECT 1 FROM background_tasks t WHERE t.account_id=r.account_id AND t.kind='billing_reconcile' AND t.status IN ('pending','running'))
500
+ ORDER BY r.confirmed_at LIMIT 1000 FOR UPDATE OF r SKIP LOCKED);
501
+ GET DIAGNOSTICS changed=ROW_COUNT;
502
+ RETURN total+changed;
503
+ END $$;
504
+ CREATE FUNCTION grove_lifecycle_erase(owner_id uuid) RETURNS integer LANGUAGE plpgsql
505
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
506
+ DECLARE total integer; changed integer;
507
+ BEGIN
508
+ IF owner_id::text IS DISTINCT FROM current_setting('grove.account_id',true) THEN RAISE EXCEPTION 'lifecycle tenant fence'; END IF;
509
+ PERFORM 1 FROM accounts WHERE id=owner_id FOR UPDATE;
510
+ IF EXISTS(SELECT 1 FROM lifecycle_billing_effects e WHERE e.account_id=owner_id AND e.state='uncertain')
511
+ OR EXISTS(SELECT 1 FROM background_tasks t WHERE t.account_id=owner_id AND t.kind='billing_reconcile' AND t.status IN ('pending','running'))
512
+ OR NOT EXISTS(SELECT 1 FROM accounts WHERE id=owner_id AND status='deleted')
513
+ OR EXISTS(SELECT 1 FROM lifecycle_billing_state s WHERE s.account_id=owner_id AND (s.generation<>s.reconciled_generation OR s.authority_status NOT IN ('deleting','deleted')))
514
+ THEN RAISE EXCEPTION 'unresolved lifecycle prevents erasure'; END IF;
515
+ UPDATE lifecycle_events SET event_id=NULL WHERE (provider,event_hash) IN(SELECT provider,event_hash FROM lifecycle_events
516
+ WHERE account_id=owner_id AND event_id IS NOT NULL LIMIT 1000 FOR UPDATE SKIP LOCKED);
517
+ GET DIAGNOSTICS total=ROW_COUNT;
518
+ UPDATE lifecycle_billing_effects e SET remote_id=NULL WHERE (e.account_id,e.operation,e.target_hash) IN(
519
+ SELECT account_id,operation,target_hash FROM lifecycle_billing_effects WHERE account_id=owner_id AND state='confirmed' AND remote_id IS NOT NULL LIMIT 1000 FOR UPDATE SKIP LOCKED);
520
+ GET DIAGNOSTICS changed=ROW_COUNT;
521
+ RETURN total+changed;
522
+ END $$;
523
+ REVOKE ALL ON FUNCTION grove_lifecycle_retention(text,text),grove_lifecycle_erase(uuid) FROM PUBLIC;
524
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_retention(text,text),grove_lifecycle_erase(uuid) TO grove_worker;
525
+
526
+ CREATE FUNCTION grove_lifecycle_public_allowed(release_key text,approval_key text) RETURNS boolean LANGUAGE sql STABLE
527
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
528
+ SELECT EXISTS(SELECT 1 FROM lifecycle_release_control WHERE singleton AND release_hash=release_key
529
+ AND approval_hash=approval_key AND phase='public' AND public_hash IS NOT NULL)
530
+ $$;
531
+ CREATE FUNCTION grove_lifecycle_open_public(release_key text,approval_key text,public_receipt text,expected_generation bigint,expected_evidence jsonb)
532
+ RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
533
+ DECLARE control lifecycle_release_control; evidence jsonb;
534
+ BEGIN
535
+ SELECT * INTO control FROM lifecycle_release_control WHERE singleton FOR UPDATE;
536
+ IF NOT FOUND OR control.release_hash<>release_key OR control.approval_hash IS DISTINCT FROM approval_key
537
+ OR public_receipt !~ '^[a-f0-9]{64}$' THEN RAISE EXCEPTION 'public release fence'; END IF;
538
+ IF control.phase='public' AND control.public_hash=public_receipt THEN RETURN control.public_evidence; END IF;
539
+ IF control.phase<>'released' OR control.generation<>expected_generation THEN RAISE EXCEPTION 'public generation fence'; END IF;
540
+ evidence:=grove_lifecycle_status(release_key,control.receipt_hash);
541
+ IF evidence IS DISTINCT FROM expected_evidence OR evidence->>'caughtUp' IS DISTINCT FROM 'true' THEN RAISE EXCEPTION 'public evidence fence'; END IF;
542
+ UPDATE lifecycle_release_control SET phase='public',public_hash=public_receipt,public_evidence=evidence WHERE singleton;
543
+ RETURN evidence;
544
+ END $$;
545
+ REVOKE ALL ON FUNCTION grove_lifecycle_public_allowed(text,text),grove_lifecycle_open_public(text,text,text,bigint,jsonb) FROM PUBLIC;
546
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_public_allowed(text,text) TO grove_runtime;
547
+ CREATE FUNCTION grove_lifecycle_status_approved(release_key text,approval_key text) RETURNS jsonb LANGUAGE sql STABLE
548
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
549
+ SELECT grove_lifecycle_proof(release_key,receipt_hash) FROM lifecycle_release_control WHERE singleton AND release_hash=release_key
550
+ AND approval_hash=approval_key AND phase IN ('released','public')
551
+ $$;
552
+ REVOKE ALL ON FUNCTION grove_lifecycle_status_approved(text,text) FROM PUBLIC;
553
+ GRANT EXECUTE ON FUNCTION grove_lifecycle_status_approved(text,text) TO grove_runtime,grove_worker;
554
+ `);
555
+ },
556
+ async down() {
557
+ throw new Error("Use a forward migration");
558
+ }
559
+ };
560
+
561
+ // lib/database/src/export-ready-migration.ts
562
+ var exportReadyEmail = {
563
+ name: "20261119_046_export_ready_email",
564
+ async up(db2) {
565
+ await db2.raw(`
566
+ ALTER TABLE transactional_emails DROP CONSTRAINT transactional_emails_kind_check,
567
+ ADD COLUMN fingerprint text,
568
+ ADD COLUMN export_task_id uuid,
569
+ ADD COLUMN export_preparation_id uuid,
570
+ ADD CONSTRAINT transactional_emails_kind_check CHECK
571
+ (kind IN ('welcome','connection_approved','connection_revoked','export_ready')),
572
+ ADD CONSTRAINT transactional_emails_export_reference CHECK (
573
+ (kind = 'export_ready' AND export_task_id IS NOT NULL AND export_preparation_id IS NOT NULL
574
+ AND event_key = 'export_ready:' || export_task_id::text || ':' || export_preparation_id::text)
575
+ OR (kind <> 'export_ready' AND export_task_id IS NULL AND export_preparation_id IS NULL)
576
+ );
577
+ `);
578
+ },
579
+ async down() {
580
+ throw new Error("Use a forward migration");
581
+ }
582
+ };
583
+
584
+ // lib/database/src/import-destination-migration.ts
585
+ var importDestination = {
586
+ name: "20261118_045_import_destination",
587
+ async up(db2) {
588
+ await db2.raw(
589
+ "ALTER TABLE document_import_batches ADD COLUMN initial_destination jsonb NOT NULL DEFAULT 'null'"
590
+ );
591
+ },
592
+ async down() {
593
+ throw new Error("Use a forward migration");
594
+ }
595
+ };
596
+
597
+ // lib/database/src/deletion-receipt-migration.ts
598
+ var deletionReceipt = {
599
+ name: "20261119_047_deletion_receipt",
600
+ async up(db2) {
601
+ await db2.raw(`
602
+ CREATE TABLE deletion_receipts (
603
+ id uuid PRIMARY KEY, account_id uuid NOT NULL UNIQUE REFERENCES accounts(id),
604
+ snapshot bytea CHECK (octet_length(snapshot) BETWEEN 29 AND 512),
605
+ created_at timestamptz NOT NULL DEFAULT now(), due_at timestamptz NOT NULL DEFAULT now(),
606
+ attempts integer NOT NULL DEFAULT 0, lease_id uuid, lease_until timestamptz,
607
+ dispatched_at timestamptz, dispatch_id uuid, dispatch_until timestamptz,
608
+ fingerprint text, accepted_at timestamptz, provider_id text, failed_at timestamptz, error_code text,
609
+ CHECK ((snapshot IS NULL) = (accepted_at IS NOT NULL OR failed_at IS NOT NULL))
610
+ );
611
+ CREATE INDEX deletion_receipts_due ON deletion_receipts(due_at) WHERE snapshot IS NOT NULL;
612
+ ALTER TABLE deletion_receipts ENABLE ROW LEVEL SECURITY;
613
+ CREATE POLICY worker_tenant ON deletion_receipts TO grove_worker
614
+ USING (account_id=NULLIF(current_setting('grove.account_id',true),'')::uuid);
615
+ CREATE POLICY deletion_intent ON deletion_receipts FOR INSERT TO grove_runtime WITH CHECK (
616
+ account_id=NULLIF(current_setting('grove.account_id',true),'')::uuid AND EXISTS (
617
+ SELECT 1 FROM accounts a WHERE a.id=account_id AND a.status='deleting' AND a.provider_deleted_at IS NULL));
618
+ GRANT INSERT(id,account_id,snapshot) ON deletion_receipts TO grove_runtime;
619
+ GRANT SELECT,UPDATE ON deletion_receipts TO grove_worker;
620
+
621
+ CREATE FUNCTION grove_receipt_due(r deletion_receipts) RETURNS boolean LANGUAGE sql STABLE
622
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
623
+ SELECT r.snapshot IS NOT NULL AND r.attempts<5 AND r.created_at>now()-interval '23 hours'
624
+ AND r.due_at<=now() AND (r.lease_until IS NULL OR r.lease_until<now())
625
+ AND EXISTS (SELECT 1 FROM accounts a WHERE a.id=r.account_id AND a.status IN ('deleting','deleted'))
626
+ AND NOT EXISTS (SELECT 1 FROM transactional_emails e WHERE e.account_id=r.account_id AND e.lease_until>now())
627
+ $$;
628
+ CREATE FUNCTION grove_dispatch_receipts() RETURNS TABLE(id uuid, dispatch_id uuid) LANGUAGE sql
629
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
630
+ UPDATE deletion_receipts SET dispatch_id=gen_random_uuid(),dispatch_until=now()+interval '15 seconds' WHERE deletion_receipts.id IN (
631
+ SELECT r.id FROM deletion_receipts r WHERE grove_receipt_due(r)
632
+ AND (r.dispatch_until IS NULL OR r.dispatch_until<now())
633
+ AND (r.dispatched_at IS NULL OR r.dispatched_at<now()-interval '15 seconds')
634
+ ORDER BY r.due_at,r.id LIMIT 32 FOR UPDATE SKIP LOCKED) RETURNING deletion_receipts.id,deletion_receipts.dispatch_id
635
+ $$;
636
+ CREATE FUNCTION grove_mark_receipt_dispatched(wanted uuid, token uuid) RETURNS void LANGUAGE sql
637
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
638
+ UPDATE deletion_receipts SET dispatched_at=now(),dispatch_id=NULL,dispatch_until=NULL
639
+ WHERE id=wanted AND dispatch_id=token AND dispatch_until>now() AND snapshot IS NOT NULL
640
+ $$;
641
+ CREATE FUNCTION grove_claim_receipt(wanted uuid) RETURNS SETOF deletion_receipts LANGUAGE sql
642
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
643
+ UPDATE deletion_receipts SET attempts=attempts+1,lease_id=gen_random_uuid(),lease_until=now()+interval '120 seconds'
644
+ WHERE id=(SELECT r.id FROM deletion_receipts r WHERE (wanted IS NULL OR r.id=wanted) AND grove_receipt_due(r)
645
+ ORDER BY r.due_at,r.id LIMIT 1 FOR UPDATE SKIP LOCKED) RETURNING *
646
+ $$;
647
+ CREATE FUNCTION grove_sweep_receipts(paused boolean) RETURNS bigint LANGUAGE sql
648
+ SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$
649
+ WITH cleared AS (UPDATE deletion_receipts SET snapshot=NULL, fingerprint=NULL, lease_id=NULL,lease_until=NULL,
650
+ failed_at=now(),error_code=CASE WHEN paused THEN 'receipt_paused' ELSE 'receipt_exhausted' END
651
+ WHERE id IN (SELECT r.id FROM deletion_receipts r WHERE r.snapshot IS NOT NULL
652
+ AND (paused OR r.created_at<=now()-interval '23 hours' OR (r.attempts>=5 AND r.lease_until<now()))
653
+ ORDER BY r.created_at LIMIT 1000 FOR UPDATE SKIP LOCKED) RETURNING 1) SELECT count(*) FROM cleared
654
+ $$;
655
+ REVOKE ALL ON FUNCTION grove_receipt_due(deletion_receipts),grove_dispatch_receipts(),grove_mark_receipt_dispatched(uuid,uuid),grove_claim_receipt(uuid),grove_sweep_receipts(boolean) FROM PUBLIC;
656
+ GRANT EXECUTE ON FUNCTION grove_dispatch_receipts(),grove_mark_receipt_dispatched(uuid,uuid),grove_claim_receipt(uuid),grove_sweep_receipts(boolean) TO grove_worker;
657
+ `);
658
+ },
659
+ async down() {
660
+ throw new Error("Use a forward migration");
661
+ }
662
+ };
663
+
7
664
  // lib/database/src/daily-note-migration.ts
8
665
  var dailyNotes = {
9
666
  name: "20261117_042_daily_notes",
@@ -2254,6 +2911,32 @@ var aiPreferences = {
2254
2911
  }
2255
2912
  };
2256
2913
 
2914
+ // lib/database/src/proofing-migration.ts
2915
+ var proofingConsents = {
2916
+ name: "20261118_044_proofing_consent",
2917
+ async up(db2) {
2918
+ await db2.raw(`CREATE TABLE proofing_consents (
2919
+ account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
2920
+ scope text NOT NULL CHECK(scope='grove-note-editor'),
2921
+ version integer NOT NULL CHECK(version>0),
2922
+ generation uuid NOT NULL,
2923
+ automatic boolean NOT NULL,
2924
+ updated_at timestamptz NOT NULL DEFAULT now(),
2925
+ revoked_at timestamptz,
2926
+ CHECK(revoked_at IS NULL OR NOT automatic),
2927
+ PRIMARY KEY(account_id,scope)
2928
+ );
2929
+ ALTER TABLE proofing_consents ENABLE ROW LEVEL SECURITY;
2930
+ ALTER TABLE proofing_consents FORCE ROW LEVEL SECURITY;
2931
+ CREATE POLICY tenant ON proofing_consents USING(account_id=nullif(current_setting('grove.account_id',true),'')::uuid);
2932
+ GRANT SELECT, INSERT, UPDATE ON proofing_consents TO grove_runtime;
2933
+ GRANT SELECT, DELETE ON proofing_consents TO grove_worker;`);
2934
+ },
2935
+ async down() {
2936
+ throw new Error("Use a forward migration");
2937
+ }
2938
+ };
2939
+
2257
2940
  // lib/database/src/soft-deletion.ts
2258
2941
  async function softDeletion(db2) {
2259
2942
  for (const table of [
@@ -3753,7 +4436,12 @@ var migrations = [
3753
4436
  billingTrial,
3754
4437
  writingAllowance,
3755
4438
  dailyNotes,
3756
- cacheRetention
4439
+ cacheRetention,
4440
+ proofingConsents,
4441
+ importDestination,
4442
+ exportReadyEmail,
4443
+ deletionReceipt,
4444
+ lifecycleReconciliation
3757
4445
  ];
3758
4446
  var migrationSource = {
3759
4447
  getMigrations: async () => migrations,