@miniaxolotl/grove-server 1.10.0 → 1.11.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.
@@ -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/relationship-migration.ts", "../../../lib/database/src/sharing-migration.ts", "../../../lib/database/src/share-expiration-migration.ts", "../../../lib/database/src/migrations.ts", "../src/migrate.ts"],
4
- "sourcesContent": ["import knex from \"knex\";\nimport { Model, knexSnakeCaseMappers } from \"objection\";\nimport type { Knex } from \"knex\";\nimport { migrationSource } from \"./migrations.ts\";\n\nexport { migrationSource };\nexport type { Knex };\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, closeDatabase } from \"@lib/database\";\n\nconst url = process.env.MIGRATION_DATABASE_URL;\nif (!url)\n throw new Error(\n \"MIGRATION_DATABASE_URL is required; runtime credentials cannot run migrations\",\n );\nconst db = createDatabase(url, { ssl: process.env.DATABASE_SSL === \"require\" });\ntry {\n const [, applied] = await db.migrate.latest();\n console.log(JSON.stringify({ applied }));\n} finally {\n await closeDatabase(db);\n}\n"],
5
- "mappings": ";;;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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAoBZ;AAAA,EACH;AAAA,EACA,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Y;AAAA,EAC3B,kBAAkB,CAAC,cAAc,UAAU;AAAA,EAC3C,cAAc,OAAO,cAAc;AACrC;;;AVlOO,SAAS,eACdC,MACA,UAA2C,CAAC,GAC5C;AACA,SAAO,KAAK;AAAA,IACV,QAAQ;AAAA,IACR,YAAY;AAAA,MACV,kBAAkBA;AAAA,MAClB,KAAK,QAAQ,MAAM,EAAE,oBAAoB,KAAK,IAAI;AAAA,MAClD,yBAAyB;AAAA,MACzB,kBAAkB;AAAA,IACpB;AAAA,IACA,MAAM,EAAE,KAAK,GAAG,KAAK,QAAQ,OAAO,EAAE;AAAA,IACtC,0BAA0B;AAAA,IAC1B,GAAG,qBAAqB;AAAA,IACxB,YAAY,EAAE,gBAAgB;AAAA,EAChC,CAAC;AACH;AAEO,IAAM,gBAAgB,CAACC,QAAaA,IAAG,QAAQ;;;AW1BtD,IAAM,MAAM,QAAQ,IAAI;AACxB,IAAI,CAAC;AACH,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF,IAAM,KAAK,eAAe,KAAK,EAAE,KAAK,QAAQ,IAAI,iBAAiB,UAAU,CAAC;AAC9E,IAAI;AACF,QAAM,CAAC,EAAE,OAAO,IAAI,MAAM,GAAG,QAAQ,OAAO;AAC5C,UAAQ,IAAI,KAAK,UAAU,EAAE,QAAQ,CAAC,CAAC;AACzC,UAAE;AACA,QAAM,cAAc,EAAE;AACxB;",
6
- "names": ["db", "db", "db", "db", "db", "db", "db", "db", "db", "db", "url", "db"]
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/preferences-migration.ts", "../../../lib/database/src/soft-deletion.ts", "../../../lib/database/src/queue-dispatch.ts", "../../../lib/database/src/backfill-migration.ts", "../../../lib/database/src/bulk-migration.ts", "../../../lib/database/src/queue-migration.ts", "../../../lib/database/src/assistance-migration.ts", "../../../lib/database/src/migrations.ts", "../../../lib/database/src/context.ts", "../src/migrate.ts"],
4
+ "sourcesContent": ["import knex from \"knex\";\nimport { Model, knexSnakeCaseMappers } from \"objection\";\nimport type { Knex } from \"knex\";\nimport { migrationSource } from \"./migrations.ts\";\nimport { databaseSignal } from \"./context.ts\";\n\nexport { migrationSource };\nexport { databaseSignal, withDatabaseSignal } from \"./context.ts\";\nexport type { Knex };\nexport type { QueryBuilder } from \"objection\";\nconst statementTimeouts = new WeakMap<Knex, number>();\n\nexport function createDatabase(\n url: string,\n options: {\n ssl?: boolean;\n max?: number;\n acquireTimeoutMs?: number;\n statementTimeoutMs?: number;\n } = {},\n) {\n const db = knex({\n client: \"pg\",\n connection: {\n connectionString: url,\n ssl: options.ssl ? { rejectUnauthorized: true } : undefined,\n connectionTimeoutMillis: options.acquireTimeoutMs ?? 10000,\n statement_timeout: options.statementTimeoutMs,\n application_name: \"grove\",\n },\n pool: { min: 0, max: options.max ?? 8 },\n acquireConnectionTimeout: options.acquireTimeoutMs ?? 10000,\n ...knexSnakeCaseMappers(),\n migrations: { migrationSource },\n });\n statementTimeouts.set(db, options.statementTimeoutMs ?? 10000);\n return db;\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 const signal = databaseSignal();\n signal?.throwIfAborted();\n return db.transaction(async (trx) => {\n signal?.throwIfAborted();\n await trx.raw(\n \"SELECT set_config('grove.account_id', ?, true), set_config('statement_timeout', ?, true)\",\n [accountId, String(statementTimeouts.get(db) ?? 10000)],\n );\n const result = await run(trx);\n // An aborted save must roll back, including when cancellation arrived during SQL.\n signal?.throwIfAborted();\n return result;\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(\n \"SELECT content_version, ask_enabled, export_version, filing_enabled, change_token FROM accounts LIMIT 0\",\n );\n await db.raw(\"SELECT id, lane, lease_id FROM background_tasks 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\";\n\nexport const aiPreferences = {\n name: \"20261022_013_ai_preferences\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE accounts\n ADD COLUMN titles_tags_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN classification_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN note_connections_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN notebook_connections_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN notebook_summaries_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN personal_summary_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN progress_summaries_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN ask_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN ask_version integer NOT NULL DEFAULT 0;\n UPDATE accounts SET\n titles_tags_enabled=organize_enabled, classification_enabled=organize_enabled,\n note_connections_enabled=organize_enabled, notebook_connections_enabled=organize_enabled,\n notebook_summaries_enabled=summaries_enabled, personal_summary_enabled=summaries_enabled,\n progress_summaries_enabled=summaries_enabled, ask_enabled=summaries_enabled;\n\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'\n OR (p.kind='decision' AND a.classification_enabled)\n OR (p.kind='organization' AND a.titles_tags_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 m.status='active' AND (m.expires_at IS NULL OR m.expires_at>now())\n AND CASE WHEN m.project_id IS NULL THEN a.personal_summary_enabled ELSE a.notebook_summaries_enabled END;\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.progress_summaries_enabled AND m.status='active'\n AND m.kind='handoff' AND (m.expires_at IS NULL OR 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\n/** Additive lifecycle change shared by normal mutations, cleanup and recovery. */\nexport async function softDeletion(db: Knex) {\n for (const table of [\n \"memories\",\n \"projects\",\n \"conversations\",\n \"connections\",\n ]) {\n await db.raw(\"ALTER TABLE ?? ADD COLUMN deleted_at timestamptz\", [table]);\n await db.raw(\n \"CREATE POLICY visible ON ?? AS RESTRICTIVE USING (deleted_at IS NULL) WITH CHECK (true)\",\n [table],\n );\n await db.raw(\n \"CREATE INDEX ?? ON ?? (account_id,id) WHERE deleted_at IS NULL\",\n [`${table}_visible`, table],\n );\n }\n for (const [table, parent] of [\n [\"memory_relationships\", \"memories\"],\n [\"notebook_relationships\", \"projects\"],\n ]) {\n await db.raw(\n `CREATE POLICY visible_endpoints ON ?? AS RESTRICTIVE USING\n (EXISTS(SELECT 1 FROM ?? p WHERE p.account_id=??.account_id AND p.id=??.left_id AND p.deleted_at IS NULL)\n AND EXISTS(SELECT 1 FROM ?? p WHERE p.account_id=??.account_id AND p.id=??.right_id AND p.deleted_at IS NULL)) WITH CHECK(true)`,\n [table, parent, table, table, parent, table, table],\n );\n }\n await db.raw(`CREATE POLICY visible_target ON public_shares AS RESTRICTIVE USING\n ((memory_id IS NOT NULL AND EXISTS(SELECT 1 FROM memories m WHERE m.account_id=public_shares.account_id AND m.id=public_shares.memory_id AND m.deleted_at IS NULL))\n OR (project_id IS NOT NULL AND EXISTS(SELECT 1 FROM projects p WHERE p.account_id=public_shares.account_id AND p.id=public_shares.project_id AND p.deleted_at IS NULL))) WITH CHECK(true)`);\n await db.raw(`\n DROP INDEX memories_task;\n CREATE UNIQUE INDEX memories_task ON memories(account_id,COALESCE(project_id,'00000000-0000-4000-8000-000000000000'::uuid),task_id)\n WHERE task_id IS NOT NULL AND deleted_at IS NULL;\n ALTER TABLE projects DROP CONSTRAINT projects_account_id_identity_key;\n CREATE UNIQUE INDEX projects_account_id_identity_key ON projects(account_id,identity) WHERE deleted_at IS NULL;\n\n CREATE FUNCTION grove_soft_delete() RETURNS trigger LANGUAGE plpgsql\n SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n BEGIN\n IF TG_TABLE_NAME='memories' THEN\n UPDATE memories SET deleted_at=now(),status='archived' WHERE id=OLD.id AND deleted_at IS NULL;\n ELSIF TG_TABLE_NAME='connections' THEN\n UPDATE connections SET deleted_at=now(),revoked_at=COALESCE(revoked_at,now()) WHERE id=OLD.id AND deleted_at IS NULL;\n ELSE\n EXECUTE format('UPDATE public.%I SET deleted_at=now() WHERE id=$1 AND deleted_at IS NULL',TG_TABLE_NAME) USING OLD.id;\n END IF;\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_soft_delete() FROM PUBLIC;\n\n CREATE FUNCTION grove_deleted_content() RETURNS trigger LANGUAGE plpgsql\n SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n BEGIN\n IF OLD.deleted_at IS NOT NULL OR NEW.deleted_at IS NULL THEN RETURN NULL; END IF;\n IF TG_TABLE_NAME='memories' THEN\n INSERT INTO deleted_memories(account_id,id) VALUES(NEW.account_id,NEW.id) ON CONFLICT DO NOTHING;\n DELETE FROM public_share_rates WHERE bucket IN (SELECT id::text FROM public_shares WHERE account_id=NEW.account_id AND memory_id=NEW.id);\n DELETE FROM jobs WHERE account_id=NEW.account_id AND memory_id=NEW.id;\n DELETE FROM memory_embeddings WHERE account_id=NEW.account_id AND memory_id=NEW.id;\n DELETE FROM notebook_profiles WHERE account_id=NEW.account_id AND project_id=NEW.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=NEW.account_id AND (left_id=NEW.project_id OR right_id=NEW.project_id\n OR EXISTS(SELECT 1 FROM jsonb_array_elements(assessment->'evidence') e WHERE e->>'id'=NEW.id::text));\n UPDATE public_shares SET revoked_at=now(),token_digest=NULL,token_ciphertext=NULL,version=version+1\n WHERE account_id=NEW.account_id AND memory_id=NEW.id;\n ELSIF TG_TABLE_NAME='conversations' THEN\n INSERT INTO deleted_conversations(account_id,id) VALUES(NEW.account_id,NEW.id) ON CONFLICT DO NOTHING;\n ELSIF TG_TABLE_NAME='projects' THEN\n DELETE FROM public_share_rates WHERE bucket IN (SELECT id::text FROM public_shares WHERE account_id=NEW.account_id AND project_id=NEW.id);\n UPDATE public_shares SET revoked_at=now(),token_digest=NULL,token_ciphertext=NULL,version=version+1\n WHERE account_id=NEW.account_id AND project_id=NEW.id;\n END IF;\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_deleted_content() FROM PUBLIC;\n `);\n for (const table of [\n \"memories\",\n \"projects\",\n \"conversations\",\n \"connections\",\n ]) {\n await db.raw(\n `CREATE TRIGGER soft_delete BEFORE DELETE ON ?? FOR EACH ROW EXECUTE FUNCTION grove_soft_delete()`,\n [table],\n );\n await db.raw(\n `CREATE TRIGGER deleted_content AFTER UPDATE OF deleted_at ON ?? FOR EACH ROW EXECUTE FUNCTION grove_deleted_content()`,\n [table],\n );\n }\n for (const [table, parent, column] of [\n [\"memory_revisions\", \"memories\", \"memory_id\"],\n [\"memory_embeddings\", \"memories\", \"memory_id\"],\n [\"memory_enrichments\", \"memories\", \"memory_id\"],\n [\"conversation_turns\", \"conversations\", \"conversation_id\"],\n [\"notebook_profiles\", \"projects\", \"project_id\"],\n ]) {\n await db.raw(\n `CREATE POLICY visible_parent ON ?? AS RESTRICTIVE USING\n (EXISTS(SELECT 1 FROM ?? parent WHERE parent.account_id=??.account_id AND parent.id=??.?? AND parent.deleted_at IS NULL)) WITH CHECK(true)`,\n [table, parent, table, table, column],\n );\n }\n // The public reader runs with narrowly elevated privileges, so it must filter\n // tombstones explicitly as well as checking account/share status.\n const { rows } = await db.raw(\n \"SELECT pg_get_functiondef('grove_public_share(text,text,uuid,uuid,uuid,integer,integer)'::regprocedure) AS definition\",\n );\n await db.raw(\n rows[0].definition\n .replaceAll(\n \"FROM projects WHERE account_id = owner_id\",\n \"FROM projects WHERE deleted_at IS NULL AND account_id = owner_id\",\n )\n .replaceAll(\n \"WHERE p.account_id = owner_id\",\n \"WHERE p.deleted_at IS NULL AND p.account_id = owner_id\",\n )\n .replaceAll(\n \"AND status = 'active' AND (expires_at\",\n \"AND deleted_at IS NULL AND status = 'active' AND (expires_at\",\n )\n .replaceAll(\n \"AND m.status = 'active' AND (m.expires_at\",\n \"AND m.deleted_at IS NULL AND m.status = 'active' AND (m.expires_at\",\n ),\n );\n\n await db.raw(`\n CREATE OR REPLACE 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,pg_temp AS $$\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(subject,event_at,deleted) 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';\n ELSIF event_type IN ('user.created','user.updated') THEN\n INSERT INTO subject_authority(subject,event_at,deleted) 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\n CREATE FUNCTION grove_schedule_cleanup() RETURNS integer LANGUAGE plpgsql\n SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n DECLARE added integer;\n BEGIN\n WITH due AS (\n SELECT a.id,CASE WHEN a.status='deleting' THEN 'account_cleanup' ELSE 'retention_cleanup' END AS kind\n FROM accounts a WHERE a.status='deleting' OR (a.status='active' AND (\n EXISTS(SELECT 1 FROM memories m WHERE m.account_id=a.id AND m.deleted_at IS NULL AND m.purge_at<=now())\n OR EXISTS(SELECT 1 FROM rate_buckets r WHERE r.account_id=a.id AND r.minute<now()-interval '1 day')))\n ORDER BY a.work_claimed_at NULLS FIRST,a.id LIMIT 20\n ), inserted AS (\n INSERT INTO background_tasks(account_id,kind,dedupe_key)\n SELECT id,kind,'lifecycle' FROM due\n ON CONFLICT(account_id,kind,dedupe_key) DO UPDATE SET status='pending',due_at=now(),updated_at=now(),\n finished_at=NULL,cursor='{}',processed=0,failures=0,error_code=NULL,dispatched_at=NULL,dispatch_id=NULL,dispatch_until=NULL\n WHERE background_tasks.status='succeeded'\n RETURNING 1\n ) SELECT count(*) INTO added FROM inserted;\n RETURN added;\n END $$;\n REVOKE ALL ON FUNCTION grove_schedule_cleanup() FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_schedule_cleanup() TO grove_worker;\n\n CREATE FUNCTION grove_account_cleanup_requested() RETURNS trigger LANGUAGE plpgsql\n SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n BEGIN\n IF NEW.status='deleting' AND OLD.status IS DISTINCT FROM NEW.status THEN\n INSERT INTO background_tasks(account_id,kind,dedupe_key) VALUES(NEW.id,'account_cleanup','lifecycle')\n ON CONFLICT(account_id,kind,dedupe_key) DO NOTHING;\n UPDATE background_tasks SET status='cancelled',lease_id=NULL,lease_until=NULL,updated_at=now(),finished_at=now()\n WHERE account_id=NEW.id AND kind NOT IN ('account_cleanup','artifact_cleanup') AND status IN ('pending','running');\n END IF;\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_account_cleanup_requested() FROM PUBLIC;\n CREATE TRIGGER account_cleanup_requested AFTER UPDATE OF status ON accounts\n FOR EACH ROW EXECUTE FUNCTION grove_account_cleanup_requested();\n `);\n}\n", "import type { Knex } from \"knex\";\n\nexport async function queueDispatch(db: Knex) {\n await db.raw(`\n CREATE FUNCTION grove_job_due(j jobs, profiles text[]) RETURNS boolean LANGUAGE sql STABLE\n SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n SELECT 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())\n AND j.epoch=(SELECT epoch FROM processing_control WHERE singleton)\n AND (profiles IS NULL OR j.profile=ANY(profiles))\n AND EXISTS(SELECT 1 FROM accounts a WHERE a.id=j.account_id AND a.status='active')\n AND (j.memory_id IS NULL OR EXISTS(SELECT 1 FROM memories m WHERE m.account_id=j.account_id AND m.id=j.memory_id\n AND m.version=j.version AND m.deleted_at IS NULL AND m.status='active' AND (m.expires_at IS NULL OR m.expires_at>now())))\n AND (j.kind NOT IN ('decision','relationship_scan') OR NOT EXISTS(SELECT 1 FROM jobs e WHERE e.account_id=j.account_id\n AND e.target=j.target AND e.kind='embedding' AND e.failed_at IS NULL AND e.epoch=j.epoch 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\n 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 e.epoch=j.epoch\n 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')\n AND e.failed_at IS NULL AND e.epoch=j.epoch AND (profiles IS NULL OR e.profile=ANY(profiles))))\n $$;\n REVOKE ALL ON FUNCTION grove_job_due(jobs,text[]) FROM PUBLIC;\n\n CREATE FUNCTION grove_claim_processing(profiles text[], wanted uuid, requested_lane text, account_limit integer, provider_limit integer DEFAULT 8) RETURNS SETOF jobs\n LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE selected uuid; owner_id uuid; selected_lane text;\n BEGIN\n SELECT j.id,j.account_id,j.lane INTO selected,owner_id,selected_lane FROM jobs j JOIN accounts a ON a.id=j.account_id\n WHERE (wanted IS NULL OR j.id=wanted) AND (requested_lane IS NULL OR j.lane=requested_lane) AND grove_job_due(j,profiles)\n AND (SELECT count(*) FROM jobs busy WHERE busy.account_id=j.account_id AND busy.lane=j.lane AND busy.lease_until>now())\n < greatest(1,least(account_limit,32))\n ORDER BY a.work_claimed_at NULLS FIRST,j.due_at,j.id LIMIT 1 FOR UPDATE OF a SKIP LOCKED;\n IF selected IS NULL THEN RETURN; END IF;\n -- One short cross-replica admission lock per provider lane, never held\n -- while calling a provider. Active leases are the durable reservations.\n IF NOT pg_try_advisory_xact_lock(hashtextextended(selected_lane,68142020)) THEN RETURN; END IF;\n IF (SELECT count(*) FROM jobs WHERE lane=selected_lane AND lease_until>now())\n >= greatest(1,least(provider_limit,128)) THEN RETURN; END IF;\n PERFORM 1 FROM accounts WHERE id=owner_id AND status='active' FOR UPDATE SKIP LOCKED;\n IF NOT FOUND THEN RETURN; END IF;\n IF (SELECT count(*) FROM jobs WHERE account_id=owner_id AND lane=selected_lane AND lease_until>now())\n >= greatest(1,least(account_limit,32)) THEN RETURN; END IF;\n PERFORM 1 FROM jobs j WHERE j.id=selected AND grove_job_due(j,profiles) FOR UPDATE SKIP LOCKED;\n IF NOT FOUND THEN RETURN; END IF;\n UPDATE accounts SET work_claimed_at=now() WHERE id=owner_id;\n RETURN QUERY UPDATE jobs SET lease_id=gen_random_uuid(),lease_until=now()+interval '120 seconds',attempts=attempts+1\n WHERE id=selected RETURNING *;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_processing(text[],uuid,text,integer,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_processing(text[],uuid,text,integer,integer) TO grove_worker;\n CREATE OR REPLACE FUNCTION grove_claim_job(profiles text[] DEFAULT NULL,wanted uuid DEFAULT NULL) RETURNS SETOF jobs\n LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n SELECT * FROM grove_claim_processing(profiles,wanted,NULL,2)\n $$;\n\n CREATE INDEX jobs_active_leases ON jobs(account_id,lane,lease_until) WHERE lease_id IS NOT NULL;\n CREATE INDEX jobs_provider_leases ON jobs(lane,lease_until) WHERE lease_id IS NOT NULL;\n CREATE OR REPLACE FUNCTION grove_sweep_deliveries() RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n BEGIN\n UPDATE jobs SET failed_at=now(),error_code='lease_exhausted',lease_id=NULL,lease_until=NULL\n WHERE id IN (SELECT id FROM jobs WHERE failed_at IS NULL AND attempts>=5 AND (lease_until IS NULL OR lease_until<now()) LIMIT 1000 FOR UPDATE SKIP LOCKED);\n UPDATE transactional_emails SET failed_at=now(),error_code='delivery_exhausted',lease_id=NULL,lease_until=NULL\n WHERE id IN (SELECT id FROM transactional_emails WHERE sent_at IS NULL AND failed_at IS NULL\n AND (attempts>=5 OR created_at<now()-interval '23 hours') AND (lease_until IS NULL OR lease_until<now()) LIMIT 1000 FOR UPDATE SKIP LOCKED);\n UPDATE background_tasks SET status='failed',error_code=CASE WHEN expires_at<=now() THEN 'export_expired' ELSE 'lease_exhausted' END,\n lease_id=NULL,lease_until=NULL,dispatch_id=NULL,dispatch_until=NULL,dispatched_at=NULL,finished_at=now(),updated_at=now()\n WHERE id IN (SELECT id FROM background_tasks WHERE status IN ('pending','running')\n AND ((failures>=5 AND (lease_until IS NULL OR lease_until<now())) OR (kind='export' AND expires_at<=now())) LIMIT 1000 FOR UPDATE SKIP LOCKED);\n END $$;\n CREATE OR REPLACE FUNCTION grove_claim_email(wanted uuid DEFAULT NULL) RETURNS SETOF transactional_emails\n LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE selected uuid; owner_id uuid;\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 SELECT e.id,e.account_id INTO selected,owner_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 AND NOT EXISTS(SELECT 1 FROM transactional_emails busy WHERE busy.account_id=e.account_id AND busy.lease_until>now())\n ORDER BY a.work_claimed_at NULLS FIRST,e.due_at,e.id LIMIT 1 FOR UPDATE OF a SKIP LOCKED;\n IF selected IS NULL THEN RETURN; END IF;\n PERFORM 1 FROM accounts WHERE id=owner_id AND status='active' FOR UPDATE SKIP LOCKED;\n IF NOT FOUND OR EXISTS(SELECT 1 FROM transactional_emails WHERE account_id=owner_id AND lease_until>now()) THEN RETURN; END IF;\n UPDATE accounts SET work_claimed_at=now() WHERE id=owner_id;\n RETURN QUERY UPDATE transactional_emails SET lease_id=gen_random_uuid(),lease_until=now()+interval '120 seconds',attempts=attempts+1\n WHERE id=selected AND sent_at IS NULL AND failed_at IS NULL AND (lease_until IS NULL OR lease_until<now()) RETURNING *;\n END $$;\n CREATE FUNCTION grove_dispatch_claim(source text, requested_lane text, profiles text[], batch_size integer)\n RETURNS TABLE(id uuid,account_id uuid,kind text,lane text,dispatch_id uuid)\n LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE relation text; eligible text; lane_expression text;\n BEGIN\n IF source='memory' THEN\n relation:='jobs'; eligible:='grove_job_due(q,$1) AND q.lane=$2'; lane_expression:='q.lane';\n ELSIF source='task' THEN\n relation:='background_tasks'; eligible:='grove_task_allowed(q) AND q.status IN (''pending'',''running'') AND q.failures<5 AND q.lane=$2'; lane_expression:='q.lane';\n ELSIF source='email' AND requested_lane='email' THEN\n relation:='transactional_emails'; eligible:='q.sent_at IS NULL AND q.failed_at IS NULL AND q.attempts<5 AND q.created_at>now()-interval ''23 hours'' AND EXISTS(SELECT 1 FROM accounts a WHERE a.id=q.account_id AND a.status=''active'')'; lane_expression:='''email''::text';\n ELSE RETURN; END IF;\n RETURN QUERY EXECUTE format('\n WITH eligible AS (\n SELECT q.id,row_number() OVER(PARTITION BY q.account_id ORDER BY q.due_at,q.id) AS rank\n FROM public.%I q WHERE %s AND q.due_at<=now() AND (q.lease_until IS NULL OR q.lease_until<now())\n AND (q.dispatch_until IS NULL OR q.dispatch_until<now())\n AND (q.dispatched_at IS NULL OR q.dispatched_at<now()-interval ''15 seconds'')\n ), picked AS (\n SELECT q.id FROM public.%I q JOIN eligible e ON e.id=q.id WHERE e.rank<=4\n AND (q.dispatch_until IS NULL OR q.dispatch_until<now())\n ORDER BY e.rank,q.due_at,q.id FOR UPDATE OF q SKIP LOCKED LIMIT $3\n ) UPDATE public.%I q SET dispatch_id=gen_random_uuid(),dispatch_until=now()+interval ''30 seconds''\n FROM picked p WHERE q.id=p.id RETURNING q.id,q.account_id,$4::text,%s,q.dispatch_id',\n relation,eligible,relation,relation,lane_expression)\n USING profiles,requested_lane,greatest(1,least(batch_size,100)),source;\n END $$;\n REVOKE ALL ON FUNCTION grove_dispatch_claim(text,text,text[],integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_dispatch_claim(text,text,text[],integer) TO grove_worker;\n\n CREATE FUNCTION grove_dispatch_finish(source text,wanted uuid,token uuid,confirmed boolean) RETURNS void\n LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE relation text;\n BEGIN\n relation:=CASE source WHEN 'memory' THEN 'jobs' WHEN 'email' THEN 'transactional_emails' WHEN 'task' THEN 'background_tasks' END;\n IF relation IS NULL THEN RETURN; END IF;\n EXECUTE format('UPDATE public.%I SET dispatched_at=CASE WHEN $3 THEN now() ELSE NULL END,dispatch_id=NULL,dispatch_until=NULL WHERE id=$1 AND dispatch_id=$2',relation)\n USING wanted,token,confirmed;\n END $$;\n REVOKE ALL ON FUNCTION grove_dispatch_finish(text,uuid,uuid,boolean) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_dispatch_finish(text,uuid,uuid,boolean) TO grove_worker;\n\n CREATE FUNCTION grove_queue_stats() RETURNS TABLE(lane text,pending bigint,running bigint,failed bigint,oldest_seconds double precision)\n LANGUAGE sql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n SELECT q.lane,count(*) FILTER(WHERE q.pending),count(*) FILTER(WHERE q.running),count(*) FILTER(WHERE q.failed),\n coalesce(extract(epoch FROM now()-min(q.due_at) FILTER(WHERE q.pending)),0)::double precision\n FROM (\n SELECT j.lane,j.due_at,j.failed_at IS NULL AND (j.lease_until IS NULL OR j.lease_until<now()) AS pending,\n j.lease_until>now() AS running,j.failed_at IS NOT NULL AS failed FROM jobs j WHERE j.epoch=(SELECT epoch FROM processing_control WHERE singleton)\n UNION ALL SELECT t.lane,t.due_at,t.status='pending',t.status='running',t.status='failed' FROM background_tasks t WHERE t.status IN ('pending','running','failed')\n UNION ALL SELECT 'email',e.due_at,e.failed_at IS NULL AND (e.lease_until IS NULL OR e.lease_until<now()),e.lease_until>now(),e.failed_at IS NOT NULL\n FROM transactional_emails e WHERE e.sent_at IS NULL\n ) q GROUP BY q.lane\n $$;\n REVOKE ALL ON FUNCTION grove_queue_stats() FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_queue_stats() TO grove_worker;\n `);\n}\n", "import type { Knex } from \"knex\";\n\nexport async function incrementalBackfills(db: Knex) {\n await db.raw(`\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,pg_temp AS $$\n DECLARE generation bigint;\n BEGIN\n PERFORM pg_advisory_xact_lock(68142019);\n UPDATE processing_control SET epoch=epoch+1,profiles=jsonb_build_object('embedding',embedding_profile,'decision',decision_profile,'generation',generation_profile)\n WHERE singleton RETURNING epoch INTO generation;\n UPDATE background_tasks SET status='cancelled',finished_at=now(),updated_at=now(),lease_id=NULL,lease_until=NULL\n WHERE kind='model_backfill' AND status IN ('pending','running');\n INSERT INTO background_tasks(kind,dedupe_key,payload)\n VALUES('model_backfill',generation::text,jsonb_build_object('epoch',generation));\n END $$;\n\n CREATE FUNCTION grove_backfill_batch(wanted uuid,token uuid,batch_size integer) RETURNS boolean\n LANGUAGE plpgsql SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE task background_tasks; control processing_control; owner accounts;\n selected uuid[]; last_id uuid; completed_count integer; last_owner uuid; after_note uuid;\n BEGIN\n PERFORM pg_advisory_xact_lock_shared(68142019);\n SELECT * INTO task FROM background_tasks WHERE id=wanted AND lease_id=token AND status='running'\n AND kind='model_backfill' AND lease_until>now() FOR UPDATE;\n IF NOT FOUND THEN RETURN false; END IF;\n SELECT * INTO control FROM processing_control WHERE singleton;\n IF (task.payload->>'epoch')::bigint IS DISTINCT FROM control.epoch THEN\n UPDATE background_tasks SET status='cancelled',lease_id=NULL,lease_until=NULL,updated_at=now(),finished_at=now() WHERE id=task.id;\n RETURN false;\n END IF;\n last_owner:=(task.cursor->>'accountId')::uuid;\n after_note:=(task.cursor->>'afterId')::uuid;\n SELECT * INTO owner FROM accounts WHERE status='active'\n AND (last_owner IS NULL OR id>last_owner OR (id=last_owner AND after_note IS NOT NULL)) ORDER BY id LIMIT 1 FOR UPDATE;\n IF NOT FOUND THEN\n PERFORM grove_task_checkpoint(task.id,token,task.cursor,task.processed,task.result,true,0);\n RETURN true;\n END IF;\n IF owner.id IS DISTINCT FROM last_owner THEN after_note:=NULL; END IF;\n SELECT array_agg(id ORDER BY id) INTO selected FROM (\n SELECT id FROM memories WHERE account_id=owner.id AND deleted_at IS NULL AND status='active'\n AND (expires_at IS NULL OR expires_at>now()) AND (after_note IS NULL OR id>after_note)\n ORDER BY id LIMIT greatest(1,least(batch_size,250))\n ) page;\n completed_count:=coalesce(cardinality(selected),0);\n last_id:=selected[completed_count];\n -- Old generations are removed incrementally, never in the settings request.\n DELETE FROM jobs WHERE id IN (SELECT id FROM jobs WHERE account_id=owner.id AND epoch<control.epoch ORDER BY id LIMIT 1000);\n IF EXISTS(SELECT 1 FROM jobs WHERE account_id=owner.id AND epoch<control.epoch) THEN\n PERFORM grove_task_checkpoint(task.id,token,jsonb_build_object('accountId',owner.id,'afterId',coalesce(after_note,'00000000-0000-0000-0000-000000000000'::uuid)),task.processed,NULL,false,0);\n RETURN true;\n END IF;\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 FROM memories m\n CROSS JOIN (VALUES ('embedding',control.profiles->>'embedding'),('decision',control.profiles->>'decision'),('organization',control.profiles->>'generation')) p(kind,profile)\n WHERE m.account_id=owner.id AND m.id=ANY(selected) AND p.profile IS NOT NULL\n AND (p.kind='embedding' OR (p.kind='decision' AND owner.classification_enabled) OR (p.kind='organization' AND owner.titles_tags_enabled))\n ON CONFLICT(account_id,kind,target,profile) DO UPDATE SET version=EXCLUDED.version,epoch=EXCLUDED.epoch,\n attempts=0,failed_at=NULL,error_code=NULL,lease_id=NULL,lease_until=NULL,dispatch_id=NULL,dispatch_until=NULL,dispatched_at=NULL,due_at=now()\n WHERE jobs.epoch<>EXCLUDED.epoch OR jobs.version IS DISTINCT FROM EXCLUDED.version;\n IF control.profiles->>'generation' IS NOT NULL THEN\n INSERT INTO jobs(account_id,kind,target,profile,scope,due_at)\n SELECT DISTINCT owner.id,'brief',coalesce(m.project_id::text,'personal'),control.profiles->>'generation',\n jsonb_build_object('projectId',m.project_id),now()+interval '5 seconds'\n FROM memories m WHERE m.account_id=owner.id AND m.id=ANY(selected)\n AND CASE WHEN m.project_id IS NULL THEN owner.personal_summary_enabled ELSE owner.notebook_summaries_enabled END\n ON CONFLICT(account_id,kind,target,profile) DO UPDATE SET epoch=EXCLUDED.epoch,attempts=0,failed_at=NULL,error_code=NULL,\n lease_id=NULL,lease_until=NULL,dispatched_at=NULL,dispatch_id=NULL,dispatch_until=NULL,due_at=EXCLUDED.due_at\n WHERE jobs.epoch<>EXCLUDED.epoch;\n INSERT INTO jobs(account_id,kind,target,profile,scope,due_at)\n SELECT owner.id,'brief',coalesce(m.project_id::text,'personal')||':task:'||m.task_id,control.profiles->>'generation',\n jsonb_build_object('projectId',m.project_id,'taskId',m.task_id),now()+interval '5 seconds'\n FROM memories m WHERE m.account_id=owner.id AND m.id=ANY(selected) AND m.task_id IS NOT NULL AND owner.progress_summaries_enabled\n ON CONFLICT(account_id,kind,target,profile) DO UPDATE SET epoch=EXCLUDED.epoch,attempts=0,failed_at=NULL,error_code=NULL,\n lease_id=NULL,lease_until=NULL,dispatched_at=NULL,dispatch_id=NULL,dispatch_until=NULL,due_at=EXCLUDED.due_at\n WHERE jobs.epoch<>EXCLUDED.epoch;\n END IF;\n UPDATE accounts SET organization_due_at=now() WHERE id=owner.id;\n PERFORM grove_task_checkpoint(task.id,token,jsonb_build_object('accountId',owner.id,'afterId',\n CASE WHEN completed_count>=greatest(1,least(batch_size,250)) THEN last_id ELSE NULL END),\n task.processed+completed_count,NULL,false,0);\n RETURN true;\n END $$;\n REVOKE ALL ON FUNCTION grove_backfill_batch(uuid,uuid,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_backfill_batch(uuid,uuid,integer) TO grove_worker;\n `);\n}\n", "import type { Knex } from \"knex\";\n\nexport async function bulkWork(db: Knex) {\n await db.raw(`\n ALTER TABLE accounts ADD COLUMN export_version bigint NOT NULL DEFAULT 0;\n ALTER TABLE background_tasks ADD CONSTRAINT background_tasks_owner_id UNIQUE(account_id,id);\n CREATE TABLE export_objects (\n object_key text PRIMARY KEY,account_id uuid NOT NULL,task_id uuid NOT NULL,part integer,\n bytes bigint NOT NULL DEFAULT 0,expires_at timestamptz NOT NULL DEFAULT now()+interval '1 day',\n FOREIGN KEY(account_id,task_id) REFERENCES background_tasks(account_id,id)\n );\n CREATE UNIQUE INDEX export_objects_parts ON export_objects(task_id,part) WHERE part IS NOT NULL;\n CREATE INDEX export_objects_expiry ON export_objects(expires_at,account_id);\n CREATE TABLE import_sources (\n account_id uuid NOT NULL,source text NOT NULL,external_id text NOT NULL,\n memory_id uuid NOT NULL,version integer NOT NULL,fingerprint text NOT NULL,\n PRIMARY KEY(account_id,source,external_id),\n FOREIGN KEY(account_id,memory_id) REFERENCES memories(account_id,id)\n );\n CREATE TABLE connector_checkpoints (\n account_id uuid NOT NULL REFERENCES accounts(id),source text NOT NULL,cursor jsonb NOT NULL DEFAULT '{}',\n PRIMARY KEY(account_id,source)\n );\n CREATE FUNCTION grove_export_version() RETURNS trigger LANGUAGE plpgsql\n SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n BEGIN\n UPDATE accounts SET export_version=export_version+1 WHERE id=COALESCE(NEW.account_id,OLD.account_id);\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_export_version() FROM PUBLIC;\n `);\n for (const table of [\n \"export_objects\",\n \"import_sources\",\n \"connector_checkpoints\",\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 for (const table of [\n \"memories\",\n \"projects\",\n \"conversations\",\n \"conversation_turns\",\n \"memory_relationships\",\n \"notebook_relationships\",\n ]) {\n await db.raw(\n \"CREATE TRIGGER export_version AFTER INSERT OR UPDATE OR DELETE ON ?? FOR EACH ROW EXECUTE FUNCTION grove_export_version()\",\n [table],\n );\n }\n await db.raw(`\n CREATE FUNCTION grove_schedule_artifacts() RETURNS integer LANGUAGE plpgsql\n SECURITY DEFINER SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE added integer;\n BEGIN\n WITH inserted AS (INSERT INTO background_tasks(account_id,kind,dedupe_key)\n SELECT DISTINCT account_id,'artifact_cleanup','artifacts' FROM export_objects WHERE expires_at<=now() LIMIT 20\n ON CONFLICT(account_id,kind,dedupe_key) DO UPDATE SET status='pending',failures=0,error_code=NULL,\n due_at=now(),finished_at=NULL,updated_at=now(),dispatched_at=NULL,dispatch_id=NULL,dispatch_until=NULL\n WHERE background_tasks.status='succeeded' RETURNING 1)\n SELECT count(*) INTO added FROM inserted;\n RETURN added;\n END $$;\n REVOKE ALL ON FUNCTION grove_schedule_artifacts() FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_schedule_artifacts() TO grove_worker;\n `);\n}\n", "import type { Knex } from \"knex\";\nimport { softDeletion } from \"./soft-deletion.ts\";\nimport { queueDispatch } from \"./queue-dispatch.ts\";\nimport { incrementalBackfills } from \"./backfill-migration.ts\";\nimport { bulkWork } from \"./bulk-migration.ts\";\n\nexport const queueProcessing = {\n name: \"20261022_014_queue_processing\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE accounts ADD COLUMN work_claimed_at timestamptz;\n CREATE TABLE processing_control (\n singleton boolean PRIMARY KEY DEFAULT true CHECK(singleton),\n epoch bigint NOT NULL DEFAULT 0, profiles jsonb NOT NULL DEFAULT '{}'\n );\n INSERT INTO processing_control DEFAULT VALUES;\n GRANT SELECT ON processing_control TO grove_runtime, grove_worker;\n ALTER TABLE jobs ADD COLUMN epoch bigint NOT NULL DEFAULT 0,\n ADD COLUMN created_at timestamptz NOT NULL DEFAULT now(),\n ADD COLUMN dispatch_id uuid, ADD COLUMN dispatch_until timestamptz,\n ADD COLUMN lane text GENERATED ALWAYS AS\n (CASE WHEN kind='embedding' THEN 'indexing' ELSE 'enrichment' END) STORED;\n ALTER TABLE transactional_emails ADD COLUMN dispatch_id uuid, ADD COLUMN dispatch_until timestamptz;\n CREATE INDEX jobs_lane_due ON jobs(lane, due_at, account_id) WHERE failed_at IS NULL;\n CREATE FUNCTION grove_job_epoch() RETURNS trigger LANGUAGE plpgsql\n SET search_path = pg_catalog, public, pg_temp AS $$\n BEGIN\n NEW.epoch := (SELECT epoch FROM processing_control WHERE singleton);\n RETURN NEW;\n END $$;\n REVOKE ALL ON FUNCTION grove_job_epoch() FROM PUBLIC;\n CREATE TRIGGER job_epoch BEFORE INSERT ON jobs FOR EACH ROW EXECUTE FUNCTION grove_job_epoch();\n\n CREATE TABLE background_tasks (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(), account_id uuid REFERENCES accounts(id),\n kind text NOT NULL CHECK(kind IN ('export','account_cleanup','retention_cleanup','artifact_cleanup','model_backfill','import','connector_sync')),\n lane text GENERATED ALWAYS AS (CASE WHEN kind IN ('account_cleanup','retention_cleanup','artifact_cleanup') THEN 'maintenance' ELSE 'bulk' END) STORED,\n dedupe_key text NOT NULL CHECK(length(dedupe_key) BETWEEN 1 AND 250),\n payload jsonb NOT NULL DEFAULT '{}' CHECK(octet_length(payload::text)<=1048576),\n cursor jsonb NOT NULL DEFAULT '{}', result jsonb,\n status text NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','running','succeeded','failed','cancelled')),\n processed bigint NOT NULL DEFAULT 0 CHECK(processed>=0), total bigint CHECK(total>=0),\n attempts integer NOT NULL DEFAULT 0, failures integer NOT NULL DEFAULT 0,\n due_at timestamptz NOT NULL DEFAULT now(), lease_id uuid, lease_until timestamptz,\n dispatch_id uuid, dispatch_until timestamptz, dispatched_at timestamptz,\n error_code text, claimed_at timestamptz, created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),\n finished_at timestamptz, expires_at timestamptz,\n UNIQUE NULLS NOT DISTINCT(account_id,kind,dedupe_key),\n CHECK(account_id IS NOT NULL OR kind='model_backfill')\n );\n ALTER TABLE background_tasks ENABLE ROW LEVEL SECURITY;\n ALTER TABLE background_tasks FORCE ROW LEVEL SECURITY;\n CREATE POLICY tenant ON background_tasks 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 ON background_tasks TO grove_runtime;\n GRANT SELECT,INSERT,UPDATE,DELETE ON background_tasks TO grove_worker;\n CREATE INDEX background_tasks_due ON background_tasks(lane,due_at,account_id) WHERE status IN ('pending','running');\n CREATE INDEX background_tasks_account ON background_tasks(account_id,created_at DESC,id);\n CREATE INDEX background_tasks_leases ON background_tasks(account_id,lane,lease_until) WHERE status='running';\n\n CREATE FUNCTION grove_task_allowed(t background_tasks) RETURNS boolean LANGUAGE sql STABLE\n SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n SELECT (t.account_id IS NULL AND t.kind='model_backfill') OR EXISTS(\n SELECT 1 FROM accounts a WHERE a.id=t.account_id AND\n (t.kind='artifact_cleanup' OR (a.status='active' AND t.kind<>'account_cleanup') OR (t.kind='account_cleanup' AND a.status IN ('deleting','deleted'))))\n $$;\n REVOKE ALL ON FUNCTION grove_task_allowed(background_tasks) FROM PUBLIC;\n\n CREATE FUNCTION grove_claim_task(wanted uuid, requested_lane text, account_limit integer) RETURNS SETOF background_tasks\n LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n DECLARE candidate record; selected uuid; owner_id uuid; selected_lane text;\n BEGIN\n -- Expired attempts are reclaimed; the failure count bounds consecutive crashes.\n UPDATE background_tasks SET status='failed',error_code='lease_exhausted',finished_at=now(),updated_at=now(),lease_id=NULL,lease_until=NULL\n WHERE status IN ('pending','running') AND failures>=5 AND (lease_until IS NULL OR lease_until<now());\n FOR candidate IN SELECT t.id,t.account_id,t.lane FROM background_tasks t LEFT JOIN accounts a ON a.id=t.account_id\n WHERE (wanted IS NULL OR t.id=wanted) AND (requested_lane IS NULL OR t.lane=requested_lane)\n AND t.status IN ('pending','running') AND t.failures<5 AND t.due_at<=now()\n AND (t.lease_until IS NULL OR t.lease_until<now()) AND grove_task_allowed(t)\n AND (t.account_id IS NULL OR (SELECT count(*) FROM background_tasks busy WHERE busy.account_id=t.account_id\n AND busy.lane=t.lane AND busy.status='running' AND busy.lease_until>now()) < greatest(1,least(account_limit,32)))\n ORDER BY coalesce(a.work_claimed_at,t.claimed_at) NULLS FIRST,t.due_at,t.id LIMIT 32\n LOOP\n selected:=candidate.id; owner_id:=candidate.account_id; selected_lane:=candidate.lane;\n IF owner_id IS NOT NULL THEN\n -- Match mutation lock order: account before task. Recheck capacity after locking.\n PERFORM 1 FROM accounts WHERE id=owner_id FOR UPDATE SKIP LOCKED;\n IF NOT FOUND THEN CONTINUE; END IF;\n IF (SELECT count(*) FROM background_tasks WHERE account_id=owner_id AND status='running' AND lease_until>now()\n AND lane=selected_lane) >= greatest(1,least(account_limit,32)) THEN CONTINUE; END IF;\n END IF;\n PERFORM 1 FROM background_tasks t WHERE t.id=selected AND t.status IN ('pending','running')\n AND (t.lease_until IS NULL OR t.lease_until<now()) AND t.failures<5 AND t.due_at<=now()\n AND grove_task_allowed(t) FOR UPDATE SKIP LOCKED;\n IF NOT FOUND THEN CONTINUE; END IF;\n IF owner_id IS NOT NULL THEN UPDATE accounts SET work_claimed_at=now() WHERE id=owner_id; END IF;\n RETURN QUERY UPDATE background_tasks SET status='running',lease_id=gen_random_uuid(),lease_until=now()+interval '120 seconds',\n attempts=attempts+1,failures=failures+1,claimed_at=now(),updated_at=now() WHERE id=selected RETURNING *;\n RETURN;\n END LOOP;\n END $$;\n REVOKE ALL ON FUNCTION grove_claim_task(uuid,text,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_claim_task(uuid,text,integer) TO grove_worker;\n\n CREATE FUNCTION grove_task_heartbeat(wanted uuid, token uuid) RETURNS boolean LANGUAGE sql\n SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n WITH renewed AS (UPDATE background_tasks t SET lease_until=now()+interval '120 seconds'\n WHERE t.id=wanted AND t.lease_id=token AND t.status='running' AND t.lease_until>now() AND grove_task_allowed(t) RETURNING 1)\n SELECT EXISTS(SELECT 1 FROM renewed)\n $$;\n REVOKE ALL ON FUNCTION grove_task_heartbeat(uuid,uuid) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_task_heartbeat(uuid,uuid) TO grove_worker;\n\n CREATE FUNCTION grove_task_checkpoint(wanted uuid, token uuid, checkpoint jsonb, done_count bigint, outcome jsonb, complete boolean, retry_seconds integer)\n RETURNS boolean LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n WITH saved AS (UPDATE background_tasks t SET cursor=checkpoint,processed=done_count,result=outcome,\n status=CASE WHEN complete THEN 'succeeded' ELSE 'pending' END,failures=0,error_code=NULL,\n finished_at=CASE WHEN complete THEN now() ELSE NULL END,updated_at=now(),\n lease_id=NULL,lease_until=NULL,dispatch_id=NULL,dispatch_until=NULL,dispatched_at=NULL,\n due_at=now()+greatest(0,least(retry_seconds,86400))*interval '1 second'\n WHERE t.id=wanted AND t.lease_id=token AND t.status='running' AND t.lease_until>now() AND grove_task_allowed(t) RETURNING 1)\n SELECT EXISTS(SELECT 1 FROM saved)\n $$;\n REVOKE ALL ON FUNCTION grove_task_checkpoint(uuid,uuid,jsonb,bigint,jsonb,boolean,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_task_checkpoint(uuid,uuid,jsonb,bigint,jsonb,boolean,integer) TO grove_worker;\n\n CREATE FUNCTION grove_task_failure(wanted uuid, token uuid, code text, retryable boolean, retry_seconds integer)\n RETURNS void LANGUAGE sql SECURITY DEFINER SET search_path = pg_catalog, public, pg_temp AS $$\n UPDATE background_tasks SET status=CASE WHEN retryable AND failures<5 THEN 'pending' ELSE 'failed' END,\n error_code=left(code,80),lease_id=NULL,lease_until=NULL,dispatch_id=NULL,dispatch_until=NULL,dispatched_at=NULL,updated_at=now(),\n finished_at=CASE WHEN retryable AND failures<5 THEN NULL ELSE now() END,\n due_at=now()+greatest(1,least(retry_seconds,3600))*interval '1 second'\n WHERE id=wanted AND lease_id=token AND status='running' AND lease_until>now()\n $$;\n REVOKE ALL ON FUNCTION grove_task_failure(uuid,uuid,text,boolean,integer) FROM PUBLIC;\n GRANT EXECUTE ON FUNCTION grove_task_failure(uuid,uuid,text,boolean,integer) TO grove_worker;\n `);\n await softDeletion(db);\n await queueDispatch(db);\n await incrementalBackfills(db);\n await bulkWork(db);\n },\n async down() {\n throw new Error(\"Use a forward migration\");\n },\n};\n", "import type { Knex } from \"knex\";\n\nexport const notebookAssistance = {\n name: \"20261022_015_notebook_assistance\",\n async up(db: Knex) {\n await db.raw(`\n ALTER TABLE accounts ADD COLUMN filing_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN action_lists_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN digests_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN cleanup_enabled boolean NOT NULL DEFAULT true,\n ADD COLUMN change_token bigint NOT NULL DEFAULT 0,\n ADD COLUMN notebook_catalog_version integer NOT NULL DEFAULT 0;\n UPDATE accounts SET filing_enabled=titles_tags_enabled, action_lists_enabled=ask_enabled,\n digests_enabled=notebook_summaries_enabled, cleanup_enabled=note_connections_enabled;\n CREATE TABLE assistance_requests (\n account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, id uuid NOT NULL,\n kind text NOT NULL CHECK(kind IN('filing','actions','digest','cleanup')),\n input jsonb NOT NULL, fingerprint text NOT NULL, profile text NOT NULL,\n status text NOT NULL DEFAULT 'pending', version integer NOT NULL DEFAULT 1,\n state jsonb NOT NULL DEFAULT '{}', dependencies jsonb NOT NULL DEFAULT '[]',\n scopes jsonb NOT NULL DEFAULT '[]', result jsonb, error text,\n applied jsonb NOT NULL DEFAULT '[]', undo jsonb, application text,\n created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now(),\n PRIMARY KEY(account_id,id)\n );\n CREATE TABLE assistance_reviews (\n account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,\n key text NOT NULL, version integer NOT NULL DEFAULT 0, dismissed boolean NOT NULL,\n PRIMARY KEY(account_id,key)\n );\n CREATE TABLE notebook_changes (\n account_id uuid NOT NULL REFERENCES accounts(id) ON DELETE CASCADE, token bigint NOT NULL,\n memory_id uuid NOT NULL, old_project_id uuid, new_project_id uuid,\n before_version integer, after_version integer, kind text NOT NULL,\n at timestamptz NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY(account_id,token)\n );\n CREATE INDEX notebook_changes_old ON notebook_changes(account_id,old_project_id,token);\n CREATE INDEX notebook_changes_new ON notebook_changes(account_id,new_project_id,token);\n CREATE TABLE notebook_checkpoints (\n account_id uuid NOT NULL, project_id uuid NOT NULL, token bigint NOT NULL,\n PRIMARY KEY(account_id,project_id),\n FOREIGN KEY(account_id,project_id) REFERENCES projects(account_id,id) ON DELETE CASCADE\n );\n CREATE TABLE notebook_visits (\n account_id uuid NOT NULL, id uuid NOT NULL, project_id uuid NOT NULL,\n from_token bigint NOT NULL, to_token bigint NOT NULL, baseline boolean NOT NULL,\n at timestamptz NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY(account_id,id),\n FOREIGN KEY(account_id,project_id) REFERENCES projects(account_id,id) ON DELETE CASCADE\n );\n CREATE TABLE notebook_expiries (\n account_id uuid NOT NULL, memory_id uuid NOT NULL, version integer NOT NULL,\n project_id uuid NOT NULL, due_at timestamptz NOT NULL,\n PRIMARY KEY(account_id,memory_id),\n FOREIGN KEY(account_id,memory_id) REFERENCES memories(account_id,id) ON DELETE CASCADE\n );\n CREATE INDEX notebook_expiries_due ON notebook_expiries(account_id,project_id,due_at,memory_id);\n INSERT INTO notebook_expiries(account_id,memory_id,version,project_id,due_at)\n SELECT account_id,id,version,project_id,expires_at FROM memories\n WHERE project_id IS NOT NULL AND expires_at>now() AND deleted_at IS NULL;\n ALTER TABLE jobs DROP CONSTRAINT jobs_kind_check;\n ALTER TABLE jobs ADD CONSTRAINT jobs_kind_check CHECK(kind IN\n ('embedding','decision','organization','brief','relationship_scan','note_relationship','notebook_profile','notebook_relationship','assistance'));\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','assistance') 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 for (const table of [\n \"assistance_requests\",\n \"assistance_reviews\",\n \"notebook_changes\",\n \"notebook_checkpoints\",\n \"notebook_visits\",\n \"notebook_expiries\",\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\n (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,grove_worker\",\n [table],\n );\n }\n await db.raw(`\n CREATE FUNCTION grove_record_note_change() RETURNS trigger LANGUAGE plpgsql\n SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE aid uuid; stamp bigint; action text;\n BEGIN\n aid:=COALESCE(NEW.account_id,OLD.account_id);\n IF TG_OP='INSERT' THEN action:='created';\n ELSIF TG_OP='DELETE' THEN action:='deleted';\n ELSIF OLD.deleted_at IS DISTINCT FROM NEW.deleted_at THEN action:=CASE WHEN NEW.deleted_at IS NULL THEN 'restored' ELSE 'deleted' END;\n ELSIF OLD.project_id IS DISTINCT FROM NEW.project_id THEN action:='moved';\n ELSIF OLD.status IS DISTINCT FROM NEW.status THEN action:=CASE WHEN NEW.status='archived' THEN 'archived' ELSE 'restored' END;\n ELSIF OLD.content IS DISTINCT FROM NEW.content THEN action:='edited';\n ELSIF OLD.expires_at IS DISTINCT FROM NEW.expires_at THEN action:='retention';\n ELSE RETURN NULL; END IF;\n UPDATE accounts SET change_token=change_token+1 WHERE id=aid RETURNING change_token INTO stamp;\n INSERT INTO notebook_changes(account_id,token,memory_id,old_project_id,new_project_id,before_version,after_version,kind)\n VALUES(aid,stamp,COALESCE(NEW.id,OLD.id),OLD.project_id,NEW.project_id,OLD.version,NEW.version,action);\n DELETE FROM notebook_expiries WHERE account_id=aid AND memory_id=COALESCE(NEW.id,OLD.id);\n IF TG_OP<>'DELETE' AND NEW.project_id IS NOT NULL AND NEW.expires_at IS NOT NULL AND NEW.deleted_at IS NULL THEN\n INSERT INTO notebook_expiries(account_id,memory_id,version,project_id,due_at)\n VALUES(aid,NEW.id,NEW.version,NEW.project_id,NEW.expires_at);\n END IF;\n IF action='deleted' THEN\n UPDATE assistance_requests SET result=NULL,state='{}',\n undo=CASE WHEN applied @> jsonb_build_array(jsonb_build_object('id',COALESCE(NEW.id,OLD.id))) THEN NULL ELSE undo END,\n status=CASE WHEN status IN ('applied','undone') AND NOT applied @> jsonb_build_array(jsonb_build_object('id',COALESCE(NEW.id,OLD.id))) THEN status ELSE 'stale' END,\n error='Source removed'\n WHERE account_id=aid AND (applied @> jsonb_build_array(jsonb_build_object('id',COALESCE(NEW.id,OLD.id)))\n OR dependencies @> jsonb_build_array(jsonb_build_object('id',COALESCE(NEW.id,OLD.id)))\n OR scopes @> jsonb_build_array(jsonb_build_object('id',OLD.project_id)));\n END IF;\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_record_note_change() FROM PUBLIC;\n CREATE TRIGGER assistance_note_changed AFTER INSERT OR DELETE OR UPDATE OF content,project_id,status,expires_at,deleted_at\n ON memories FOR EACH ROW EXECUTE FUNCTION grove_record_note_change();\n CREATE FUNCTION grove_catalog_changed() RETURNS trigger LANGUAGE plpgsql\n SET search_path=pg_catalog,public,pg_temp AS $$\n BEGIN\n UPDATE accounts SET notebook_catalog_version=notebook_catalog_version+1 WHERE id=COALESCE(NEW.account_id,OLD.account_id);\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_catalog_changed() FROM PUBLIC;\n CREATE TRIGGER assistance_catalog_changed AFTER INSERT OR DELETE OR UPDATE OF name,parent_id,deleted_at\n ON projects FOR EACH ROW EXECUTE FUNCTION grove_catalog_changed();\n CREATE FUNCTION grove_assistance_export_changed() RETURNS trigger LANGUAGE plpgsql\n SET search_path=pg_catalog,public,pg_temp AS $$\n BEGIN\n IF TG_TABLE_NAME='assistance_requests' THEN\n IF COALESCE(jsonb_array_length(NEW.applied),0)=0 AND COALESCE(jsonb_array_length(OLD.applied),0)=0 THEN RETURN NULL; END IF;\n END IF;\n UPDATE accounts SET export_version=export_version+1 WHERE id=COALESCE(NEW.account_id,OLD.account_id);\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_assistance_export_changed() FROM PUBLIC;\n `);\n for (const table of [\n \"assistance_requests\",\n \"assistance_reviews\",\n \"notebook_checkpoints\",\n \"notebook_visits\",\n ])\n await db.raw(\n \"CREATE TRIGGER assistance_export_changed AFTER INSERT OR UPDATE OR DELETE ON ?? FOR EACH ROW EXECUTE FUNCTION grove_assistance_export_changed()\",\n [table],\n );\n await db.raw(`\n ALTER TABLE memory_briefs ADD COLUMN notebook_version integer,\n ADD COLUMN coverage jsonb, ADD COLUMN expires_at timestamptz;\n CREATE TABLE notebook_summary_nodes (\n account_id uuid NOT NULL, project_id uuid NOT NULL, profile text NOT NULL,\n path text NOT NULL, fingerprint text NOT NULL, content jsonb NOT NULL,\n evidence jsonb NOT NULL, examined integer NOT NULL, expires_at timestamptz,\n PRIMARY KEY(account_id,project_id,profile,path),\n FOREIGN KEY(account_id,project_id) REFERENCES projects(account_id,id) ON DELETE CASCADE\n );\n CREATE TABLE notebook_summary_work (\n account_id uuid NOT NULL, project_id uuid NOT NULL, profile text NOT NULL,\n content_version integer NOT NULL, stack jsonb NOT NULL, expires_at timestamptz,\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 of [\"notebook_summary_nodes\", \"notebook_summary_work\"]) {\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\n (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 `CREATE POLICY visible_parent ON ?? AS RESTRICTIVE USING\n (EXISTS(SELECT 1 FROM projects p WHERE p.account_id=??.account_id AND p.id=??.project_id AND p.deleted_at IS NULL))`,\n [table, table, 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_summary_changed() RETURNS trigger LANGUAGE plpgsql\n SET search_path=pg_catalog,public,pg_temp AS $$\n DECLARE old_project uuid; new_project uuid; bits text;\n BEGIN\n IF TG_OP<>'INSERT' THEN old_project:=OLD.project_id; END IF;\n IF TG_OP<>'DELETE' THEN new_project:=NEW.project_id; END IF;\n bits:=(('x'||replace(COALESCE(NEW.id,OLD.id)::text,'-',''))::bit(128))::text;\n -- Invalidate the changed leaf and its ancestors, retaining independent subtrees.\n DELETE FROM notebook_summary_nodes WHERE account_id=COALESCE(NEW.account_id,OLD.account_id)\n AND project_id IN(old_project,new_project)\n AND path IN(SELECT left(bits,n) FROM generate_series(0,128) AS n);\n INSERT INTO jobs(account_id,kind,target,profile,scope,due_at)\n SELECT account_id,'brief',target,profile,scope,now()+interval '5 seconds'\n FROM memory_briefs WHERE account_id=COALESCE(NEW.account_id,OLD.account_id)\n AND scope->>'taskId' IS NULL\n AND (scope->>'projectId')::uuid IN (old_project,new_project)\n ON CONFLICT(account_id,kind,target,profile) DO UPDATE SET attempts=0,failed_at=NULL,\n error_code=NULL,lease_id=NULL,lease_until=NULL,due_at=EXCLUDED.due_at;\n IF TG_OP='DELETE' OR (TG_OP='UPDATE' AND NEW.deleted_at IS NOT NULL) THEN\n DELETE FROM notebook_summary_nodes WHERE account_id=OLD.account_id\n AND project_id IN(old_project,new_project);\n DELETE FROM memory_briefs WHERE account_id=OLD.account_id\n AND (scope->>'projectId')::uuid IN(old_project,new_project);\n END IF;\n RETURN NULL;\n END $$;\n REVOKE ALL ON FUNCTION grove_summary_changed() FROM PUBLIC;\n CREATE TRIGGER summary_changed AFTER INSERT OR DELETE OR UPDATE OF content,version,project_id,status,expires_at,deleted_at\n ON memories FOR EACH ROW EXECUTE FUNCTION grove_summary_changed();\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\";\nimport { aiPreferences } from \"./preferences-migration.ts\";\nimport { queueProcessing } from \"./queue-migration.ts\";\nimport { notebookAssistance } from \"./assistance-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 aiPreferences,\n queueProcessing,\n notebookAssistance,\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 { AsyncLocalStorage } from \"node:async_hooks\";\n\nconst signals = new AsyncLocalStorage<AbortSignal | undefined>();\nexport const databaseSignal = () => signals.getStore();\nexport const withDatabaseSignal = <T>(\n signal: AbortSignal | undefined,\n run: () => T,\n): T => signals.run(signal, run);\n", "import { createDatabase, closeDatabase } from \"@lib/database\";\n\nconst url = process.env.MIGRATION_DATABASE_URL;\nif (!url)\n throw new Error(\n \"MIGRATION_DATABASE_URL is required; runtime credentials cannot run migrations\",\n );\nconst db = createDatabase(url, { ssl: process.env.DATABASE_SSL === \"require\" });\ntry {\n const [, applied] = await db.migrate.latest();\n console.log(JSON.stringify({ applied }));\n} finally {\n await closeDatabase(db);\n}\n"],
5
+ "mappings": ";;;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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAoBZ;AAAA,EACH;AAAA,EACA,MAAM,OAAO;AACX,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;AAEO,IAAM,gBAAgB;AAAA,EAC3B,MAAM;AAAA,EACN,MAAM,GAAGA,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,KAsBZ;AAAA,EACH;AAAA,EACA,MAAM,OAAO;AACX,UAAM,IAAI,MAAM,yBAAyB;AAAA,EAC3C;AACF;;;AC5DO,IAAM,iBAAiB;AAAA;AAAA,EAE5B,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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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