@miniaxolotl/grove-server 1.8.1 → 1.10.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.
- package/dist/bootstrap.js +374 -1
- package/dist/bootstrap.js.map +4 -4
- package/dist/migrate.js +374 -1
- package/dist/migrate.js.map +4 -4
- package/dist/server.js +2363 -291
- package/dist/server.js.map +4 -4
- package/dist/telemetry-build.json +1 -1
- package/dist/worker.js +1693 -131
- package/dist/worker.js.map +4 -4
- package/package.json +1 -1
package/dist/bootstrap.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../../../lib/database/src/index.ts", "../../../lib/database/src/hardening.ts", "../../../lib/database/src/model-migration.ts", "../../../lib/database/src/lifetime-migration.ts", "../../../lib/database/src/background-migration.ts", "../../../lib/database/src/notebook-migration.ts", "../../../lib/database/src/conversation-migration.ts", "../../../lib/database/src/migrations.ts", "../src/bootstrap.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 autoKind!: boolean;\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 retentionDays!: number | 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\";\n\nexport const modelProviders = {\n // 004 belongs to the independently reviewed cloud-onboarding PR.\n name: \"20261019_005_model_providers\",\n async up(db: Knex) {\n await db.raw(`\n CREATE TABLE model_settings (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n version integer NOT NULL DEFAULT 0, encrypted text NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n );\n GRANT SELECT ON model_settings TO grove_runtime, grove_worker;\n GRANT INSERT, UPDATE ON model_settings TO grove_runtime;\n CREATE TABLE embedding_profiles (\n id text PRIMARY KEY, model text NOT NULL, dimensions integer NOT NULL CHECK (dimensions BETWEEN 32 AND 16000),\n created_at timestamptz NOT NULL DEFAULT now(), UNIQUE(id, dimensions)\n );\n GRANT SELECT, INSERT ON embedding_profiles TO grove_runtime, grove_worker;\n INSERT INTO embedding_profiles(id, model, dimensions)\n SELECT DISTINCT profile, 'legacy', 384 FROM memory_embeddings;\n ALTER TABLE memory_embeddings ALTER COLUMN embedding TYPE vector;\n ALTER TABLE memory_embeddings ADD COLUMN dimensions integer NOT NULL DEFAULT 384;\n ALTER TABLE memory_embeddings ADD CONSTRAINT embedding_dimensions CHECK (vector_dims(embedding) = dimensions);\n ALTER TABLE memory_embeddings ADD CONSTRAINT embedding_profile_fk FOREIGN KEY (profile, dimensions) REFERENCES embedding_profiles(id, dimensions);\n ALTER TABLE memories ADD COLUMN auto_kind boolean NOT NULL DEFAULT false;\n ALTER TABLE accounts ADD COLUMN organize_enabled boolean NOT NULL DEFAULT true;\n ALTER TABLE accounts ADD COLUMN summaries_enabled boolean NOT NULL DEFAULT true;\n\n ALTER TABLE jobs DROP CONSTRAINT jobs_account_id_memory_id_version_key;\n ALTER TABLE jobs ALTER COLUMN memory_id DROP NOT NULL;\n ALTER TABLE jobs ALTER COLUMN version DROP NOT NULL;\n ALTER TABLE jobs ADD COLUMN kind text NOT NULL DEFAULT 'embedding' CHECK (kind IN ('embedding','decision','organization','brief'));\n ALTER TABLE jobs ADD COLUMN profile text NOT NULL DEFAULT 'minilm-l6-v2-mean-normalized-v1';\n ALTER TABLE jobs ADD COLUMN target text;\n UPDATE jobs SET target = memory_id::text;\n ALTER TABLE jobs ALTER COLUMN target SET NOT NULL;\n ALTER TABLE jobs ADD COLUMN scope jsonb;\n 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));\n ALTER TABLE jobs ADD CONSTRAINT job_identity UNIQUE(account_id, kind, target, profile);\n\n CREATE TABLE memory_enrichments (\n account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,\n kind text NOT NULL CHECK (kind IN ('decision','organization')), profile text NOT NULL,\n data jsonb NOT NULL, sources jsonb NOT NULL DEFAULT '[]', created_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id, memory_id, version, kind, profile),\n FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE\n );\n CREATE TABLE memory_briefs (\n account_id uuid NOT NULL REFERENCES accounts(id), target text NOT NULL,\n scope jsonb NOT NULL, profile text NOT NULL, content_version integer NOT NULL,\n content jsonb NOT NULL, sources jsonb NOT NULL, truncated boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, target, profile)\n );\n CREATE TABLE inference_usage (\n account_id uuid NOT NULL REFERENCES accounts(id), day date NOT NULL DEFAULT CURRENT_DATE,\n role text NOT NULL, requests integer NOT NULL DEFAULT 0, input_tokens bigint NOT NULL DEFAULT 0,\n output_tokens bigint NOT NULL DEFAULT 0, PRIMARY KEY(account_id, day, role)\n );\n `);\n for (const table of [\n \"memory_enrichments\",\n \"memory_briefs\",\n \"inference_usage\",\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 DROP FUNCTION grove_claim_job();\n CREATE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL) 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 (profiles IS NULL OR j.profile = ANY(profiles))\n 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))))\n 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))))\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_job(text[]) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_job(text[]) TO grove_worker;\n CREATE FUNCTION grove_reprocess(embedding_profile text, decision_profile text, generation_profile text) RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n DELETE FROM jobs;\n DELETE FROM memory_briefs;\n INSERT INTO jobs(account_id, memory_id, version, target, kind, profile)\n SELECT m.account_id, m.id, m.version, m.id::text, p.kind, p.profile\n FROM memories m JOIN accounts a ON a.id = m.account_id\n CROSS JOIN (VALUES ('embedding', embedding_profile), ('decision', decision_profile), ('organization', generation_profile)) AS p(kind, profile)\n WHERE a.status = 'active' AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now())\n AND p.profile IS NOT NULL AND (p.kind = 'embedding' OR a.organize_enabled);\n IF generation_profile IS NOT NULL THEN\n INSERT INTO jobs(account_id, kind, target, profile, scope, due_at)\n SELECT DISTINCT m.account_id, 'brief', COALESCE(m.project_id::text, 'personal'), generation_profile,\n jsonb_build_object('projectId', m.project_id), now() + interval '5 seconds'\n FROM memories m JOIN accounts a ON a.id = m.account_id\n WHERE a.status = 'active' AND a.summaries_enabled AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now());\n INSERT INTO jobs(account_id, kind, target, profile, scope, due_at)\n SELECT m.account_id, 'brief', COALESCE(m.project_id::text, 'personal') || ':task:' || m.task_id, generation_profile,\n jsonb_build_object('projectId', m.project_id, 'taskId', m.task_id), now() + interval '5 seconds'\n FROM memories m JOIN accounts a ON a.id = m.account_id\n WHERE a.status = 'active' AND a.summaries_enabled AND m.status = 'active' AND m.kind = 'handoff' AND m.expires_at > now();\n END IF;\n END $$;\n REVOKE ALL ON FUNCTION grove_reprocess(text,text,text) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_reprocess(text,text,text) TO grove_runtime;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const memoryLifetimes = {\n name: \"20261020_006_memory_lifetimes\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE memories DROP CONSTRAINT memories_check;\n ALTER TABLE memories ADD COLUMN retention_days integer CHECK (retention_days BETWEEN 1 AND 365);\n UPDATE memories SET retention_days = 30 WHERE expires_at IS NOT NULL;\n ALTER TABLE memories ADD CONSTRAINT memory_task_reference CHECK ((kind = 'handoff') = (task_id IS NOT NULL));\n ALTER TABLE memories ADD CONSTRAINT memory_lifetime CHECK (\n (retention_days IS NULL AND expires_at IS NULL AND purge_at IS NULL) OR\n (retention_days IS NOT NULL AND expires_at IS NOT NULL AND purge_at IS NOT NULL AND purge_at > expires_at)\n );\n CREATE INDEX memories_updated_page ON memories(account_id, updated_at DESC, id DESC);\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const backgroundServices = {\n name: \"20261020_007_background_services\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE accounts ADD COLUMN organization_due_at timestamptz NOT NULL DEFAULT now();\n ALTER TABLE accounts ADD COLUMN organization_checked_at timestamptz;\n ALTER TABLE jobs ADD COLUMN dispatched_at timestamptz;\n CREATE TABLE transactional_emails (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),\n event_key text NOT NULL, kind text NOT NULL CHECK (kind IN ('welcome','connection_approved','connection_revoked')),\n created_at timestamptz NOT NULL DEFAULT now(), due_at timestamptz NOT NULL DEFAULT now(),\n attempts integer NOT NULL DEFAULT 0, lease_id uuid, lease_until timestamptz,\n dispatched_at timestamptz, sent_at timestamptz, provider_id text, failed_at timestamptz, error_code text,\n UNIQUE(account_id, event_key)\n );\n ALTER TABLE transactional_emails ENABLE ROW LEVEL SECURITY;\n CREATE POLICY tenant ON transactional_emails USING (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid)\n WITH CHECK (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid);\n GRANT SELECT, INSERT, UPDATE, DELETE ON transactional_emails TO grove_worker;\n CREATE INDEX transactional_emails_due ON transactional_emails(due_at) WHERE sent_at IS NULL AND failed_at IS NULL;\n\n CREATE FUNCTION grove_queue_transactional_email() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n DECLARE event_kind text; owner_id uuid; event_identity text;\n BEGIN\n IF TG_TABLE_NAME = 'accounts' THEN\n owner_id := NEW.id; event_kind := 'welcome'; event_identity := 'welcome';\n ELSE\n owner_id := NEW.account_id;\n IF NOT EXISTS (SELECT 1 FROM accounts WHERE id = owner_id AND status = 'active') THEN RETURN NEW; END IF;\n IF TG_OP = 'INSERT' THEN\n IF cardinality(NEW.capabilities) = 0 OR NEW.revoked_at IS NOT NULL THEN RETURN NEW; END IF;\n event_kind := 'connection_approved';\n ELSIF OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL THEN\n IF cardinality(OLD.capabilities) = 0 THEN RETURN NEW; END IF;\n event_kind := 'connection_revoked';\n ELSIF cardinality(NEW.capabilities) > 0 AND NEW.revoked_at IS NULL AND (cardinality(OLD.capabilities) = 0 OR OLD.revoked_at IS NOT NULL) THEN\n event_kind := 'connection_approved';\n ELSE RETURN NEW;\n END IF;\n event_identity := event_kind || ':' || NEW.id::text || ':' || txid_current()::text;\n END IF;\n INSERT INTO transactional_emails(account_id, event_key, kind) VALUES(owner_id, event_identity, event_kind)\n ON CONFLICT(account_id, event_key) DO NOTHING;\n RETURN NEW;\n END $$;\n REVOKE ALL ON FUNCTION grove_queue_transactional_email() FROM PUBLIC;\n CREATE TRIGGER account_welcome AFTER INSERT ON accounts FOR EACH ROW EXECUTE FUNCTION grove_queue_transactional_email();\n CREATE TRIGGER connection_notification AFTER INSERT OR UPDATE ON connections FOR EACH ROW EXECUTE FUNCTION grove_queue_transactional_email();\n\n DROP FUNCTION grove_claim_job(text[]);\n CREATE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL, wanted uuid DEFAULT NULL) 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 (wanted IS NULL OR j.id = wanted) AND (profiles IS NULL OR j.profile = ANY(profiles))\n 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))))\n 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))))\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_job(text[],uuid) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_job(text[],uuid) TO grove_worker;\n\n CREATE FUNCTION grove_claim_email(wanted uuid DEFAULT NULL) RETURNS SETOF transactional_emails\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n UPDATE transactional_emails SET failed_at = now(), error_code = 'delivery_exhausted'\n WHERE sent_at IS NULL AND failed_at IS NULL AND (attempts >= 5 OR created_at < now() - interval '23 hours')\n AND (lease_until IS NULL OR lease_until < now());\n RETURN QUERY UPDATE transactional_emails SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1\n WHERE id = (SELECT e.id FROM transactional_emails e JOIN accounts a ON a.id = e.account_id\n WHERE a.status = 'active' AND e.sent_at IS NULL AND e.failed_at IS NULL AND e.due_at <= now()\n AND (wanted IS NULL OR e.id = wanted) AND (e.lease_until IS NULL OR e.lease_until < now())\n ORDER BY e.due_at, e.id FOR UPDATE OF e SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_email(uuid) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_email(uuid) TO grove_worker;\n\n CREATE FUNCTION grove_due_dispatch(profiles text[], mail_enabled boolean) RETURNS TABLE(id uuid, account_id uuid, queue_kind text)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n SELECT due.id, due.account_id, due.queue_kind FROM (\n 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\n WHERE a.status = 'active' AND j.profile = ANY(profiles) AND j.failed_at IS NULL AND j.attempts < 5\n AND j.due_at <= now() AND (j.lease_until IS NULL OR j.lease_until < now())\n AND (j.dispatched_at IS NULL OR j.dispatched_at < now() - interval '60 seconds')\n UNION ALL\n 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\n WHERE mail_enabled AND a.status = 'active' AND e.sent_at IS NULL AND e.failed_at IS NULL AND e.attempts < 5\n AND e.created_at > now() - interval '23 hours' AND e.due_at <= now() AND (e.lease_until IS NULL OR e.lease_until < now())\n AND (e.dispatched_at IS NULL OR e.dispatched_at < now() - interval '60 seconds')\n ) due ORDER BY due.due_at, due.id LIMIT 100;\n $$;\n REVOKE ALL ON FUNCTION grove_due_dispatch(text[],boolean) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_due_dispatch(text[],boolean) TO grove_worker;\n\n CREATE FUNCTION grove_organization_accounts(interval_seconds integer) RETURNS TABLE(id uuid)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n UPDATE accounts SET organization_due_at = now() + (greatest(60, least(interval_seconds, 86400)) * interval '1 second'), organization_checked_at = now()\n WHERE accounts.id IN (SELECT a.id FROM accounts a WHERE a.status = 'active' AND a.organization_due_at <= now()\n ORDER BY a.organization_due_at, a.id FOR UPDATE SKIP LOCKED LIMIT 20) RETURNING accounts.id;\n $$;\n REVOKE ALL ON FUNCTION grove_organization_accounts(integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_organization_accounts(integer) TO grove_worker;\n\n CREATE FUNCTION grove_sweep_deliveries() RETURNS void\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 UPDATE transactional_emails SET failed_at = now(), error_code = 'delivery_exhausted'\n WHERE sent_at IS NULL AND failed_at IS NULL AND (attempts >= 5 OR created_at < now() - interval '23 hours')\n AND (lease_until IS NULL OR lease_until < now());\n END $$;\n REVOKE ALL ON FUNCTION grove_sweep_deliveries() FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_sweep_deliveries() TO grove_worker;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const nestedNotebooks = {\n name: \"20261020_008_nested_notebooks\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE projects\n ADD COLUMN parent_id uuid,\n ADD COLUMN version integer NOT NULL DEFAULT 1 CHECK (version > 0),\n ADD CONSTRAINT projects_parent_owner FOREIGN KEY (account_id, parent_id)\n REFERENCES projects(account_id, id) ON DELETE SET NULL (parent_id),\n ADD CONSTRAINT projects_not_own_parent CHECK (parent_id IS DISTINCT FROM id);\n CREATE INDEX projects_parent ON projects(account_id, parent_id);\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const conversations = {\n name: \"20261020_009_conversations\",\n async up(db: Knex) {\n await db.raw(`\n CREATE TABLE conversations (\n id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES accounts(id),\n title text NOT NULL DEFAULT 'New conversation', scope jsonb NOT NULL,\n version integer NOT NULL DEFAULT 0 CHECK (version >= 0),\n created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, id)\n );\n CREATE INDEX conversations_recent ON conversations(account_id, updated_at DESC, id DESC);\n CREATE TABLE deleted_conversations (\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 conversation_turns (\n id uuid PRIMARY KEY, account_id uuid NOT NULL, conversation_id uuid NOT NULL,\n position integer NOT NULL CHECK (position > 0), question text NOT NULL,\n format text NOT NULL DEFAULT 'plain' CHECK (format IN ('plain','markdown')),\n fingerprint text NOT NULL, status text NOT NULL CHECK (status IN ('pending','ready','failed')),\n result jsonb, undo jsonb, error text, lease_id uuid, lease_until timestamptz,\n created_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, conversation_id, position),\n FOREIGN KEY(account_id, conversation_id) REFERENCES conversations(account_id, id) ON DELETE CASCADE\n );\n `);\n for (const table of [\n \"conversations\",\n \"conversation_turns\",\n \"deleted_conversations\",\n ]) {\n await db.raw(\"ALTER TABLE ?? ENABLE ROW LEVEL SECURITY\", [table]);\n await db.raw(\"ALTER TABLE ?? FORCE 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 },\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\";\nimport { modelProviders } from \"./model-migration.ts\";\nimport { memoryLifetimes } from \"./lifetime-migration.ts\";\nimport { backgroundServices } from \"./background-migration.ts\";\nimport { nestedNotebooks } from \"./notebook-migration.ts\";\nimport { conversations } from \"./conversation-migration.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 name: \"20261019_004_connection_setup\",\n async up(db: Knex) {\n // One bounded, replaceable attempt per existing RLS-protected connection.\n await db.raw(\"ALTER TABLE connections ADD COLUMN setup jsonb\");\n await db.raw(\n \"CREATE INDEX connections_setup_id ON connections ((setup->>'id')) WHERE setup IS NOT NULL\",\n );\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n },\n modelProviders,\n memoryLifetimes,\n backgroundServices,\n nestedNotebooks,\n conversations,\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 } from \"@lib/database\";\n\nconst url = process.env.MIGRATION_DATABASE_URL;\nif (!url) throw new Error(\"MIGRATION_DATABASE_URL is required\");\nconst db = createDatabase(url, { ssl: process.env.DATABASE_SSL === \"require\" });\ntry {\n await db.migrate.latest();\n for (const [name, role, password] of [\n [\"grove_api\", \"grove_runtime\", process.env.API_DATABASE_PASSWORD],\n [\"grove_jobs\", \"grove_worker\", process.env.WORKER_DATABASE_PASSWORD],\n ] as const) {\n if (!password || password.length < 16)\n throw new Error(\n \"Runtime database passwords must have at least 16 characters\",\n );\n const existing = await db.raw(\n \"SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = ?\",\n [name],\n );\n if (!existing.rows.length) {\n const result = await db.raw(\n \"SELECT format('CREATE ROLE %I LOGIN PASSWORD %L NOSUPERUSER NOBYPASSRLS', ?::text, ?::text) AS statement\",\n [name, password],\n );\n await db.raw(result.rows[0].statement);\n } else if (existing.rows[0].rolsuper || existing.rows[0].rolbypassrls)\n throw new Error(\"Runtime role has unsafe privileges\");\n await db.raw(\"GRANT ?? TO ??\", [role!, name!]);\n }\n console.log(JSON.stringify({ status: \"schema-and-roles-ready\" }));\n} finally {\n await db.destroy();\n}\n"],
|
|
5
|
-
"mappings": ";;;AAAA,OAAO,UAAU;AACjB,SAAS,OAAO,4BAA4B;;;ACCrC,IAAM,YAAY;AAAA,EACvB,MAAM;AAAA,EACN,MAAM,GAAGA,KAAU;AACjB,UAAMA,IAAG,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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A;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAqHZ;AAAA,EACH;AAAA,EACA,MAAM,OAAO;AACX,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;;;AC7HO,IAAM,kBAAkB;AAAA,EAC7B,MAAM;AAAA,EACN,MAAM,GAAGC,KAAU;AACjB,UAAMA,IAAG,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAQZ;AAAA,EACH;AAAA,EACA,MAAM,OAAO;AACX,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;;;AChBO,IAAM,gBAAgB;AAAA,EAC3B,MAAM;AAAA,EACN,MAAM,GAAGC,KAAU;AACjB,UAAMA,IAAG,IAAI;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAuBZ;AACD,eAAW,SAAS;AAAA,MAClB;AAAA,MACA;AAAA,MACA;AAAA,IACF,GAAG;AACD,YAAMA,IAAG,IAAI,4CAA4C,CAAC,KAAK,CAAC;AAChE,YAAMA,IAAG,IAAI,2CAA2C,CAAC,KAAK,CAAC;AAC/D,YAAMA,IAAG;AAAA,QACP;AAAA,QACA,CAAC,KAAK;AAAA,MACR;AACA,YAAMA,IAAG;AAAA,QACP;AAAA,QACA,CAAC,KAAK;AAAA,MACR;AAAA,IACF;AAAA,EACF;AAAA,EACA,MAAM,OAAO;AACX,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;;;
|
|
6
|
-
"names": ["db", "db", "db", "db", "db", "db", "db", "url"]
|
|
3
|
+
"sources": ["../../../lib/database/src/index.ts", "../../../lib/database/src/hardening.ts", "../../../lib/database/src/model-migration.ts", "../../../lib/database/src/lifetime-migration.ts", "../../../lib/database/src/background-migration.ts", "../../../lib/database/src/notebook-migration.ts", "../../../lib/database/src/conversation-migration.ts", "../../../lib/database/src/relationship-migration.ts", "../../../lib/database/src/sharing-migration.ts", "../../../lib/database/src/share-expiration-migration.ts", "../../../lib/database/src/migrations.ts", "../src/bootstrap.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 };\nexport type { QueryBuilder } from \"objection\";\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 autoKind!: boolean;\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 retentionDays!: number | 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\";\n\nexport const modelProviders = {\n // 004 belongs to the independently reviewed cloud-onboarding PR.\n name: \"20261019_005_model_providers\",\n async up(db: Knex) {\n await db.raw(`\n CREATE TABLE model_settings (\n singleton boolean PRIMARY KEY DEFAULT true CHECK (singleton),\n version integer NOT NULL DEFAULT 0, encrypted text NOT NULL,\n updated_at timestamptz NOT NULL DEFAULT now()\n );\n GRANT SELECT ON model_settings TO grove_runtime, grove_worker;\n GRANT INSERT, UPDATE ON model_settings TO grove_runtime;\n CREATE TABLE embedding_profiles (\n id text PRIMARY KEY, model text NOT NULL, dimensions integer NOT NULL CHECK (dimensions BETWEEN 32 AND 16000),\n created_at timestamptz NOT NULL DEFAULT now(), UNIQUE(id, dimensions)\n );\n GRANT SELECT, INSERT ON embedding_profiles TO grove_runtime, grove_worker;\n INSERT INTO embedding_profiles(id, model, dimensions)\n SELECT DISTINCT profile, 'legacy', 384 FROM memory_embeddings;\n ALTER TABLE memory_embeddings ALTER COLUMN embedding TYPE vector;\n ALTER TABLE memory_embeddings ADD COLUMN dimensions integer NOT NULL DEFAULT 384;\n ALTER TABLE memory_embeddings ADD CONSTRAINT embedding_dimensions CHECK (vector_dims(embedding) = dimensions);\n ALTER TABLE memory_embeddings ADD CONSTRAINT embedding_profile_fk FOREIGN KEY (profile, dimensions) REFERENCES embedding_profiles(id, dimensions);\n ALTER TABLE memories ADD COLUMN auto_kind boolean NOT NULL DEFAULT false;\n ALTER TABLE accounts ADD COLUMN organize_enabled boolean NOT NULL DEFAULT true;\n ALTER TABLE accounts ADD COLUMN summaries_enabled boolean NOT NULL DEFAULT true;\n\n ALTER TABLE jobs DROP CONSTRAINT jobs_account_id_memory_id_version_key;\n ALTER TABLE jobs ALTER COLUMN memory_id DROP NOT NULL;\n ALTER TABLE jobs ALTER COLUMN version DROP NOT NULL;\n ALTER TABLE jobs ADD COLUMN kind text NOT NULL DEFAULT 'embedding' CHECK (kind IN ('embedding','decision','organization','brief'));\n ALTER TABLE jobs ADD COLUMN profile text NOT NULL DEFAULT 'minilm-l6-v2-mean-normalized-v1';\n ALTER TABLE jobs ADD COLUMN target text;\n UPDATE jobs SET target = memory_id::text;\n ALTER TABLE jobs ALTER COLUMN target SET NOT NULL;\n ALTER TABLE jobs ADD COLUMN scope jsonb;\n 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));\n ALTER TABLE jobs ADD CONSTRAINT job_identity UNIQUE(account_id, kind, target, profile);\n\n CREATE TABLE memory_enrichments (\n account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,\n kind text NOT NULL CHECK (kind IN ('decision','organization')), profile text NOT NULL,\n data jsonb NOT NULL, sources jsonb NOT NULL DEFAULT '[]', created_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id, memory_id, version, kind, profile),\n FOREIGN KEY(account_id, memory_id, version) REFERENCES memory_revisions ON DELETE CASCADE\n );\n CREATE TABLE memory_briefs (\n account_id uuid NOT NULL REFERENCES accounts(id), target text NOT NULL,\n scope jsonb NOT NULL, profile text NOT NULL, content_version integer NOT NULL,\n content jsonb NOT NULL, sources jsonb NOT NULL, truncated boolean NOT NULL DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, target, profile)\n );\n CREATE TABLE inference_usage (\n account_id uuid NOT NULL REFERENCES accounts(id), day date NOT NULL DEFAULT CURRENT_DATE,\n role text NOT NULL, requests integer NOT NULL DEFAULT 0, input_tokens bigint NOT NULL DEFAULT 0,\n output_tokens bigint NOT NULL DEFAULT 0, PRIMARY KEY(account_id, day, role)\n );\n `);\n for (const table of [\n \"memory_enrichments\",\n \"memory_briefs\",\n \"inference_usage\",\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 DROP FUNCTION grove_claim_job();\n CREATE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL) 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 (profiles IS NULL OR j.profile = ANY(profiles))\n 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))))\n 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))))\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_job(text[]) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_job(text[]) TO grove_worker;\n CREATE FUNCTION grove_reprocess(embedding_profile text, decision_profile text, generation_profile text) RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n DELETE FROM jobs;\n DELETE FROM memory_briefs;\n INSERT INTO jobs(account_id, memory_id, version, target, kind, profile)\n SELECT m.account_id, m.id, m.version, m.id::text, p.kind, p.profile\n FROM memories m JOIN accounts a ON a.id = m.account_id\n CROSS JOIN (VALUES ('embedding', embedding_profile), ('decision', decision_profile), ('organization', generation_profile)) AS p(kind, profile)\n WHERE a.status = 'active' AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now())\n AND p.profile IS NOT NULL AND (p.kind = 'embedding' OR a.organize_enabled);\n IF generation_profile IS NOT NULL THEN\n INSERT INTO jobs(account_id, kind, target, profile, scope, due_at)\n SELECT DISTINCT m.account_id, 'brief', COALESCE(m.project_id::text, 'personal'), generation_profile,\n jsonb_build_object('projectId', m.project_id), now() + interval '5 seconds'\n FROM memories m JOIN accounts a ON a.id = m.account_id\n WHERE a.status = 'active' AND a.summaries_enabled AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now());\n INSERT INTO jobs(account_id, kind, target, profile, scope, due_at)\n SELECT m.account_id, 'brief', COALESCE(m.project_id::text, 'personal') || ':task:' || m.task_id, generation_profile,\n jsonb_build_object('projectId', m.project_id, 'taskId', m.task_id), now() + interval '5 seconds'\n FROM memories m JOIN accounts a ON a.id = m.account_id\n WHERE a.status = 'active' AND a.summaries_enabled AND m.status = 'active' AND m.kind = 'handoff' AND m.expires_at > now();\n END IF;\n END $$;\n REVOKE ALL ON FUNCTION grove_reprocess(text,text,text) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_reprocess(text,text,text) TO grove_runtime;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const memoryLifetimes = {\n name: \"20261020_006_memory_lifetimes\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE memories DROP CONSTRAINT memories_check;\n ALTER TABLE memories ADD COLUMN retention_days integer CHECK (retention_days BETWEEN 1 AND 365);\n UPDATE memories SET retention_days = 30 WHERE expires_at IS NOT NULL;\n ALTER TABLE memories ADD CONSTRAINT memory_task_reference CHECK ((kind = 'handoff') = (task_id IS NOT NULL));\n ALTER TABLE memories ADD CONSTRAINT memory_lifetime CHECK (\n (retention_days IS NULL AND expires_at IS NULL AND purge_at IS NULL) OR\n (retention_days IS NOT NULL AND expires_at IS NOT NULL AND purge_at IS NOT NULL AND purge_at > expires_at)\n );\n CREATE INDEX memories_updated_page ON memories(account_id, updated_at DESC, id DESC);\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const backgroundServices = {\n name: \"20261020_007_background_services\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE accounts ADD COLUMN organization_due_at timestamptz NOT NULL DEFAULT now();\n ALTER TABLE accounts ADD COLUMN organization_checked_at timestamptz;\n ALTER TABLE jobs ADD COLUMN dispatched_at timestamptz;\n CREATE TABLE transactional_emails (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL REFERENCES accounts(id),\n event_key text NOT NULL, kind text NOT NULL CHECK (kind IN ('welcome','connection_approved','connection_revoked')),\n created_at timestamptz NOT NULL DEFAULT now(), due_at timestamptz NOT NULL DEFAULT now(),\n attempts integer NOT NULL DEFAULT 0, lease_id uuid, lease_until timestamptz,\n dispatched_at timestamptz, sent_at timestamptz, provider_id text, failed_at timestamptz, error_code text,\n UNIQUE(account_id, event_key)\n );\n ALTER TABLE transactional_emails ENABLE ROW LEVEL SECURITY;\n CREATE POLICY tenant ON transactional_emails USING (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid)\n WITH CHECK (account_id = NULLIF(current_setting('grove.account_id', true), '')::uuid);\n GRANT SELECT, INSERT, UPDATE, DELETE ON transactional_emails TO grove_worker;\n CREATE INDEX transactional_emails_due ON transactional_emails(due_at) WHERE sent_at IS NULL AND failed_at IS NULL;\n\n CREATE FUNCTION grove_queue_transactional_email() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n DECLARE event_kind text; owner_id uuid; event_identity text;\n BEGIN\n IF TG_TABLE_NAME = 'accounts' THEN\n owner_id := NEW.id; event_kind := 'welcome'; event_identity := 'welcome';\n ELSE\n owner_id := NEW.account_id;\n IF NOT EXISTS (SELECT 1 FROM accounts WHERE id = owner_id AND status = 'active') THEN RETURN NEW; END IF;\n IF TG_OP = 'INSERT' THEN\n IF cardinality(NEW.capabilities) = 0 OR NEW.revoked_at IS NOT NULL THEN RETURN NEW; END IF;\n event_kind := 'connection_approved';\n ELSIF OLD.revoked_at IS NULL AND NEW.revoked_at IS NOT NULL THEN\n IF cardinality(OLD.capabilities) = 0 THEN RETURN NEW; END IF;\n event_kind := 'connection_revoked';\n ELSIF cardinality(NEW.capabilities) > 0 AND NEW.revoked_at IS NULL AND (cardinality(OLD.capabilities) = 0 OR OLD.revoked_at IS NOT NULL) THEN\n event_kind := 'connection_approved';\n ELSE RETURN NEW;\n END IF;\n event_identity := event_kind || ':' || NEW.id::text || ':' || txid_current()::text;\n END IF;\n INSERT INTO transactional_emails(account_id, event_key, kind) VALUES(owner_id, event_identity, event_kind)\n ON CONFLICT(account_id, event_key) DO NOTHING;\n RETURN NEW;\n END $$;\n REVOKE ALL ON FUNCTION grove_queue_transactional_email() FROM PUBLIC;\n CREATE TRIGGER account_welcome AFTER INSERT ON accounts FOR EACH ROW EXECUTE FUNCTION grove_queue_transactional_email();\n CREATE TRIGGER connection_notification AFTER INSERT OR UPDATE ON connections FOR EACH ROW EXECUTE FUNCTION grove_queue_transactional_email();\n\n DROP FUNCTION grove_claim_job(text[]);\n CREATE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL, wanted uuid DEFAULT NULL) 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 (wanted IS NULL OR j.id = wanted) AND (profiles IS NULL OR j.profile = ANY(profiles))\n 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))))\n 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))))\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_job(text[],uuid) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_job(text[],uuid) TO grove_worker;\n\n CREATE FUNCTION grove_claim_email(wanted uuid DEFAULT NULL) RETURNS SETOF transactional_emails\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n UPDATE transactional_emails SET failed_at = now(), error_code = 'delivery_exhausted'\n WHERE sent_at IS NULL AND failed_at IS NULL AND (attempts >= 5 OR created_at < now() - interval '23 hours')\n AND (lease_until IS NULL OR lease_until < now());\n RETURN QUERY UPDATE transactional_emails SET lease_id = gen_random_uuid(), lease_until = now() + interval '120 seconds', attempts = attempts + 1\n WHERE id = (SELECT e.id FROM transactional_emails e JOIN accounts a ON a.id = e.account_id\n WHERE a.status = 'active' AND e.sent_at IS NULL AND e.failed_at IS NULL AND e.due_at <= now()\n AND (wanted IS NULL OR e.id = wanted) AND (e.lease_until IS NULL OR e.lease_until < now())\n ORDER BY e.due_at, e.id FOR UPDATE OF e SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_email(uuid) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_email(uuid) TO grove_worker;\n\n CREATE FUNCTION grove_due_dispatch(profiles text[], mail_enabled boolean) RETURNS TABLE(id uuid, account_id uuid, queue_kind text)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n SELECT due.id, due.account_id, due.queue_kind FROM (\n 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\n WHERE a.status = 'active' AND j.profile = ANY(profiles) AND j.failed_at IS NULL AND j.attempts < 5\n AND j.due_at <= now() AND (j.lease_until IS NULL OR j.lease_until < now())\n AND (j.dispatched_at IS NULL OR j.dispatched_at < now() - interval '60 seconds')\n UNION ALL\n 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\n WHERE mail_enabled AND a.status = 'active' AND e.sent_at IS NULL AND e.failed_at IS NULL AND e.attempts < 5\n AND e.created_at > now() - interval '23 hours' AND e.due_at <= now() AND (e.lease_until IS NULL OR e.lease_until < now())\n AND (e.dispatched_at IS NULL OR e.dispatched_at < now() - interval '60 seconds')\n ) due ORDER BY due.due_at, due.id LIMIT 100;\n $$;\n REVOKE ALL ON FUNCTION grove_due_dispatch(text[],boolean) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_due_dispatch(text[],boolean) TO grove_worker;\n\n CREATE FUNCTION grove_organization_accounts(interval_seconds integer) RETURNS TABLE(id uuid)\n LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n UPDATE accounts SET organization_due_at = now() + (greatest(60, least(interval_seconds, 86400)) * interval '1 second'), organization_checked_at = now()\n WHERE accounts.id IN (SELECT a.id FROM accounts a WHERE a.status = 'active' AND a.organization_due_at <= now()\n ORDER BY a.organization_due_at, a.id FOR UPDATE SKIP LOCKED LIMIT 20) RETURNING accounts.id;\n $$;\n REVOKE ALL ON FUNCTION grove_organization_accounts(integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_organization_accounts(integer) TO grove_worker;\n\n CREATE FUNCTION grove_sweep_deliveries() RETURNS void\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 UPDATE transactional_emails SET failed_at = now(), error_code = 'delivery_exhausted'\n WHERE sent_at IS NULL AND failed_at IS NULL AND (attempts >= 5 OR created_at < now() - interval '23 hours')\n AND (lease_until IS NULL OR lease_until < now());\n END $$;\n REVOKE ALL ON FUNCTION grove_sweep_deliveries() FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_sweep_deliveries() TO grove_worker;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const nestedNotebooks = {\n name: \"20261020_008_nested_notebooks\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE projects\n ADD COLUMN parent_id uuid,\n ADD COLUMN version integer NOT NULL DEFAULT 1 CHECK (version > 0),\n ADD CONSTRAINT projects_parent_owner FOREIGN KEY (account_id, parent_id)\n REFERENCES projects(account_id, id) ON DELETE SET NULL (parent_id),\n ADD CONSTRAINT projects_not_own_parent CHECK (parent_id IS DISTINCT FROM id);\n CREATE INDEX projects_parent ON projects(account_id, parent_id);\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const conversations = {\n name: \"20261020_009_conversations\",\n async up(db: Knex) {\n await db.raw(`\n CREATE TABLE conversations (\n id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES accounts(id),\n title text NOT NULL DEFAULT 'New conversation', scope jsonb NOT NULL,\n version integer NOT NULL DEFAULT 0 CHECK (version >= 0),\n created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, id)\n );\n CREATE INDEX conversations_recent ON conversations(account_id, updated_at DESC, id DESC);\n CREATE TABLE deleted_conversations (\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 conversation_turns (\n id uuid PRIMARY KEY, account_id uuid NOT NULL, conversation_id uuid NOT NULL,\n position integer NOT NULL CHECK (position > 0), question text NOT NULL,\n format text NOT NULL DEFAULT 'plain' CHECK (format IN ('plain','markdown')),\n fingerprint text NOT NULL, status text NOT NULL CHECK (status IN ('pending','ready','failed')),\n result jsonb, undo jsonb, error text, lease_id uuid, lease_until timestamptz,\n created_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, conversation_id, position),\n FOREIGN KEY(account_id, conversation_id) REFERENCES conversations(account_id, id) ON DELETE CASCADE\n );\n `);\n for (const table of [\n \"conversations\",\n \"conversation_turns\",\n \"deleted_conversations\",\n ]) {\n await db.raw(\"ALTER TABLE ?? ENABLE ROW LEVEL SECURITY\", [table]);\n await db.raw(\"ALTER TABLE ?? FORCE 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 },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const relationships = {\n name: \"20261021_010_relationship_evidence\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE projects ADD COLUMN content_version integer NOT NULL DEFAULT 0;\n ALTER TABLE memory_enrichments DROP CONSTRAINT memory_enrichments_kind_check;\n ALTER TABLE memory_enrichments ADD CONSTRAINT memory_enrichments_kind_check CHECK (kind IN ('decision','organization','relationship_scan'));\n CREATE TABLE notebook_profiles (\n account_id uuid NOT NULL, project_id uuid NOT NULL, profile text NOT NULL,\n content_version integer NOT NULL, expires_at timestamptz,\n total integer NOT NULL DEFAULT 0, processed integer NOT NULL DEFAULT 0,\n after_id uuid, complete boolean NOT NULL DEFAULT false, data jsonb NOT NULL DEFAULT '{}',\n updated_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id, project_id, profile),\n FOREIGN KEY(account_id, project_id) REFERENCES projects(account_id, id) ON DELETE CASCADE\n );\n `);\n for (const [table, endpoint] of [\n [\"memory_relationships\", \"memories\"],\n [\"notebook_relationships\", \"projects\"],\n ]) {\n await db.raw(`\n CREATE TABLE ${table} (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid NOT NULL,\n left_id uuid NOT NULL, right_id uuid NOT NULL, profile text NOT NULL,\n left_version integer NOT NULL, right_version integer NOT NULL,\n revision text NOT NULL, assessment jsonb NOT NULL,\n expires_at timestamptz, updated_at timestamptz NOT NULL DEFAULT now(),\n dismissed_revision text, review_version integer NOT NULL DEFAULT 0,\n CHECK (left_id < right_id), UNIQUE(account_id, left_id, right_id),\n FOREIGN KEY(account_id, left_id) REFERENCES ${endpoint}(account_id, id) ON DELETE CASCADE,\n FOREIGN KEY(account_id, right_id) REFERENCES ${endpoint}(account_id, id) ON DELETE CASCADE\n );\n CREATE INDEX ${table}_right ON ${table}(account_id, right_id);\n `);\n }\n for (const table of [\n \"notebook_profiles\",\n \"memory_relationships\",\n \"notebook_relationships\",\n ]) {\n await db.raw(`ALTER TABLE ?? ENABLE ROW LEVEL SECURITY`, [table]);\n await db.raw(`ALTER TABLE ?? FORCE 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 CREATE FUNCTION grove_notebook_content_changed() RETURNS trigger\n LANGUAGE plpgsql SET search_path = pg_catalog, public AS $$\n BEGIN\n IF TG_OP = 'DELETE' THEN\n DELETE FROM notebook_profiles WHERE account_id=OLD.account_id AND project_id=OLD.project_id;\n UPDATE notebook_relationships SET assessment=jsonb_build_object('relationship','unrelated','reason','','basis','none','direction','both','evidence','[]'::jsonb,'coverage',assessment->'coverage','breadth','thread'), profile='rebuild-after-deletion'\n WHERE account_id=OLD.account_id AND (left_id=OLD.project_id OR right_id=OLD.project_id\n OR EXISTS (SELECT 1 FROM jsonb_array_elements(assessment->'evidence') e WHERE e->>'id'=OLD.id::text));\n UPDATE projects SET content_version = content_version + 1 WHERE account_id = OLD.account_id AND id = OLD.project_id;\n UPDATE accounts SET organization_due_at = now() WHERE id = OLD.account_id;\n ELSE\n IF TG_OP = 'UPDATE' AND OLD.project_id IS DISTINCT FROM NEW.project_id THEN\n DELETE FROM notebook_profiles WHERE account_id=OLD.account_id AND project_id=OLD.project_id;\n UPDATE projects SET content_version = content_version + 1 WHERE account_id = OLD.account_id AND id = OLD.project_id;\n END IF;\n DELETE FROM notebook_profiles WHERE account_id=NEW.account_id AND project_id=NEW.project_id;\n UPDATE projects SET content_version = content_version + 1 WHERE account_id = NEW.account_id AND id = NEW.project_id;\n UPDATE accounts SET organization_due_at = now() WHERE id = NEW.account_id;\n END IF;\n RETURN NULL;\n END $$;\n CREATE TRIGGER notebook_content_changed AFTER INSERT OR DELETE OR UPDATE OF content, version, project_id, status, expires_at ON memories\n FOR EACH ROW EXECUTE FUNCTION grove_notebook_content_changed();\n ALTER TABLE jobs DROP CONSTRAINT jobs_kind_check;\n ALTER TABLE jobs ADD CONSTRAINT jobs_kind_check CHECK (kind IN ('embedding','decision','organization','brief','relationship_scan','note_relationship','notebook_profile','notebook_relationship'));\n ALTER TABLE jobs DROP CONSTRAINT job_target;\n ALTER TABLE jobs ADD CONSTRAINT job_target CHECK (\n (kind IN ('brief','note_relationship','notebook_profile','notebook_relationship') AND memory_id IS NULL AND version IS NULL AND scope IS NOT NULL)\n OR (kind IN ('embedding','decision','organization','relationship_scan') AND memory_id IS NOT NULL AND version IS NOT NULL)\n );\n CREATE OR REPLACE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL, wanted uuid DEFAULT NULL) 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 (wanted IS NULL OR j.id = wanted) AND (profiles IS NULL OR j.profile = ANY(profiles))\n AND (j.kind NOT IN ('decision','relationship_scan') 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))))\n AND (j.kind <> 'notebook_profile' OR NOT EXISTS (SELECT 1 FROM jobs e JOIN memories m ON m.account_id=e.account_id AND m.id=e.memory_id WHERE e.account_id=j.account_id AND m.project_id::text=j.target AND e.kind='embedding' AND e.failed_at IS NULL AND (profiles IS NULL OR e.profile=ANY(profiles))))\n AND (j.kind <> 'brief' OR NOT EXISTS (SELECT 1 FROM jobs e WHERE e.account_id = j.account_id AND e.kind IN ('embedding','decision','organization') AND e.failed_at IS NULL AND (profiles IS NULL OR e.profile = ANY(profiles))))\n AND (j.lease_until IS NULL OR j.lease_until < now()) ORDER BY j.due_at, j.id\n FOR UPDATE OF j SKIP LOCKED LIMIT 1) RETURNING *;\n END $$;\n CREATE OR REPLACE FUNCTION grove_reprocess(embedding_profile text, decision_profile text, generation_profile text) RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public AS $$\n BEGIN\n DELETE FROM jobs;\n DELETE FROM memory_briefs;\n DELETE FROM notebook_profiles;\n DELETE FROM memory_enrichments WHERE kind='relationship_scan';\n UPDATE accounts SET organization_due_at=now();\n INSERT INTO jobs(account_id, memory_id, version, target, kind, profile)\n SELECT m.account_id, m.id, m.version, m.id::text, p.kind, p.profile\n FROM memories m JOIN accounts a ON a.id=m.account_id\n CROSS JOIN (VALUES ('embedding',embedding_profile),('decision',decision_profile),('organization',generation_profile)) AS p(kind,profile)\n WHERE a.status='active' AND m.status='active' AND (m.expires_at IS NULL OR m.expires_at>now())\n AND p.profile IS NOT NULL AND (p.kind='embedding' OR a.organize_enabled);\n IF generation_profile IS NOT NULL THEN\n INSERT INTO jobs(account_id,kind,target,profile,scope,due_at)\n SELECT DISTINCT m.account_id,'brief',COALESCE(m.project_id::text,'personal'),generation_profile,jsonb_build_object('projectId',m.project_id),now()+interval '5 seconds'\n FROM memories m JOIN accounts a ON a.id=m.account_id\n WHERE a.status='active' AND a.summaries_enabled AND m.status='active' AND (m.expires_at IS NULL OR m.expires_at>now());\n INSERT INTO jobs(account_id,kind,target,profile,scope,due_at)\n SELECT m.account_id,'brief',COALESCE(m.project_id::text,'personal')||':task:'||m.task_id,generation_profile,jsonb_build_object('projectId',m.project_id,'taskId',m.task_id),now()+interval '5 seconds'\n FROM memories m JOIN accounts a ON a.id=m.account_id\n WHERE a.status='active' AND a.summaries_enabled AND m.status='active' AND m.kind='handoff' AND m.expires_at>now();\n END IF;\n END $$;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const publicSharing = {\n name: \"20261021_011_public_sharing\",\n async up(db: Knex) {\n await db.raw(`\n CREATE TABLE public_shares (\n id uuid PRIMARY KEY, account_id uuid NOT NULL REFERENCES accounts(id),\n memory_id uuid, project_id uuid, include_descendants boolean NOT NULL DEFAULT false,\n token_digest text UNIQUE CHECK (token_digest ~ '^[0-9a-f]{64}$'),\n token_ciphertext text, version integer NOT NULL DEFAULT 1 CHECK (version > 0),\n revoked_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE(account_id, id), UNIQUE(account_id, memory_id), UNIQUE(account_id, project_id),\n FOREIGN KEY(account_id, memory_id) REFERENCES memories(account_id, id) ON DELETE CASCADE,\n FOREIGN KEY(account_id, project_id) REFERENCES projects(account_id, id) ON DELETE CASCADE,\n CHECK (num_nonnulls(memory_id, project_id) = 1),\n CHECK (memory_id IS NULL OR NOT include_descendants),\n CHECK ((revoked_at IS NULL AND token_digest IS NOT NULL AND token_ciphertext IS NOT NULL)\n OR (revoked_at IS NOT NULL AND token_digest IS NULL AND token_ciphertext IS NULL))\n );\n CREATE TABLE public_share_operations (\n account_id uuid NOT NULL, id uuid NOT NULL, fingerprint text NOT NULL,\n share_id uuid NOT NULL, version integer NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(), PRIMARY KEY(account_id, id),\n FOREIGN KEY(account_id, share_id) REFERENCES public_shares(account_id, id) ON DELETE CASCADE\n );\n CREATE TABLE public_share_rates (\n bucket text NOT NULL, minute timestamptz NOT NULL, count integer NOT NULL,\n PRIMARY KEY(bucket, minute)\n );\n CREATE INDEX public_share_rates_expiry ON public_share_rates(minute);\n REVOKE ALL ON public_share_rates FROM PUBLIC;\n CREATE FUNCTION grove_share_cleanup() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n BEGIN\n DELETE FROM public_share_rates WHERE bucket = OLD.id::text;\n RETURN OLD;\n END $$;\n REVOKE ALL ON FUNCTION grove_share_cleanup() FROM PUBLIC;\n CREATE TRIGGER public_share_cleanup AFTER DELETE ON public_shares\n FOR EACH ROW EXECUTE FUNCTION grove_share_cleanup();\n CREATE FUNCTION grove_share_admit(bucket_name text) RETURNS boolean\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n DECLARE hits integer;\n BEGIN\n IF bucket_name <> 'global' AND bucket_name !~ '^[0-9a-f-]{36}$' THEN RETURN false; END IF;\n DELETE FROM public_share_rates WHERE minute < date_trunc('minute', now()) - interval '1 minute';\n INSERT INTO public_share_rates(bucket, minute, count)\n VALUES(bucket_name, date_trunc('minute', now()), 1)\n ON CONFLICT(bucket, minute) DO UPDATE SET count = LEAST(public_share_rates.count + 1, 1201)\n RETURNING count INTO hits;\n RETURN hits <= CASE WHEN bucket_name = 'global' THEN 1200 ELSE 240 END;\n END $$;\n REVOKE ALL ON FUNCTION grove_share_admit(text) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_share_admit(text) TO grove_runtime;\n `);\n for (const table of [\"public_shares\", \"public_share_operations\"]) {\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)\n 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\",\n [table],\n );\n await db.raw(\"GRANT SELECT, DELETE ON ?? TO grove_worker\", [table]);\n }\n // Like grove_key, this narrow capability entrypoint is owned by the migration\n // role. It projects content itself; it never returns an owner identity/grant.\n await db.raw(`\n CREATE FUNCTION grove_public_share(\n secret_digest text, requested_kind text, requested_id uuid,\n after_id uuid, cursor_share uuid, cursor_version integer, page_size integer\n ) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n DECLARE link public_shares; owner_id uuid; permitted uuid[]; selected uuid;\n root_name text; notebook_name text; note memories; result jsonb; page jsonb; children jsonb;\n BEGIN\n IF page_size IS NULL OR page_size < 1 OR page_size > 100\n OR requested_kind IS NULL OR requested_kind NOT IN ('root', 'note', 'notebook') THEN RETURN NULL; END IF;\n SELECT account_id INTO owner_id FROM public_shares WHERE token_digest = secret_digest AND revoked_at IS NULL;\n IF owner_id IS NULL THEN RETURN NULL; END IF;\n -- Match the service's lock order. Revocation, moves and deletion all take\n -- the account write lock, so a completed revocation precedes later reads.\n PERFORM 1 FROM accounts WHERE id = owner_id AND status = 'active' FOR SHARE;\n IF NOT FOUND THEN RETURN NULL; END IF;\n SELECT * INTO link FROM public_shares WHERE account_id = owner_id\n AND token_digest = secret_digest AND revoked_at IS NULL FOR SHARE;\n IF NOT FOUND THEN RETURN NULL; END IF;\n IF NOT grove_share_admit(link.id::text) THEN RETURN jsonb_build_object('limited', true); END IF;\n IF cursor_share IS NOT NULL AND (cursor_share <> link.id OR cursor_version IS DISTINCT FROM link.version)\n THEN RETURN jsonb_build_object('stale', true); END IF;\n IF link.project_id IS NOT NULL THEN\n WITH RECURSIVE scope(id) AS (\n SELECT id FROM projects WHERE account_id = owner_id AND id = link.project_id\n UNION\n SELECT p.id FROM projects p JOIN scope s ON p.parent_id = s.id\n WHERE p.account_id = owner_id AND link.include_descendants\n ) SELECT array_agg(id) INTO permitted FROM scope;\n SELECT name INTO root_name FROM projects WHERE account_id = owner_id AND id = link.project_id;\n IF root_name IS NULL THEN RETURN NULL; END IF;\n ELSE\n SELECT * INTO note FROM memories WHERE account_id = owner_id AND id = link.memory_id\n AND status = 'active' AND (expires_at IS NULL OR expires_at > now());\n IF NOT FOUND THEN RETURN NULL; END IF;\n root_name := left(regexp_replace(split_part(trim(note.content), E'\\\\n', 1), '^#{1,6}\\\\s+', ''), 110);\n END IF;\n result := jsonb_build_object('shareId', link.id, 'shareVersion', link.version,\n 'kind', CASE WHEN link.memory_id IS NULL THEN 'notebook' ELSE 'note' END,\n 'root', jsonb_build_object('id', coalesce(link.project_id, link.memory_id), 'name', root_name),\n 'notebook', NULL, 'note', NULL, 'notebooks', '[]'::jsonb, 'notes', '[]'::jsonb);\n IF requested_kind = 'note' OR (requested_kind = 'root' AND link.memory_id IS NOT NULL) THEN\n selected := CASE WHEN requested_kind = 'root' THEN link.memory_id ELSE requested_id END;\n SELECT * INTO note FROM memories WHERE account_id = owner_id AND id = selected\n AND (id = link.memory_id OR project_id = ANY(permitted))\n AND status = 'active' AND (expires_at IS NULL OR expires_at > now());\n IF NOT FOUND THEN RETURN NULL; END IF;\n SELECT coalesce(jsonb_agg(m.id), '[]'::jsonb) INTO page FROM memories m\n WHERE m.account_id = owner_id AND (m.id = link.memory_id OR m.project_id = ANY(permitted))\n AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now())\n AND m.id IN (SELECT matches[1]::uuid FROM regexp_matches(note.content,\n '/app/memories/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})', 'g') AS matches);\n RETURN result || jsonb_build_object('note', jsonb_build_object('id', note.id,\n 'title', left(regexp_replace(split_part(trim(note.content), E'\\\\n', 1), '^#{1,6}\\\\s+', ''), 110),\n 'content', note.content, 'updatedAt', note.updated_at, 'linkedNoteIds', page));\n END IF;\n selected := CASE WHEN requested_kind = 'root' THEN link.project_id ELSE requested_id END;\n IF selected IS NULL OR NOT (selected = ANY(permitted)) OR permitted IS NULL THEN RETURN NULL; END IF;\n SELECT name INTO notebook_name FROM projects WHERE account_id = owner_id AND id = selected;\n SELECT coalesce(jsonb_agg(jsonb_build_object('id', p.id, 'name', p.name) ORDER BY p.name, p.id), '[]'::jsonb)\n INTO children FROM projects p WHERE p.account_id = owner_id AND p.parent_id = selected AND p.id = ANY(permitted);\n SELECT coalesce(jsonb_agg(jsonb_build_object('id', m.id,\n 'title', left(regexp_replace(split_part(trim(m.content), E'\\\\n', 1), '^#{1,6}\\\\s+', ''), 110),\n 'updatedAt', m.updated_at) ORDER BY m.id), '[]'::jsonb) INTO page FROM (\n SELECT id, content, updated_at FROM memories WHERE account_id = owner_id AND project_id = selected\n AND status = 'active' AND (expires_at IS NULL OR expires_at > now())\n AND (after_id IS NULL OR id > after_id) ORDER BY id LIMIT page_size + 1\n ) m;\n RETURN result || jsonb_build_object('notebook', jsonb_build_object('id', selected, 'name', notebook_name),\n 'notebooks', children, 'notes', page);\n END $$;\n REVOKE ALL ON FUNCTION grove_public_share(text,text,uuid,uuid,uuid,integer,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_public_share(text,text,uuid,uuid,uuid,integer,integer) TO grove_runtime;\n `);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const shareExpiration = {\n name: \"20261022_012_share_expiration\",\n async up(db: Knex) {\n // Existing links retain their capability and unlimited lifetime. Do not edit 011.\n await db.raw(`\n ALTER TABLE public_shares\n ADD COLUMN duration text CHECK (duration IN ('1h','4h','1d','1w','2w','1mo')),\n ADD COLUMN expires_at timestamptz,\n ADD CONSTRAINT public_shares_expiration CHECK ((duration IS NULL) = (expires_at IS NULL));\n\n CREATE OR REPLACE FUNCTION grove_public_share(\n secret_digest text, requested_kind text, requested_id uuid,\n after_id uuid, cursor_share uuid, cursor_version integer, page_size integer\n ) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n DECLARE link public_shares; owner_id uuid; permitted uuid[]; selected uuid;\n root_name text; notebook_name text; note memories; result jsonb; page jsonb; children jsonb;\n BEGIN\n IF page_size IS NULL OR page_size < 1 OR page_size > 100\n OR requested_kind IS NULL OR requested_kind NOT IN ('root', 'note', 'notebook') THEN RETURN NULL; END IF;\n SELECT account_id INTO owner_id FROM public_shares WHERE token_digest = secret_digest AND revoked_at IS NULL;\n IF owner_id IS NULL THEN RETURN NULL; END IF;\n -- Keep account-first locking. Wall-clock expiry must be checked AFTER a\n -- blocked reader acquires its locks, not against transaction-start now().\n PERFORM 1 FROM accounts WHERE id = owner_id AND status = 'active' FOR SHARE;\n IF NOT FOUND THEN RETURN NULL; END IF;\n SELECT * INTO link FROM public_shares WHERE account_id = owner_id\n AND token_digest = secret_digest AND revoked_at IS NULL FOR SHARE;\n IF NOT FOUND THEN RETURN NULL; END IF;\n IF link.expires_at IS NOT NULL AND link.expires_at <= clock_timestamp() THEN RETURN NULL; END IF;\n IF NOT grove_share_admit(link.id::text) THEN RETURN jsonb_build_object('limited', true); END IF;\n IF cursor_share IS NOT NULL AND (cursor_share <> link.id OR cursor_version IS DISTINCT FROM link.version)\n THEN RETURN jsonb_build_object('stale', true); END IF;\n IF link.project_id IS NOT NULL THEN\n WITH RECURSIVE scope(id) AS (\n SELECT id FROM projects WHERE account_id = owner_id AND id = link.project_id\n UNION\n SELECT p.id FROM projects p JOIN scope s ON p.parent_id = s.id\n WHERE p.account_id = owner_id AND link.include_descendants\n ) SELECT array_agg(id) INTO permitted FROM scope;\n SELECT name INTO root_name FROM projects WHERE account_id = owner_id AND id = link.project_id;\n IF root_name IS NULL THEN RETURN NULL; END IF;\n ELSE\n SELECT * INTO note FROM memories WHERE account_id = owner_id AND id = link.memory_id\n AND status = 'active' AND (expires_at IS NULL OR expires_at > now());\n IF NOT FOUND THEN RETURN NULL; END IF;\n root_name := left(regexp_replace(split_part(trim(note.content), E'\\\\n', 1), '^#{1,6}\\\\s+', ''), 110);\n END IF;\n result := jsonb_build_object('shareId', link.id, 'shareVersion', link.version,\n 'kind', CASE WHEN link.memory_id IS NULL THEN 'notebook' ELSE 'note' END,\n 'root', jsonb_build_object('id', coalesce(link.project_id, link.memory_id), 'name', root_name),\n 'notebook', NULL, 'note', NULL, 'notebooks', '[]'::jsonb, 'notes', '[]'::jsonb);\n IF requested_kind = 'note' OR (requested_kind = 'root' AND link.memory_id IS NOT NULL) THEN\n selected := CASE WHEN requested_kind = 'root' THEN link.memory_id ELSE requested_id END;\n SELECT * INTO note FROM memories WHERE account_id = owner_id AND id = selected\n AND (id = link.memory_id OR project_id = ANY(permitted))\n AND status = 'active' AND (expires_at IS NULL OR expires_at > now());\n IF NOT FOUND THEN RETURN NULL; END IF;\n SELECT coalesce(jsonb_agg(m.id), '[]'::jsonb) INTO page FROM memories m\n WHERE m.account_id = owner_id AND (m.id = link.memory_id OR m.project_id = ANY(permitted))\n AND m.status = 'active' AND (m.expires_at IS NULL OR m.expires_at > now())\n AND m.id IN (SELECT matches[1]::uuid FROM regexp_matches(note.content,\n '/app/memories/([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})', 'g') AS matches);\n RETURN result || jsonb_build_object('note', jsonb_build_object('id', note.id,\n 'title', left(regexp_replace(split_part(trim(note.content), E'\\\\n', 1), '^#{1,6}\\\\s+', ''), 110),\n 'content', note.content, 'updatedAt', note.updated_at, 'linkedNoteIds', page));\n END IF;\n selected := CASE WHEN requested_kind = 'root' THEN link.project_id ELSE requested_id END;\n IF selected IS NULL OR NOT (selected = ANY(permitted)) OR permitted IS NULL THEN RETURN NULL; END IF;\n SELECT name INTO notebook_name FROM projects WHERE account_id = owner_id AND id = selected;\n SELECT coalesce(jsonb_agg(jsonb_build_object('id', p.id, 'name', p.name) ORDER BY p.name, p.id), '[]'::jsonb)\n INTO children FROM projects p WHERE p.account_id = owner_id AND p.parent_id = selected AND p.id = ANY(permitted);\n SELECT coalesce(jsonb_agg(jsonb_build_object('id', m.id,\n 'title', left(regexp_replace(split_part(trim(m.content), E'\\\\n', 1), '^#{1,6}\\\\s+', ''), 110),\n 'updatedAt', m.updated_at) ORDER BY m.id), '[]'::jsonb) INTO page FROM (\n SELECT id, content, updated_at FROM memories WHERE account_id = owner_id AND project_id = selected\n AND status = 'active' AND (expires_at IS NULL OR expires_at > now())\n AND (after_id IS NULL OR id > after_id) ORDER BY id LIMIT page_size + 1\n ) m;\n RETURN result || jsonb_build_object('notebook', jsonb_build_object('id', selected, 'name', notebook_name),\n 'notebooks', children, 'notes', page);\n END $$;\n REVOKE ALL ON FUNCTION grove_public_share(text,text,uuid,uuid,uuid,integer,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_public_share(text,text,uuid,uuid,uuid,integer,integer) 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\";\nimport { modelProviders } from \"./model-migration.ts\";\nimport { memoryLifetimes } from \"./lifetime-migration.ts\";\nimport { backgroundServices } from \"./background-migration.ts\";\nimport { nestedNotebooks } from \"./notebook-migration.ts\";\nimport { conversations } from \"./conversation-migration.ts\";\nimport { relationships } from \"./relationship-migration.ts\";\nimport { publicSharing } from \"./sharing-migration.ts\";\nimport { shareExpiration } from \"./share-expiration-migration.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 name: \"20261019_004_connection_setup\",\n async up(db: Knex) {\n // One bounded, replaceable attempt per existing RLS-protected connection.\n await db.raw(\"ALTER TABLE connections ADD COLUMN setup jsonb\");\n await db.raw(\n \"CREATE INDEX connections_setup_id ON connections ((setup->>'id')) WHERE setup IS NOT NULL\",\n );\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n },\n modelProviders,\n memoryLifetimes,\n backgroundServices,\n nestedNotebooks,\n conversations,\n relationships,\n publicSharing,\n shareExpiration,\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 } from \"@lib/database\";\n\nconst url = process.env.MIGRATION_DATABASE_URL;\nif (!url) throw new Error(\"MIGRATION_DATABASE_URL is required\");\nconst db = createDatabase(url, { ssl: process.env.DATABASE_SSL === \"require\" });\ntry {\n await db.migrate.latest();\n for (const [name, role, password] of [\n [\"grove_api\", \"grove_runtime\", process.env.API_DATABASE_PASSWORD],\n [\"grove_jobs\", \"grove_worker\", process.env.WORKER_DATABASE_PASSWORD],\n ] as const) {\n if (!password || password.length < 16)\n throw new Error(\n \"Runtime database passwords must have at least 16 characters\",\n );\n const existing = await db.raw(\n \"SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = ?\",\n [name],\n );\n if (!existing.rows.length) {\n const result = await db.raw(\n \"SELECT format('CREATE ROLE %I LOGIN PASSWORD %L NOSUPERUSER NOBYPASSRLS', ?::text, ?::text) AS statement\",\n [name, password],\n );\n await db.raw(result.rows[0].statement);\n } else if (existing.rows[0].rolsuper || existing.rows[0].rolbypassrls)\n throw new Error(\"Runtime role has unsafe privileges\");\n await db.raw(\"GRANT ?? TO ??\", [role!, name!]);\n }\n console.log(JSON.stringify({ status: \"schema-and-roles-ready\" }));\n} finally {\n await db.destroy();\n}\n"],
|
|
5
|
+
"mappings": ";;;AAAA,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