@miniaxolotl/grove-server 0.0.0-stage → 1.0.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,302 @@
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/migrations.ts
70
+ var migrations = [
71
+ {
72
+ name: "20261018_001_private_memory",
73
+ async up(db2) {
74
+ await db2.raw(`
75
+ CREATE EXTENSION IF NOT EXISTS vector;
76
+ DO $$ BEGIN
77
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'grove_runtime') THEN
78
+ CREATE ROLE grove_runtime NOLOGIN NOSUPERUSER NOBYPASSRLS;
79
+ END IF;
80
+ IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'grove_worker') THEN
81
+ CREATE ROLE grove_worker NOLOGIN NOSUPERUSER NOBYPASSRLS;
82
+ END IF;
83
+ END $$;
84
+ CREATE TABLE accounts (
85
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), clerk_subject text UNIQUE NOT NULL,
86
+ status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','disabled','deleting','deleted')),
87
+ content_version integer NOT NULL DEFAULT 0, capture_enabled boolean NOT NULL DEFAULT true,
88
+ recall_enabled boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(),
89
+ deleted_at timestamptz, provider_deleted_at timestamptz
90
+ );
91
+ CREATE TABLE projects (
92
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
93
+ name text NOT NULL, identity text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
94
+ UNIQUE(account_id, id), UNIQUE(account_id, identity)
95
+ );
96
+ CREATE TABLE memories (
97
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
98
+ project_id uuid, kind text NOT NULL CHECK (kind IN ('preference','fact','decision','solution','handoff')),
99
+ content text NOT NULL CHECK (length(content) BETWEEN 1 AND 6000),
100
+ search tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
101
+ status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','archived')),
102
+ version integer NOT NULL DEFAULT 1 CHECK (version > 0),
103
+ source jsonb NOT NULL, task_id text, expires_at timestamptz, purge_at timestamptz,
104
+ created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),
105
+ UNIQUE(account_id, id),
106
+ FOREIGN KEY (account_id, project_id) REFERENCES projects(account_id, id),
107
+ CHECK ((kind = 'handoff' AND task_id IS NOT NULL AND expires_at IS NOT NULL AND purge_at > expires_at)
108
+ OR (kind <> 'handoff' AND task_id IS NULL AND expires_at IS NULL AND purge_at IS NULL))
109
+ );
110
+ 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;
111
+ CREATE INDEX memories_owner_page ON memories(account_id, id);
112
+ CREATE INDEX memories_scope ON memories(account_id, project_id, status);
113
+ CREATE INDEX memories_lexical ON memories USING gin(search);
114
+ CREATE TABLE memory_revisions (
115
+ account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,
116
+ content text NOT NULL, source jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
117
+ PRIMARY KEY(account_id, memory_id, version),
118
+ FOREIGN KEY(account_id, memory_id) REFERENCES memories(account_id, id) ON DELETE CASCADE
119
+ );
120
+ CREATE TABLE memory_embeddings (
121
+ account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,
122
+ profile text NOT NULL, embedding vector(384) NOT NULL,
123
+ PRIMARY KEY(account_id, memory_id, version, profile),
124
+ FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE
125
+ );
126
+ CREATE TABLE memory_operations (
127
+ account_id uuid NOT NULL REFERENCES accounts(id), id uuid NOT NULL, fingerprint text NOT NULL,
128
+ result jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),
129
+ PRIMARY KEY(account_id, id)
130
+ );
131
+ CREATE TABLE connections (
132
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),
133
+ client_id text, name text NOT NULL, capabilities text[] NOT NULL,
134
+ personal boolean NOT NULL DEFAULT false, all_projects boolean NOT NULL DEFAULT false,
135
+ project_ids uuid[] NOT NULL DEFAULT '{}', revoked_at timestamptz, expires_at timestamptz,
136
+ authorized_after timestamptz NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now(),
137
+ last_used_at timestamptz, UNIQUE(account_id, client_id), UNIQUE(account_id, id)
138
+ );
139
+ CREATE TABLE api_keys (
140
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL,
141
+ connection_id uuid NOT NULL, digest text NOT NULL UNIQUE, prefix text NOT NULL,
142
+ created_at timestamptz NOT NULL DEFAULT now(),
143
+ FOREIGN KEY(account_id, connection_id) REFERENCES connections(account_id, id) ON DELETE CASCADE
144
+ );
145
+ CREATE TABLE jobs (
146
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL, memory_id uuid NOT NULL,
147
+ version integer NOT NULL, attempts integer NOT NULL DEFAULT 0,
148
+ due_at timestamptz NOT NULL DEFAULT now(), lease_id uuid, lease_until timestamptz,
149
+ failed_at timestamptz, error_code text,
150
+ UNIQUE(account_id, memory_id, version),
151
+ FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE
152
+ );
153
+ CREATE INDEX jobs_due ON jobs(due_at) WHERE failed_at IS NULL;
154
+ CREATE TABLE rate_buckets (
155
+ account_id uuid NOT NULL REFERENCES accounts(id), minute timestamptz NOT NULL,
156
+ count integer NOT NULL, PRIMARY KEY(account_id, minute)
157
+ );
158
+ CREATE TABLE deleted_memories (
159
+ account_id uuid NOT NULL REFERENCES accounts(id), id uuid NOT NULL,
160
+ deleted_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, id)
161
+ );
162
+ CREATE TABLE webhook_receipts (id text PRIMARY KEY, received_at timestamptz NOT NULL DEFAULT now());
163
+ CREATE TABLE session_revocations (id text PRIMARY KEY, revoked_at timestamptz NOT NULL DEFAULT now());
164
+ CREATE TABLE subject_authority (subject text PRIMARY KEY, event_at bigint NOT NULL, deleted boolean NOT NULL DEFAULT false);
165
+ `);
166
+ for (const table of [
167
+ "projects",
168
+ "memories",
169
+ "memory_revisions",
170
+ "memory_embeddings",
171
+ "memory_operations",
172
+ "connections",
173
+ "api_keys",
174
+ "jobs",
175
+ "rate_buckets",
176
+ "deleted_memories"
177
+ ]) {
178
+ await db2.raw(`ALTER TABLE ?? ENABLE ROW LEVEL SECURITY`, [table]);
179
+ await db2.raw(
180
+ `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)`,
181
+ [table]
182
+ );
183
+ await db2.raw(
184
+ `GRANT SELECT, INSERT, UPDATE, DELETE ON ?? TO grove_runtime, grove_worker`,
185
+ [table]
186
+ );
187
+ }
188
+ await db2.raw(`
189
+ ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;
190
+ CREATE POLICY tenant ON accounts USING (id = NULLIF(current_setting('grove.account_id', true), '')::uuid);
191
+ GRANT SELECT, UPDATE ON accounts TO grove_runtime, grove_worker;
192
+ GRANT USAGE ON SCHEMA public TO grove_runtime, grove_worker;
193
+ CREATE FUNCTION grove_account(subject text) RETURNS SETOF accounts
194
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
195
+ BEGIN
196
+ PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));
197
+ IF EXISTS(SELECT 1 FROM subject_authority WHERE subject_authority.subject = grove_account.subject AND deleted) THEN
198
+ RETURN;
199
+ END IF;
200
+ INSERT INTO accounts(clerk_subject) VALUES(subject) ON CONFLICT(clerk_subject) DO NOTHING;
201
+ RETURN QUERY SELECT * FROM accounts WHERE clerk_subject = subject;
202
+ END $$;
203
+ CREATE FUNCTION grove_key(key_id uuid, key_digest text) RETURNS TABLE(account_id uuid, connection_id uuid, clerk_subject text)
204
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
205
+ SELECT k.account_id, k.connection_id, a.clerk_subject FROM api_keys k
206
+ 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
207
+ WHERE k.id = key_id AND k.digest = key_digest AND a.status = 'active'
208
+ AND c.revoked_at IS NULL AND (c.expires_at IS NULL OR c.expires_at > now())
209
+ $$;
210
+ CREATE FUNCTION grove_session_revoked(session_id text) RETURNS boolean
211
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
212
+ SELECT EXISTS(SELECT 1 FROM session_revocations WHERE id = session_id)
213
+ $$;
214
+ CREATE FUNCTION grove_webhook(event_id text, event_type text, subject text, event_at bigint) RETURNS void
215
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
216
+ DECLARE owner_id uuid;
217
+ BEGIN
218
+ INSERT INTO webhook_receipts(id) VALUES(event_id) ON CONFLICT DO NOTHING;
219
+ IF NOT FOUND THEN RETURN; END IF;
220
+ IF event_type IN ('session.revoked','session.ended','session.removed') THEN
221
+ INSERT INTO session_revocations(id) VALUES(subject) ON CONFLICT DO NOTHING;
222
+ RETURN;
223
+ END IF;
224
+ PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));
225
+ IF event_type = 'user.deleted' THEN
226
+ INSERT INTO subject_authority VALUES(subject, event_at, true)
227
+ ON CONFLICT ON CONSTRAINT subject_authority_pkey DO UPDATE SET deleted = true;
228
+ UPDATE accounts SET status = 'deleting', deleted_at = now(), provider_deleted_at = now()
229
+ WHERE clerk_subject = subject AND status <> 'deleted' RETURNING id INTO owner_id;
230
+ UPDATE connections SET revoked_at = now() WHERE account_id = owner_id;
231
+ ELSIF event_type IN ('user.created','user.updated') THEN
232
+ INSERT INTO subject_authority VALUES(subject, event_at, false)
233
+ ON CONFLICT ON CONSTRAINT subject_authority_pkey DO UPDATE SET event_at = EXCLUDED.event_at
234
+ WHERE subject_authority.event_at < EXCLUDED.event_at AND NOT subject_authority.deleted;
235
+ END IF;
236
+ END $$;
237
+ CREATE FUNCTION grove_claim_job() RETURNS SETOF jobs
238
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
239
+ UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1
240
+ WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id
241
+ WHERE a.status = 'active' AND j.failed_at IS NULL AND j.due_at <= now()
242
+ AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at
243
+ FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *
244
+ $$;
245
+ CREATE FUNCTION grove_maintenance_accounts() RETURNS TABLE(id uuid, status text, clerk_subject text, provider_deleted_at timestamptz)
246
+ LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$
247
+ SELECT a.id, a.status, a.clerk_subject, a.provider_deleted_at FROM accounts a
248
+ WHERE a.status = 'deleting' OR EXISTS(SELECT 1 FROM memories m WHERE m.account_id = a.id AND m.purge_at <= now())
249
+ ORDER BY a.id LIMIT 100
250
+ $$;
251
+ 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;
252
+ GRANT EXECUTE ON FUNCTION grove_account(text), grove_key(uuid,text), grove_session_revoked(text), grove_webhook(text,text,text,bigint) TO grove_runtime;
253
+ GRANT EXECUTE ON FUNCTION grove_claim_job(), grove_maintenance_accounts() TO grove_worker;
254
+ `);
255
+ },
256
+ async down() {
257
+ throw new Error(
258
+ "Use a forward migration; rolling back would erase memory data"
259
+ );
260
+ }
261
+ },
262
+ hardening,
263
+ identityState
264
+ ];
265
+ var migrationSource = {
266
+ getMigrations: async () => migrations,
267
+ getMigrationName: (migration) => migration.name,
268
+ getMigration: async (migration) => migration
269
+ };
270
+
271
+ // lib/database/src/index.ts
272
+ function createDatabase(url2, options = {}) {
273
+ return knex({
274
+ client: "pg",
275
+ connection: {
276
+ connectionString: url2,
277
+ ssl: options.ssl ? { rejectUnauthorized: true } : void 0,
278
+ connectionTimeoutMillis: 1e4,
279
+ application_name: "grove"
280
+ },
281
+ pool: { min: 0, max: options.max ?? 8 },
282
+ acquireConnectionTimeout: 1e4,
283
+ ...knexSnakeCaseMappers(),
284
+ migrations: { migrationSource }
285
+ });
286
+ }
287
+ var closeDatabase = (db2) => db2.destroy();
288
+
289
+ // packages/api/src/migrate.ts
290
+ var url = process.env.MIGRATION_DATABASE_URL;
291
+ if (!url)
292
+ throw new Error(
293
+ "MIGRATION_DATABASE_URL is required; runtime credentials cannot run migrations"
294
+ );
295
+ var db = createDatabase(url, { ssl: process.env.DATABASE_SSL === "require" });
296
+ try {
297
+ const [, applied] = await db.migrate.latest();
298
+ console.log(JSON.stringify({ applied }));
299
+ } finally {
300
+ await closeDatabase(db);
301
+ }
302
+ //# sourceMappingURL=migrate.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../lib/database/src/index.ts", "../../../lib/database/src/hardening.ts", "../../../lib/database/src/migrations.ts", "../src/migrate.ts"],
4
+ "sourcesContent": ["import knex from \"knex\";\nimport { Model, knexSnakeCaseMappers } from \"objection\";\nimport type { Knex } from \"knex\";\nimport { migrationSource } from \"./migrations.ts\";\n\nexport { migrationSource };\nexport type { Knex };\n\nexport function createDatabase(\n url: string,\n options: { ssl?: boolean; max?: number } = {},\n) {\n return knex({\n client: \"pg\",\n connection: {\n connectionString: url,\n ssl: options.ssl ? { rejectUnauthorized: true } : undefined,\n connectionTimeoutMillis: 10000,\n application_name: \"grove\",\n },\n pool: { min: 0, max: options.max ?? 8 },\n acquireConnectionTimeout: 10000,\n ...knexSnakeCaseMappers(),\n migrations: { migrationSource },\n });\n}\n\nexport const closeDatabase = (db: Knex) => db.destroy();\n\n/** Knex's postProcessResponse maps query-builder rows, not pg's raw result wrapper. */\nexport function camelRows<T>(result: { rows: Record<string, unknown>[] }): T[] {\n return result.rows.map(\n (row) =>\n Object.fromEntries(\n Object.entries(row).map(([key, value]) => [\n key.replace(/_([a-z])/g, (_match, letter: string) =>\n letter.toUpperCase(),\n ),\n value,\n ]),\n ) as T,\n );\n}\n\nexport async function tenant<T>(\n db: Knex,\n accountId: string,\n run: (trx: Knex.Transaction) => Promise<T>,\n): Promise<T> {\n return db.transaction(async (trx) => {\n await trx.raw(\"SELECT set_config('grove.account_id', ?, true)\", [\n accountId,\n ]);\n await trx.raw(\"SET LOCAL statement_timeout = '10000ms'\");\n return run(trx);\n });\n}\n\nexport async function probeDatabase(db: Knex) {\n const { rows } = await db.raw(\n \"SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user\",\n );\n const owner = await db.raw(\n \"SELECT 1 FROM pg_tables WHERE tablename = 'memories' AND tableowner = current_user\",\n );\n if (rows[0]?.rolsuper || rows[0]?.rolbypassrls || owner.rows.length) {\n throw new Error(\n \"Grove requires a non-owner, non-bypass database runtime role\",\n );\n }\n await db.raw(\"SELECT content_version FROM accounts LIMIT 0\");\n const versions = await db.raw(\n \"SELECT extversion FROM pg_extension WHERE extname = 'vector'\",\n );\n if (!versions.rows[0]) throw new Error(\"The vector extension is required\");\n}\n\n/** Explicit transaction binding; no module-global connection or tenant state. */\nexport class MemoryModel extends Model {\n static tableName = \"memories\";\n id!: string;\n accountId!: string;\n projectId!: string | null;\n content!: string;\n kind!: \"preference\" | \"fact\" | \"decision\" | \"solution\" | \"handoff\";\n status!: \"active\" | \"archived\";\n version!: number;\n source!: {\n agent:\n | \"website\"\n | \"opencode\"\n | \"claude\"\n | \"codex\"\n | \"cli\"\n | \"import\"\n | \"api\";\n session?: string;\n verification?: string;\n };\n taskId!: string | null;\n expiresAt!: Date | null;\n purgeAt!: Date | null;\n createdAt!: Date;\n updatedAt!: Date;\n static jsonAttributes = [\"source\"];\n}\n", "import type { Knex } from \"knex\";\n\nexport const hardening = {\n name: \"20261018_002_lifecycle_bounds\",\n async up(db: Knex) {\n await db.raw(`\n REVOKE CREATE ON SCHEMA public FROM PUBLIC;\n CREATE OR REPLACE FUNCTION grove_claim_job() RETURNS SETOF jobs\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n UPDATE jobs SET failed_at = now(), error_code = 'lease_exhausted'\n WHERE failed_at IS NULL AND attempts >= 5 AND (lease_until IS NULL OR lease_until < now());\n RETURN QUERY UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1\n WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id\n WHERE a.status = 'active' AND j.failed_at IS NULL AND j.attempts < 5 AND j.due_at <= now()\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n CREATE OR REPLACE FUNCTION grove_maintenance_accounts() RETURNS TABLE(id uuid, status text, clerk_subject text, provider_deleted_at timestamptz)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n SELECT a.id, a.status, a.clerk_subject, a.provider_deleted_at FROM accounts a\n WHERE a.status = 'deleting' OR EXISTS(SELECT 1 FROM memories m WHERE m.account_id = a.id AND m.purge_at <= now())\n OR EXISTS(SELECT 1 FROM rate_buckets b WHERE b.account_id = a.id AND b.minute < now() - interval '1 day')\n ORDER BY a.id LIMIT 100\n $$;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n\nexport const identityState = {\n name: \"20261018_003_identity_state\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE subject_authority ADD COLUMN disabled boolean NOT NULL DEFAULT false;\n CREATE FUNCTION grove_user_state(subject text, event_at bigint, disabled boolean) RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n UPDATE subject_authority s SET disabled = grove_user_state.disabled\n WHERE s.subject = grove_user_state.subject AND s.event_at = grove_user_state.event_at AND NOT s.deleted;\n IF NOT FOUND THEN RETURN; END IF;\n UPDATE accounts SET status = CASE WHEN disabled THEN 'disabled' ELSE 'active' END\n WHERE clerk_subject = subject AND status IN ('active', 'disabled');\n END\n $$;\n CREATE OR REPLACE FUNCTION grove_account(subject text) RETURNS SETOF accounts\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));\n IF EXISTS(SELECT 1 FROM subject_authority s WHERE s.subject = grove_account.subject AND (s.deleted OR s.disabled)) THEN RETURN; END IF;\n INSERT INTO accounts(clerk_subject) VALUES(subject) ON CONFLICT(clerk_subject) DO NOTHING;\n RETURN QUERY SELECT * FROM accounts WHERE clerk_subject = subject;\n END $$;\n REVOKE ALL ON FUNCTION grove_user_state(text,bigint,boolean) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_user_state(text,bigint,boolean) TO grove_runtime;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\nimport { hardening, identityState } from \"./hardening.ts\";\n\nexport const migrations = [\n {\n name: \"20261018_001_private_memory\",\n async up(db: Knex) {\n await db.raw(`\n CREATE EXTENSION IF NOT EXISTS vector;\n DO $$ BEGIN\n IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'grove_runtime') THEN\n CREATE ROLE grove_runtime NOLOGIN NOSUPERUSER NOBYPASSRLS;\n END IF;\n IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'grove_worker') THEN\n CREATE ROLE grove_worker NOLOGIN NOSUPERUSER NOBYPASSRLS;\n END IF;\n END $$;\n CREATE TABLE accounts (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), clerk_subject text UNIQUE NOT NULL,\n status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','disabled','deleting','deleted')),\n content_version integer NOT NULL DEFAULT 0, capture_enabled boolean NOT NULL DEFAULT true,\n recall_enabled boolean NOT NULL DEFAULT true, created_at timestamptz NOT NULL DEFAULT now(),\n deleted_at timestamptz, provider_deleted_at timestamptz\n );\n CREATE TABLE projects (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),\n name text NOT NULL, identity text NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, id), UNIQUE(account_id, identity)\n );\n CREATE TABLE memories (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),\n project_id uuid, kind text NOT NULL CHECK (kind IN ('preference','fact','decision','solution','handoff')),\n content text NOT NULL CHECK (length(content) BETWEEN 1 AND 6000),\n search tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,\n status text NOT NULL DEFAULT 'active' CHECK (status IN ('active','archived')),\n version integer NOT NULL DEFAULT 1 CHECK (version > 0),\n source jsonb NOT NULL, task_id text, expires_at timestamptz, purge_at timestamptz,\n created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, id),\n FOREIGN KEY (account_id, project_id) REFERENCES projects(account_id, id),\n CHECK ((kind = 'handoff' AND task_id IS NOT NULL AND expires_at IS NOT NULL AND purge_at > expires_at)\n OR (kind <> 'handoff' AND task_id IS NULL AND expires_at IS NULL AND purge_at IS NULL))\n );\n 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;\n CREATE INDEX memories_owner_page ON memories(account_id, id);\n CREATE INDEX memories_scope ON memories(account_id, project_id, status);\n CREATE INDEX memories_lexical ON memories USING gin(search);\n CREATE TABLE memory_revisions (\n account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,\n content text NOT NULL, source jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id, memory_id, version),\n FOREIGN KEY(account_id, memory_id) REFERENCES memories(account_id, id) ON DELETE CASCADE\n );\n CREATE TABLE memory_embeddings (\n account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,\n profile text NOT NULL, embedding vector(384) NOT NULL,\n PRIMARY KEY(account_id, memory_id, version, profile),\n FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE\n );\n CREATE TABLE memory_operations (\n account_id uuid NOT NULL REFERENCES accounts(id), id uuid NOT NULL, fingerprint text NOT NULL,\n result jsonb NOT NULL, created_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id, id)\n );\n CREATE TABLE connections (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),\n client_id text, name text NOT NULL, capabilities text[] NOT NULL,\n personal boolean NOT NULL DEFAULT false, all_projects boolean NOT NULL DEFAULT false,\n project_ids uuid[] NOT NULL DEFAULT '{}', revoked_at timestamptz, expires_at timestamptz,\n authorized_after timestamptz NOT NULL DEFAULT now(), created_at timestamptz NOT NULL DEFAULT now(),\n last_used_at timestamptz, UNIQUE(account_id, client_id), UNIQUE(account_id, id)\n );\n CREATE TABLE api_keys (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL,\n connection_id uuid NOT NULL, digest text NOT NULL UNIQUE, prefix text NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n FOREIGN KEY(account_id, connection_id) REFERENCES connections(account_id, id) ON DELETE CASCADE\n );\n CREATE TABLE jobs (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL, memory_id uuid NOT NULL,\n version integer NOT NULL, attempts integer NOT NULL DEFAULT 0,\n due_at timestamptz NOT NULL DEFAULT now(), lease_id uuid, lease_until timestamptz,\n failed_at timestamptz, error_code text,\n UNIQUE(account_id, memory_id, version),\n FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE\n );\n CREATE INDEX jobs_due ON jobs(due_at) WHERE failed_at IS NULL;\n CREATE TABLE rate_buckets (\n account_id uuid NOT NULL REFERENCES accounts(id), minute timestamptz NOT NULL,\n count integer NOT NULL, PRIMARY KEY(account_id, minute)\n );\n CREATE TABLE deleted_memories (\n account_id uuid NOT NULL REFERENCES accounts(id), id uuid NOT NULL,\n deleted_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, id)\n );\n CREATE TABLE webhook_receipts (id text PRIMARY KEY, received_at timestamptz NOT NULL DEFAULT now());\n CREATE TABLE session_revocations (id text PRIMARY KEY, revoked_at timestamptz NOT NULL DEFAULT now());\n CREATE TABLE subject_authority (subject text PRIMARY KEY, event_at bigint NOT NULL, deleted boolean NOT NULL DEFAULT false);\n `);\n\n for (const table of [\n \"projects\",\n \"memories\",\n \"memory_revisions\",\n \"memory_embeddings\",\n \"memory_operations\",\n \"connections\",\n \"api_keys\",\n \"jobs\",\n \"rate_buckets\",\n \"deleted_memories\",\n ]) {\n await db.raw(`ALTER TABLE ?? ENABLE ROW LEVEL SECURITY`, [table]);\n await db.raw(\n `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)`,\n [table],\n );\n await db.raw(\n `GRANT SELECT, INSERT, UPDATE, DELETE ON ?? TO grove_runtime, grove_worker`,\n [table],\n );\n }\n await db.raw(`\n ALTER TABLE accounts ENABLE ROW LEVEL SECURITY;\n CREATE POLICY tenant ON accounts USING (id = NULLIF(current_setting('grove.account_id', true), '')::uuid);\n GRANT SELECT, UPDATE ON accounts TO grove_runtime, grove_worker;\n GRANT USAGE ON SCHEMA public TO grove_runtime, grove_worker;\n CREATE FUNCTION grove_account(subject text) RETURNS SETOF accounts\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));\n IF EXISTS(SELECT 1 FROM subject_authority WHERE subject_authority.subject = grove_account.subject AND deleted) THEN\n RETURN;\n END IF;\n INSERT INTO accounts(clerk_subject) VALUES(subject) ON CONFLICT(clerk_subject) DO NOTHING;\n RETURN QUERY SELECT * FROM accounts WHERE clerk_subject = subject;\n END $$;\n CREATE FUNCTION grove_key(key_id uuid, key_digest text) RETURNS TABLE(account_id uuid, connection_id uuid, clerk_subject text)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n SELECT k.account_id, k.connection_id, a.clerk_subject FROM api_keys k\n 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\n WHERE k.id = key_id AND k.digest = key_digest AND a.status = 'active'\n AND c.revoked_at IS NULL AND (c.expires_at IS NULL OR c.expires_at > now())\n $$;\n CREATE FUNCTION grove_session_revoked(session_id text) RETURNS boolean\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n SELECT EXISTS(SELECT 1 FROM session_revocations WHERE id = session_id)\n $$;\n CREATE FUNCTION grove_webhook(event_id text, event_type text, subject text, event_at bigint) RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n DECLARE owner_id uuid;\n BEGIN\n INSERT INTO webhook_receipts(id) VALUES(event_id) ON CONFLICT DO NOTHING;\n IF NOT FOUND THEN RETURN; END IF;\n IF event_type IN ('session.revoked','session.ended','session.removed') THEN\n INSERT INTO session_revocations(id) VALUES(subject) ON CONFLICT DO NOTHING;\n RETURN;\n END IF;\n PERFORM pg_advisory_xact_lock(hashtextextended(subject, 1));\n IF event_type = 'user.deleted' THEN\n INSERT INTO subject_authority VALUES(subject, event_at, true)\n ON CONFLICT ON CONSTRAINT subject_authority_pkey DO UPDATE SET deleted = true;\n UPDATE accounts SET status = 'deleting', deleted_at = now(), provider_deleted_at = now()\n WHERE clerk_subject = subject AND status <> 'deleted' RETURNING id INTO owner_id;\n UPDATE connections SET revoked_at = now() WHERE account_id = owner_id;\n ELSIF event_type IN ('user.created','user.updated') THEN\n INSERT INTO subject_authority VALUES(subject, event_at, false)\n ON CONFLICT ON CONSTRAINT subject_authority_pkey DO UPDATE SET event_at = EXCLUDED.event_at\n WHERE subject_authority.event_at < EXCLUDED.event_at AND NOT subject_authority.deleted;\n END IF;\n END $$;\n CREATE FUNCTION grove_claim_job() RETURNS SETOF jobs\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n UPDATE jobs SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1\n WHERE id = (SELECT j.id FROM jobs j JOIN accounts a ON a.id = j.account_id\n WHERE a.status = 'active' AND j.failed_at IS NULL AND j.due_at <= now()\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *\n $$;\n CREATE FUNCTION grove_maintenance_accounts() RETURNS TABLE(id uuid, status text, clerk_subject text, provider_deleted_at timestamptz)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n SELECT a.id, a.status, a.clerk_subject, a.provider_deleted_at FROM accounts a\n WHERE a.status = 'deleting' OR EXISTS(SELECT 1 FROM memories m WHERE m.account_id = a.id AND m.purge_at <= now())\n ORDER BY a.id LIMIT 100\n $$;\n 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;\n GRANT EXECUTE ON FUNCTION grove_account(text), grove_key(uuid,text), grove_session_revoked(text), grove_webhook(text,text,text,bigint) TO grove_runtime;\n GRANT EXECUTE ON FUNCTION grove_claim_job(), grove_maintenance_accounts() TO grove_worker;\n `);\n },\n async down() {\n throw new Error(\n \"Use a forward migration; rolling back would erase memory data\",\n );\n },\n },\n hardening,\n identityState,\n];\n\nexport const migrationSource: Knex.MigrationSource<\n (typeof migrations)[number]\n> = {\n getMigrations: async () => migrations,\n getMigrationName: (migration) => migration.name,\n getMigration: async (migration) => migration,\n};\n", "import { createDatabase, closeDatabase } from \"@lib/database\";\n\nconst url = process.env.MIGRATION_DATABASE_URL;\nif (!url)\n throw new Error(\n \"MIGRATION_DATABASE_URL is required; runtime credentials cannot run migrations\",\n );\nconst db = createDatabase(url, { ssl: process.env.DATABASE_SSL === \"require\" });\ntry {\n const [, applied] = await db.migrate.latest();\n console.log(JSON.stringify({ applied }));\n} finally {\n await closeDatabase(db);\n}\n"],
5
+ "mappings": "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",
6
+ "names": ["db", "db", "url", "db"]
7
+ }