@miniaxolotl/grove-server 0.0.0-stage → 1.1.0

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.
@@ -0,0 +1,591 @@
1
+ import { createRequire as __groveCreateRequire } from "node:module"; const require = __groveCreateRequire(import.meta.url);
2
+
3
+ // lib/database/src/index.ts
4
+ import knex from "knex";
5
+ import { Model, knexSnakeCaseMappers } from "objection";
6
+
7
+ // lib/database/src/hardening.ts
8
+ var hardening = {
9
+ name: "20261018_002_lifecycle_bounds",
10
+ async up(db2) {
11
+ await db2.raw(`
12
+ REVOKE CREATE ON SCHEMA public FROM PUBLIC;
13
+ CREATE OR REPLACE FUNCTION grove_claim_job() RETURNS SETOF jobs
14
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
15
+ BEGIN
16
+ UPDATE jobs SET failed_at = now(), error_code = 'lease_exhausted'
17
+ WHERE failed_at IS NULL AND attempts >= 5 AND (lease_until IS NULL OR lease_until < now());
18
+ RETURN QUERY UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1
19
+ WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id
20
+ WHERE a.status = 'active' AND j.failed_at IS NULL AND j.attempts < 5 AND j.due_at <= now()
21
+ AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at
22
+ FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;
23
+ END $$;
24
+ CREATE OR REPLACE FUNCTION grove_maintenance_accounts() RETURNS TABLE(id uuid, status text, clerk_subject text, provider_deleted_at timestamptz)
25
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
26
+ SELECT a.id, a.status, a.clerk_subject, a.provider_deleted_at FROM accounts a
27
+ WHERE a.status = 'deleting' OR EXISTS(SELECT 1 FROM memories m WHERE m.account_id = a.id AND m.purge_at <= now())
28
+ OR EXISTS(SELECT 1 FROM rate_buckets b WHERE b.account_id = a.id AND b.minute < now() - interval '1 day')
29
+ ORDER BY a.id LIMIT 100
30
+ $$;
31
+ `);
32
+ },
33
+ async down() {
34
+ throw new Error("Use a forward migration");
35
+ }
36
+ };
37
+ var identityState = {
38
+ name: "20261018_003_identity_state",
39
+ async up(db2) {
40
+ await db2.raw(`
41
+ ALTER TABLE subject_authority ADD COLUMN disabled boolean NOT NULL DEFAULT false;
42
+ CREATE FUNCTION grove_user_state(subject text, event_at bigint, disabled boolean) RETURNS void
43
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
44
+ BEGIN
45
+ UPDATE subject_authority s SET disabled = grove_user_state.disabled
46
+ WHERE s.subject = grove_user_state.subject AND s.event_at = grove_user_state.event_at AND NOT s.deleted;
47
+ IF NOT FOUND THEN RETURN; END IF;
48
+ UPDATE accounts SET status = CASE WHEN disabled THEN 'disabled' ELSE 'active' END
49
+ WHERE clerk_subject = subject AND status IN ('active', 'disabled');
50
+ END
51
+ $$;
52
+ CREATE OR REPLACE FUNCTION grove_account(subject text) RETURNS SETOF accounts
53
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
54
+ BEGIN
55
+ PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));
56
+ IF EXISTS(SELECT 1 FROM subject_authority s WHERE s.subject = grove_account.subject AND (s.deleted OR s.disabled)) THEN RETURN; END IF;
57
+ INSERT INTO accounts(clerk_subject) VALUES(subject) ON CONFLICT(clerk_subject) DO NOTHING;
58
+ RETURN QUERY SELECT * FROM accounts WHERE clerk_subject = subject;
59
+ END $$;
60
+ REVOKE ALL ON FUNCTION grove_user_state(text,bigint,boolean) FROM PUBLIC;
61
+ GRANT EXECUTE ON FUNCTION grove_user_state(text,bigint,boolean) TO grove_runtime;
62
+ `);
63
+ },
64
+ async down() {
65
+ throw new Error("Use a forward migration");
66
+ }
67
+ };
68
+
69
+ // lib/database/src/model-migration.ts
70
+ var modelProviders = {
71
+ // 004 belongs to the independently reviewed cloud-onboarding PR.
72
+ name: "20261019_005_model_providers",
73
+ async up(db2) {
74
+ await db2.raw(`
75
+ CREATE TABLE model_settings (
76
+ singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),
77
+ version integer NOT NULL DEFAULT 0, encrypted text NOT NULL,
78
+ updated_at timestamptz NOT NULL DEFAULT now()
79
+ );
80
+ GRANT SELECT ON model_settings TO grove_runtime, grove_worker;
81
+ GRANT INSERT, UPDATE ON model_settings TO grove_runtime;
82
+ CREATE TABLE embedding_profiles (
83
+ id text PRIMARY KEY, model text NOT NULL, dimensions integer NOT NULL CHECK (dimensions BETWEEN 32 AND 16000),
84
+ created_at timestamptz NOT NULL DEFAULT now(), UNIQUE(id, dimensions)
85
+ );
86
+ GRANT SELECT, INSERT ON embedding_profiles TO grove_runtime, grove_worker;
87
+ INSERT INTO embedding_profiles(id, model, dimensions)
88
+ SELECT DISTINCT profile, 'legacy', 384 FROM memory_embeddings;
89
+ ALTER TABLE memory_embeddings ALTER COLUMN embedding TYPE vector;
90
+ ALTER TABLE memory_embeddings ADD COLUMN dimensions integer NOT NULL DEFAULT 384;
91
+ ALTER TABLE memory_embeddings ADD CONSTRAINT embedding_dimensions CHECK (vector_dims(embedding) = dimensions);
92
+ ALTER TABLE memory_embeddings ADD CONSTRAINT embedding_profile_fk FOREIGN KEY (profile, dimensions) REFERENCES embedding_profiles(id, dimensions);
93
+ ALTER TABLE memories ADD COLUMN auto_kind boolean NOT NULL DEFAULT false;
94
+ ALTER TABLE accounts ADD COLUMN organize_enabled boolean NOT NULL DEFAULT true;
95
+ ALTER TABLE accounts ADD COLUMN summaries_enabled boolean NOT NULL DEFAULT true;
96
+
97
+ ALTER TABLE jobs DROP CONSTRAINT jobs_account_id_memory_id_version_key;
98
+ ALTER TABLE jobs ALTER COLUMN memory_id DROP NOT NULL;
99
+ ALTER TABLE jobs ALTER COLUMN version DROP NOT NULL;
100
+ ALTER TABLE jobs ADD COLUMN kind text NOT NULL DEFAULT 'embedding' CHECK (kind IN ('embedding','decision','organization','brief'));
101
+ ALTER TABLE jobs ADD COLUMN profile text NOT NULL DEFAULT 'minilm-l6-v2-mean-normalized-v1';
102
+ ALTER TABLE jobs ADD COLUMN target text;
103
+ UPDATE jobs SET target = memory_id::text;
104
+ ALTER TABLE jobs ALTER COLUMN target SET NOT NULL;
105
+ ALTER TABLE jobs ADD COLUMN scope jsonb;
106
+ ALTER TABLE jobs ADD CONSTRAINT job_target CHECK ((kind = 'brief' AND memory_id IS NULL AND version IS NULL AND scope IS NOT NULL) OR (kind <> 'brief' AND memory_id IS NOT NULL AND version IS NOT NULL));
107
+ ALTER TABLE jobs ADD CONSTRAINT job_identity UNIQUE(account_id, kind, target, profile);
108
+
109
+ CREATE TABLE memory_enrichments (
110
+ account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,
111
+ kind text NOT NULL CHECK (kind IN ('decision','organization')), profile text NOT NULL,
112
+ data jsonb NOT NULL, sources jsonb NOT NULL DEFAULT '[]', created_at timestamptz NOT NULL DEFAULT now(),
113
+ PRIMARY KEY(account_id, memory_id, version, kind, profile),
114
+ FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE
115
+ );
116
+ CREATE TABLE memory_briefs (
117
+ account_id uuid NOT NULL REFERENCES accounts(id), target text NOT NULL,
118
+ scope jsonb NOT NULL, profile text NOT NULL, content_version integer NOT NULL,
119
+ content jsonb NOT NULL, sources jsonb NOT NULL, truncated boolean NOT NULL DEFAULT false,
120
+ created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, target, profile)
121
+ );
122
+ CREATE TABLE inference_usage (
123
+ account_id uuid NOT NULL REFERENCES accounts(id), day date NOT NULL DEFAULT CURRENT_DATE,
124
+ role text NOT NULL, requests integer NOT NULL DEFAULT 0, input_tokens bigint NOT NULL DEFAULT 0,
125
+ output_tokens bigint NOT NULL DEFAULT 0, PRIMARY KEY(account_id, day, role)
126
+ );
127
+ `);
128
+ for (const table of [
129
+ "memory_enrichments",
130
+ "memory_briefs",
131
+ "inference_usage"
132
+ ]) {
133
+ await db2.raw("ALTER TABLE ?? ENABLE ROW LEVEL SECURITY", [table]);
134
+ await db2.raw(
135
+ "CREATE POLICY tenant ON ?? USING (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid) WITH CHECK (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid)",
136
+ [table]
137
+ );
138
+ await db2.raw(
139
+ "GRANT SELECT, INSERT, UPDATE, DELETE ON ?? TO grove_runtime, grove_worker",
140
+ [table]
141
+ );
142
+ }
143
+ await db2.raw(`
144
+ DROP FUNCTION grove_claim_job();
145
+ CREATE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL) RETURNS SETOF jobs
146
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
147
+ BEGIN
148
+ UPDATE jobs SET failed_at = now(), error_code = 'lease_exhausted'
149
+ WHERE failed_at IS NULL AND attempts >= 5 AND (lease_until IS NULL OR lease_until < now());
150
+ RETURN QUERY UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1
151
+ WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id
152
+ WHERE a.status = 'active' AND j.failed_at IS NULL AND j.attempts < 5 AND j.due_at <= now()
153
+ AND (profiles IS NULL OR j.profile = ANY(profiles))
154
+ AND (j.kind <> 'decision' OR NOT EXISTS (SELECT 1 FROM jobs e WHERE e.account_id = j.account_id AND e.target = j.target AND e.kind = 'embedding' AND e.failed_at IS NULL AND (profiles IS NULL OR e.profile = ANY(profiles))))
155
+ AND (j.kind <> 'brief' OR NOT EXISTS (SELECT 1 FROM jobs e WHERE e.account_id = j.account_id AND e.kind <> 'brief' AND e.failed_at IS NULL AND (profiles IS NULL OR e.profile = ANY(profiles))))
156
+ AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id
157
+ FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;
158
+ END $$;
159
+ REVOKE ALL ON FUNCTION grove_claim_job(text[]) FROM PUBLIC;
160
+ GRANT EXECUTE ON FUNCTION grove_claim_job(text[]) TO grove_worker;
161
+ CREATE FUNCTION grove_reprocess(embedding_profile text, decision_profile text, generation_profile text) RETURNS void
162
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
163
+ BEGIN
164
+ DELETE FROM jobs;
165
+ DELETE FROM memory_briefs;
166
+ INSERT INTO jobs(account_id, memory_id, version, target, kind, profile)
167
+ SELECT m.account_id, m.id, m.version, m.id::text, p.kind, p.profile
168
+ FROM memories m JOIN accounts a ON a.id = m.account_id
169
+ CROSS JOIN (VALUES ('embedding', embedding_profile), ('decision', decision_profile), ('organization', generation_profile)) AS p(kind, profile)
170
+ WHERE a.status = 'active' AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now())
171
+ AND p.profile IS NOT NULL AND (p.kind = 'embedding' OR a.organize_enabled);
172
+ IF generation_profile IS NOT NULL THEN
173
+ INSERT INTO jobs(account_id, kind, target, profile, scope, due_at)
174
+ SELECT DISTINCT m.account_id, 'brief', COALESCE(m.project_id::text, 'personal'), generation_profile,
175
+ jsonb_build_object('projectId', m.project_id), now() + interval '5 seconds'
176
+ FROM memories m JOIN accounts a ON a.id = m.account_id
177
+ WHERE a.status = 'active' AND a.summaries_enabled AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now());
178
+ INSERT INTO jobs(account_id, kind, target, profile, scope, due_at)
179
+ SELECT m.account_id, 'brief', COALESCE(m.project_id::text, 'personal') || ':task:' || m.task_id, generation_profile,
180
+ jsonb_build_object('projectId', m.project_id, 'taskId', m.task_id), now() + interval '5 seconds'
181
+ FROM memories m JOIN accounts a ON a.id = m.account_id
182
+ WHERE a.status = 'active' AND a.summaries_enabled AND m.status = 'active' AND m.kind = 'handoff' AND m.expires_at > now();
183
+ END IF;
184
+ END $$;
185
+ REVOKE ALL ON FUNCTION grove_reprocess(text,text,text) FROM PUBLIC;
186
+ GRANT EXECUTE ON FUNCTION grove_reprocess(text,text,text) TO grove_runtime;
187
+ `);
188
+ },
189
+ async down() {
190
+ throw new Error("Use a forward migration");
191
+ }
192
+ };
193
+
194
+ // lib/database/src/lifetime-migration.ts
195
+ var memoryLifetimes = {
196
+ name: "20261020_006_memory_lifetimes",
197
+ async up(db2) {
198
+ await db2.raw(`
199
+ ALTER TABLE memories DROP CONSTRAINT memories_check;
200
+ ALTER TABLE memories ADD COLUMN retention_days integer CHECK (retention_days BETWEEN 1 AND 365);
201
+ UPDATE memories SET retention_days = 30 WHERE expires_at IS NOT NULL;
202
+ ALTER TABLE memories ADD CONSTRAINT memory_task_reference CHECK ((kind = 'handoff') = (task_id IS NOT NULL));
203
+ ALTER TABLE memories ADD CONSTRAINT memory_lifetime CHECK (
204
+ (retention_days IS NULL AND expires_at IS NULL AND purge_at IS NULL) OR
205
+ (retention_days IS NOT NULL AND expires_at IS NOT NULL AND purge_at IS NOT NULL AND purge_at > expires_at)
206
+ );
207
+ CREATE INDEX memories_updated_page ON memories(account_id, updated_at DESC, id DESC);
208
+ `);
209
+ },
210
+ async down() {
211
+ throw new Error("Use a forward migration");
212
+ }
213
+ };
214
+
215
+ // lib/database/src/background-migration.ts
216
+ var backgroundServices = {
217
+ name: "20261020_007_background_services",
218
+ async up(db2) {
219
+ await db2.raw(`
220
+ ALTER TABLE accounts ADD COLUMN organization_due_at timestamptz NOT NULL DEFAULT now();
221
+ ALTER TABLE accounts ADD COLUMN organization_checked_at timestamptz;
222
+ ALTER TABLE jobs ADD COLUMN dispatched_at timestamptz;
223
+ CREATE TABLE transactional_emails (
224
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
225
+ event_key text NOT NULL, kind text NOT NULL CHECK (kind IN ('welcome','connection_approved','connection_revoked')),
226
+ created_at timestamptz NOT NULL DEFAULT now(), due_at timestamptz NOT NULL DEFAULT now(),
227
+ attempts integer NOT NULL DEFAULT 0, lease_id uuid, lease_until timestamptz,
228
+ dispatched_at timestamptz, sent_at timestamptz, provider_id text, failed_at timestamptz, error_code text,
229
+ UNIQUE(account_id, event_key)
230
+ );
231
+ ALTER TABLE transactional_emails ENABLE ROW LEVEL SECURITY;
232
+ CREATE POLICY tenant ON transactional_emails USING (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid)
233
+ WITH CHECK (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid);
234
+ GRANT SELECT, INSERT, UPDATE, DELETE ON transactional_emails TO grove_worker;
235
+ CREATE INDEX transactional_emails_due ON transactional_emails(due_at) WHERE sent_at IS NULL AND failed_at IS NULL;
236
+
237
+ CREATE FUNCTION grove_queue_transactional_email() RETURNS trigger
238
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
239
+ DECLARE event_kind text; owner_id uuid; event_identity text;
240
+ BEGIN
241
+ IF TG_TABLE_NAME = 'accounts' THEN
242
+ owner_id := NEW.id; event_kind := 'welcome'; event_identity := 'welcome';
243
+ ELSE
244
+ owner_id := NEW.account_id;
245
+ IF NOT EXISTS (SELECT 1 FROM accounts WHERE id = owner_id AND status = 'active') THEN RETURN NEW; END IF;
246
+ IF TG_OP = 'INSERT' THEN
247
+ IF cardinality(NEW.capabilities) = 0 OR NEW.revoked_at IS NOT NULL THEN RETURN NEW; END IF;
248
+ event_kind := 'connection_approved';
249
+ ELSIF OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL THEN
250
+ IF cardinality(OLD.capabilities) = 0 THEN RETURN NEW; END IF;
251
+ event_kind := 'connection_revoked';
252
+ ELSIF cardinality(NEW.capabilities) > 0 AND NEW.revoked_at IS NULL AND (cardinality(OLD.capabilities) = 0 OR OLD.revoked_at IS NOT NULL) THEN
253
+ event_kind := 'connection_approved';
254
+ ELSE RETURN NEW;
255
+ END IF;
256
+ event_identity := event_kind || ':' || NEW.id::text || ':' || txid_current()::text;
257
+ END IF;
258
+ INSERT INTO transactional_emails(account_id, event_key, kind) VALUES(owner_id, event_identity, event_kind)
259
+ ON CONFLICT(account_id, event_key) DO NOTHING;
260
+ RETURN NEW;
261
+ END $$;
262
+ REVOKE ALL ON FUNCTION grove_queue_transactional_email() FROM PUBLIC;
263
+ CREATE TRIGGER account_welcome AFTER INSERT ON accounts FOR EACH ROW EXECUTE FUNCTION grove_queue_transactional_email();
264
+ CREATE TRIGGER connection_notification AFTER INSERT OR UPDATE ON connections FOR EACH ROW EXECUTE FUNCTION grove_queue_transactional_email();
265
+
266
+ DROP FUNCTION grove_claim_job(text[]);
267
+ CREATE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL, wanted uuid DEFAULT NULL) RETURNS SETOF jobs
268
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
269
+ BEGIN
270
+ UPDATE jobs SET failed_at = now(), error_code = 'lease_exhausted'
271
+ WHERE failed_at IS NULL AND attempts >= 5 AND (lease_until IS NULL OR lease_until < now());
272
+ RETURN QUERY UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1
273
+ WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id
274
+ WHERE a.status = 'active' AND j.failed_at IS NULL AND j.attempts < 5 AND j.due_at <= now()
275
+ AND (wanted IS NULL OR j.id = wanted) AND (profiles IS NULL OR j.profile = ANY(profiles))
276
+ AND (j.kind <> 'decision' OR NOT EXISTS (SELECT 1 FROM jobs e WHERE e.account_id = j.account_id AND e.target = j.target AND e.kind = 'embedding' AND e.failed_at IS NULL AND (profiles IS NULL OR e.profile = ANY(profiles))))
277
+ AND (j.kind <> 'brief' OR NOT EXISTS (SELECT 1 FROM jobs e WHERE e.account_id = j.account_id AND e.kind <> 'brief' AND e.failed_at IS NULL AND (profiles IS NULL OR e.profile = ANY(profiles))))
278
+ AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id
279
+ FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;
280
+ END $$;
281
+ REVOKE ALL ON FUNCTION grove_claim_job(text[],uuid) FROM PUBLIC;
282
+ GRANT EXECUTE ON FUNCTION grove_claim_job(text[],uuid) TO grove_worker;
283
+
284
+ CREATE FUNCTION grove_claim_email(wanted uuid DEFAULT NULL) RETURNS SETOF transactional_emails
285
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
286
+ BEGIN
287
+ UPDATE transactional_emails SET failed_at = now(), error_code = 'delivery_exhausted'
288
+ WHERE sent_at IS NULL AND failed_at IS NULL AND (attempts >= 5 OR created_at < now() - interval '23 hours')
289
+ AND (lease_until IS NULL OR lease_until < now());
290
+ RETURN QUERY UPDATE transactional_emails SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1
291
+ WHERE id = (SELECT e.id FROM transactional_emails e JOIN accounts a ON a.id = e.account_id
292
+ WHERE a.status = 'active' AND e.sent_at IS NULL AND e.failed_at IS NULL AND e.due_at <= now()
293
+ AND (wanted IS NULL OR e.id = wanted) AND (e.lease_until IS NULL OR e.lease_until < now())
294
+ ORDER BY e.due_at, e.id FOR UPDATE OF e SKIP LOCKED LIMIT 1) RETURNING *;
295
+ END $$;
296
+ REVOKE ALL ON FUNCTION grove_claim_email(uuid) FROM PUBLIC;
297
+ GRANT EXECUTE ON FUNCTION grove_claim_email(uuid) TO grove_worker;
298
+
299
+ CREATE FUNCTION grove_due_dispatch(profiles text[], mail_enabled boolean) RETURNS TABLE(id uuid, account_id uuid, queue_kind text)
300
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
301
+ SELECT due.id, due.account_id, due.queue_kind FROM (
302
+ SELECT j.id, j.account_id, 'memory'::text AS queue_kind, j.due_at FROM jobs j JOIN accounts a ON a.id = j.account_id
303
+ WHERE a.status = 'active' AND j.profile = ANY(profiles) AND j.failed_at IS NULL AND j.attempts < 5
304
+ AND j.due_at <= now() AND (j.lease_until IS NULL OR j.lease_until < now())
305
+ AND (j.dispatched_at IS NULL OR j.dispatched_at < now() - interval '60 seconds')
306
+ UNION ALL
307
+ SELECT e.id, e.account_id, 'email'::text AS queue_kind, e.due_at FROM transactional_emails e JOIN accounts a ON a.id = e.account_id
308
+ WHERE mail_enabled AND a.status = 'active' AND e.sent_at IS NULL AND e.failed_at IS NULL AND e.attempts < 5
309
+ AND e.created_at > now() - interval '23 hours' AND e.due_at <= now() AND (e.lease_until IS NULL OR e.lease_until < now())
310
+ AND (e.dispatched_at IS NULL OR e.dispatched_at < now() - interval '60 seconds')
311
+ ) due ORDER BY due.due_at, due.id LIMIT 100;
312
+ $$;
313
+ REVOKE ALL ON FUNCTION grove_due_dispatch(text[],boolean) FROM PUBLIC;
314
+ GRANT EXECUTE ON FUNCTION grove_due_dispatch(text[],boolean) TO grove_worker;
315
+
316
+ CREATE FUNCTION grove_organization_accounts(interval_seconds integer) RETURNS TABLE(id uuid)
317
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
318
+ UPDATE accounts SET organization_due_at = now() + (greatest(60, least(interval_seconds, 86400)) * interval '1 second'), organization_checked_at = now()
319
+ WHERE accounts.id IN (SELECT a.id FROM accounts a WHERE a.status = 'active' AND a.organization_due_at <= now()
320
+ ORDER BY a.organization_due_at, a.id FOR UPDATE SKIP LOCKED LIMIT 20) RETURNING accounts.id;
321
+ $$;
322
+ REVOKE ALL ON FUNCTION grove_organization_accounts(integer) FROM PUBLIC;
323
+ GRANT EXECUTE ON FUNCTION grove_organization_accounts(integer) TO grove_worker;
324
+
325
+ CREATE FUNCTION grove_sweep_deliveries() RETURNS void
326
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
327
+ BEGIN
328
+ UPDATE jobs SET failed_at = now(), error_code = 'lease_exhausted'
329
+ WHERE failed_at IS NULL AND attempts >= 5 AND (lease_until IS NULL OR lease_until < now());
330
+ UPDATE transactional_emails SET failed_at = now(), error_code = 'delivery_exhausted'
331
+ WHERE sent_at IS NULL AND failed_at IS NULL AND (attempts >= 5 OR created_at < now() - interval '23 hours')
332
+ AND (lease_until IS NULL OR lease_until < now());
333
+ END $$;
334
+ REVOKE ALL ON FUNCTION grove_sweep_deliveries() FROM PUBLIC;
335
+ GRANT EXECUTE ON FUNCTION grove_sweep_deliveries() TO grove_worker;
336
+ `);
337
+ },
338
+ async down() {
339
+ throw new Error("Use a forward migration");
340
+ }
341
+ };
342
+
343
+ // lib/database/src/migrations.ts
344
+ var migrations = [
345
+ {
346
+ name: "20261018_001_private_memory",
347
+ async up(db2) {
348
+ await db2.raw(`
349
+ CREATE EXTENSION IF NOT EXISTS vector;
350
+ DO $$ BEGIN
351
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'grove_runtime') THEN
352
+ CREATE ROLE grove_runtime NOLOGIN NOSUPERUSER NOBYPASSRLS;
353
+ END IF;
354
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'grove_worker') THEN
355
+ CREATE ROLE grove_worker NOLOGIN NOSUPERUSER NOBYPASSRLS;
356
+ END IF;
357
+ END $$;
358
+ CREATE TABLE accounts (
359
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), clerk_subject text UNIQUE NOT NULL,
360
+ status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','disabled','deleting','deleted')),
361
+ content_version integer NOT NULL DEFAULT 0, capture_enabled boolean NOT NULL DEFAULT true,
362
+ recall_enabled boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(),
363
+ deleted_at timestamptz, provider_deleted_at timestamptz
364
+ );
365
+ CREATE TABLE projects (
366
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
367
+ name text NOT NULL, identity text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
368
+ UNIQUE(account_id, id), UNIQUE(account_id, identity)
369
+ );
370
+ CREATE TABLE memories (
371
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
372
+ project_id uuid, kind text NOT NULL CHECK (kind IN ('preference','fact','decision','solution','handoff')),
373
+ content text NOT NULL CHECK (length(content) BETWEEN 1 AND 6000),
374
+ search tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
375
+ status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','archived')),
376
+ version integer NOT NULL DEFAULT 1 CHECK (version > 0),
377
+ source jsonb NOT NULL, task_id text, expires_at timestamptz, purge_at timestamptz,
378
+ created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
379
+ UNIQUE(account_id, id),
380
+ FOREIGN KEY (account_id, project_id) REFERENCES projects(account_id, id),
381
+ CHECK ((kind = 'handoff' AND task_id IS NOT NULL AND expires_at IS NOT NULL AND purge_at > expires_at)
382
+ OR (kind <> 'handoff' AND task_id IS NULL AND expires_at IS NULL AND purge_at IS NULL))
383
+ );
384
+ CREATE UNIQUE INDEX memories_task ON memories(account_id, COALESCE(project_id, '00000000-0000-0000-0000-000000000000'), task_id) WHERE task_id IS NOT NULL;
385
+ CREATE INDEX memories_owner_page ON memories(account_id, id);
386
+ CREATE INDEX memories_scope ON memories(account_id, project_id, status);
387
+ CREATE INDEX memories_lexical ON memories USING gin(search);
388
+ CREATE TABLE memory_revisions (
389
+ account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,
390
+ content text NOT NULL, source jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
391
+ PRIMARY KEY(account_id, memory_id, version),
392
+ FOREIGN KEY(account_id, memory_id) REFERENCES memories(account_id, id) ON DELETE CASCADE
393
+ );
394
+ CREATE TABLE memory_embeddings (
395
+ account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,
396
+ profile text NOT NULL, embedding vector(384) NOT NULL,
397
+ PRIMARY KEY(account_id, memory_id, version, profile),
398
+ FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE
399
+ );
400
+ CREATE TABLE memory_operations (
401
+ account_id uuid NOT NULL REFERENCES accounts(id), id uuid NOT NULL, fingerprint text NOT NULL,
402
+ result jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
403
+ PRIMARY KEY(account_id, id)
404
+ );
405
+ CREATE TABLE connections (
406
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
407
+ client_id text, name text NOT NULL, capabilities text[] NOT NULL,
408
+ personal boolean NOT NULL DEFAULT false, all_projects boolean NOT NULL DEFAULT false,
409
+ project_ids uuid[] NOT NULL DEFAULT '{}', revoked_at timestamptz, expires_at timestamptz,
410
+ authorized_after timestamptz NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now(),
411
+ last_used_at timestamptz, UNIQUE(account_id, client_id), UNIQUE(account_id, id)
412
+ );
413
+ CREATE TABLE api_keys (
414
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL,
415
+ connection_id uuid NOT NULL, digest text NOT NULL UNIQUE, prefix text NOT NULL,
416
+ created_at timestamptz NOT NULL DEFAULT now(),
417
+ FOREIGN KEY(account_id, connection_id) REFERENCES connections(account_id, id) ON DELETE CASCADE
418
+ );
419
+ CREATE TABLE jobs (
420
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL, memory_id uuid NOT NULL,
421
+ version integer NOT NULL, attempts integer NOT NULL DEFAULT 0,
422
+ due_at timestamptz NOT NULL DEFAULT now(), lease_id uuid, lease_until timestamptz,
423
+ failed_at timestamptz, error_code text,
424
+ UNIQUE(account_id, memory_id, version),
425
+ FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE
426
+ );
427
+ CREATE INDEX jobs_due ON jobs(due_at) WHERE failed_at IS NULL;
428
+ CREATE TABLE rate_buckets (
429
+ account_id uuid NOT NULL REFERENCES accounts(id), minute timestamptz NOT NULL,
430
+ count integer NOT NULL, PRIMARY KEY(account_id, minute)
431
+ );
432
+ CREATE TABLE deleted_memories (
433
+ account_id uuid NOT NULL REFERENCES accounts(id), id uuid NOT NULL,
434
+ deleted_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, id)
435
+ );
436
+ CREATE TABLE webhook_receipts (id text PRIMARY KEY, received_at timestamptz NOT NULL DEFAULT now());
437
+ CREATE TABLE session_revocations (id text PRIMARY KEY, revoked_at timestamptz NOT NULL DEFAULT now());
438
+ CREATE TABLE subject_authority (subject text PRIMARY KEY, event_at bigint NOT NULL, deleted boolean NOT NULL DEFAULT false);
439
+ `);
440
+ for (const table of [
441
+ "projects",
442
+ "memories",
443
+ "memory_revisions",
444
+ "memory_embeddings",
445
+ "memory_operations",
446
+ "connections",
447
+ "api_keys",
448
+ "jobs",
449
+ "rate_buckets",
450
+ "deleted_memories"
451
+ ]) {
452
+ await db2.raw(`ALTER TABLE ?? ENABLE ROW LEVEL SECURITY`, [table]);
453
+ await db2.raw(
454
+ `CREATE POLICY tenant ON ?? USING (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid) WITH CHECK (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid)`,
455
+ [table]
456
+ );
457
+ await db2.raw(
458
+ `GRANT SELECT, INSERT, UPDATE, DELETE ON ?? TO grove_runtime, grove_worker`,
459
+ [table]
460
+ );
461
+ }
462
+ await db2.raw(`
463
+ ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;
464
+ CREATE POLICY tenant ON accounts USING (id = NULLIF(current_setting('grove.account_id', true), '')::uuid);
465
+ GRANT SELECT, UPDATE ON accounts TO grove_runtime, grove_worker;
466
+ GRANT USAGE ON SCHEMA public TO grove_runtime, grove_worker;
467
+ CREATE FUNCTION grove_account(subject text) RETURNS SETOF accounts
468
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
469
+ BEGIN
470
+ PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));
471
+ IF EXISTS(SELECT 1 FROM subject_authority WHERE subject_authority.subject = grove_account.subject AND deleted) THEN
472
+ RETURN;
473
+ END IF;
474
+ INSERT INTO accounts(clerk_subject) VALUES(subject) ON CONFLICT(clerk_subject) DO NOTHING;
475
+ RETURN QUERY SELECT * FROM accounts WHERE clerk_subject = subject;
476
+ END $$;
477
+ CREATE FUNCTION grove_key(key_id uuid, key_digest text) RETURNS TABLE(account_id uuid, connection_id uuid, clerk_subject text)
478
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
479
+ SELECT k.account_id, k.connection_id, a.clerk_subject FROM api_keys k
480
+ JOIN accounts a ON a.id = k.account_id JOIN connections c ON c.id = k.connection_id AND c.account_id = k.account_id
481
+ WHERE k.id = key_id AND k.digest = key_digest AND a.status = 'active'
482
+ AND c.revoked_at IS NULL AND (c.expires_at IS NULL OR c.expires_at > now())
483
+ $$;
484
+ CREATE FUNCTION grove_session_revoked(session_id text) RETURNS boolean
485
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
486
+ SELECT EXISTS(SELECT 1 FROM session_revocations WHERE id = session_id)
487
+ $$;
488
+ CREATE FUNCTION grove_webhook(event_id text, event_type text, subject text, event_at bigint) RETURNS void
489
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
490
+ DECLARE owner_id uuid;
491
+ BEGIN
492
+ INSERT INTO webhook_receipts(id) VALUES(event_id) ON CONFLICT DO NOTHING;
493
+ IF NOT FOUND THEN RETURN; END IF;
494
+ IF event_type IN ('session.revoked','session.ended','session.removed') THEN
495
+ INSERT INTO session_revocations(id) VALUES(subject) ON CONFLICT DO NOTHING;
496
+ RETURN;
497
+ END IF;
498
+ PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));
499
+ IF event_type = 'user.deleted' THEN
500
+ INSERT INTO subject_authority VALUES(subject, event_at, true)
501
+ ON CONFLICT ON CONSTRAINT subject_authority_pkey DO UPDATE SET deleted = true;
502
+ UPDATE accounts SET status = 'deleting', deleted_at = now(), provider_deleted_at = now()
503
+ WHERE clerk_subject = subject AND status <> 'deleted' RETURNING id INTO owner_id;
504
+ UPDATE connections SET revoked_at = now() WHERE account_id = owner_id;
505
+ ELSIF event_type IN ('user.created','user.updated') THEN
506
+ INSERT INTO subject_authority VALUES(subject, event_at, false)
507
+ ON CONFLICT ON CONSTRAINT subject_authority_pkey DO UPDATE SET event_at = EXCLUDED.event_at
508
+ WHERE subject_authority.event_at < EXCLUDED.event_at AND NOT subject_authority.deleted;
509
+ END IF;
510
+ END $$;
511
+ CREATE FUNCTION grove_claim_job() RETURNS SETOF jobs
512
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
513
+ UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1
514
+ WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id
515
+ WHERE a.status = 'active' AND j.failed_at IS NULL AND j.due_at <= now()
516
+ AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at
517
+ FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *
518
+ $$;
519
+ CREATE FUNCTION grove_maintenance_accounts() RETURNS TABLE(id uuid, status text, clerk_subject text, provider_deleted_at timestamptz)
520
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
521
+ SELECT a.id, a.status, a.clerk_subject, a.provider_deleted_at FROM accounts a
522
+ WHERE a.status = 'deleting' OR EXISTS(SELECT 1 FROM memories m WHERE m.account_id = a.id AND m.purge_at <= now())
523
+ ORDER BY a.id LIMIT 100
524
+ $$;
525
+ REVOKE ALL ON FUNCTION grove_account(text), grove_key(uuid,text), grove_session_revoked(text), grove_webhook(text,text,text,bigint), grove_claim_job(), grove_maintenance_accounts() FROM PUBLIC;
526
+ GRANT EXECUTE ON FUNCTION grove_account(text), grove_key(uuid,text), grove_session_revoked(text), grove_webhook(text,text,text,bigint) TO grove_runtime;
527
+ GRANT EXECUTE ON FUNCTION grove_claim_job(), grove_maintenance_accounts() TO grove_worker;
528
+ `);
529
+ },
530
+ async down() {
531
+ throw new Error(
532
+ "Use a forward migration; rolling back would erase memory data"
533
+ );
534
+ }
535
+ },
536
+ hardening,
537
+ identityState,
538
+ {
539
+ name: "20261019_004_connection_setup",
540
+ async up(db2) {
541
+ await db2.raw("ALTER TABLE connections ADD COLUMN setup jsonb");
542
+ await db2.raw(
543
+ "CREATE INDEX connections_setup_id ON connections ((setup->>'id')) WHERE setup IS NOT NULL"
544
+ );
545
+ },
546
+ async down() {
547
+ throw new Error("Use a forward migration");
548
+ }
549
+ },
550
+ modelProviders,
551
+ memoryLifetimes,
552
+ backgroundServices
553
+ ];
554
+ var migrationSource = {
555
+ getMigrations: async () => migrations,
556
+ getMigrationName: (migration) => migration.name,
557
+ getMigration: async (migration) => migration
558
+ };
559
+
560
+ // lib/database/src/index.ts
561
+ function createDatabase(url2, options = {}) {
562
+ return knex({
563
+ client: "pg",
564
+ connection: {
565
+ connectionString: url2,
566
+ ssl: options.ssl ? { rejectUnauthorized: true } : void 0,
567
+ connectionTimeoutMillis: 1e4,
568
+ application_name: "grove"
569
+ },
570
+ pool: { min: 0, max: options.max ?? 8 },
571
+ acquireConnectionTimeout: 1e4,
572
+ ...knexSnakeCaseMappers(),
573
+ migrations: { migrationSource }
574
+ });
575
+ }
576
+ var closeDatabase = (db2) => db2.destroy();
577
+
578
+ // packages/api/src/migrate.ts
579
+ var url = process.env.MIGRATION_DATABASE_URL;
580
+ if (!url)
581
+ throw new Error(
582
+ "MIGRATION_DATABASE_URL is required; runtime credentials cannot run migrations"
583
+ );
584
+ var db = createDatabase(url, { ssl: process.env.DATABASE_SSL === "require" });
585
+ try {
586
+ const [, applied] = await db.migrate.latest();
587
+ console.log(JSON.stringify({ applied }));
588
+ } finally {
589
+ await closeDatabase(db);
590
+ }
591
+ //# sourceMappingURL=migrate.js.map