@opengeni/db 0.26.0 → 0.27.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.
@@ -204,6 +204,7 @@ var FORCE_RLS_TABLES = [
204
204
  "workspace_inference_controls",
205
205
  "workspace_instruction_policy_activation_events",
206
206
  "workspace_instruction_policy_heads",
207
+ "workspace_instruction_policy_onboarding_proposals",
207
208
  "workspace_instruction_policy_revisions",
208
209
  "workspace_instruction_policy_snapshots",
209
210
  "workspace_model_policies",
@@ -356,6 +357,7 @@ var RUNTIME_READ_INSERT_TABLES = [
356
357
  "workspace_artifact_events",
357
358
  "workspace_artifact_versions",
358
359
  "workspace_instruction_policy_activation_events",
360
+ "workspace_instruction_policy_onboarding_proposals",
359
361
  "workspace_instruction_policy_revisions"
360
362
  ];
361
363
  var PROTECTED_NO_DIRECT_DML_TABLES = [
@@ -1198,4 +1200,4 @@ export {
1198
1200
  runtimeDatabaseReadyCheck,
1199
1201
  provisionRoles
1200
1202
  };
1201
- //# sourceMappingURL=chunk-KW6U54V2.js.map
1203
+ //# sourceMappingURL=chunk-IHPCI4GV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/provision-roles.ts","../src/runtime-posture.ts","../src/role-relationships.ts"],"sourcesContent":["import postgres from \"postgres\";\nimport type { RlsStrategy } from \"./index\";\nimport {\n RUNTIME_FULL_DML_TABLES,\n RUNTIME_READ_INSERT_TABLES,\n RUNTIME_READ_ONLY_TABLES,\n} from \"./runtime-posture\";\nimport {\n classifyRoleRelationships,\n roleRelationshipsCatalogQuery,\n type RoleRelationshipCatalogRow,\n} from \"./role-relationships\";\n\nexport type ProvisionResult = {\n appRole: string | null;\n hostExportRole: string | null;\n temporalRole: string | null;\n temporalDatabases: string[];\n schema: string;\n rlsStrategy: RlsStrategy;\n};\n\nexport type ProvisionRolesOptions = {\n /**\n * The schema OpenGeni's tables live in. The app-role GRANTs target this\n * schema + `opengeni_private`. Defaults to `public` (standalone).\n */\n targetSchema?: string;\n /**\n * RLS posture (Step I). `\"force\"` (default) provisions the non-owner\n * `opengeni_app` login role and GRANTs it table DML in the target schema —\n * the role OpenGeni connects as under FORCE-RLS. `\"scoped\"` SKIPS the app-role\n * provisioning entirely: the embedded host runs OpenGeni's queries over a role\n * IT owns/manages (typically the schema owner), so OpenGeni neither creates\n * nor grants the `opengeni_app` role. Temporal-role provisioning is unaffected\n * by strategy.\n */\n rlsStrategy?: RlsStrategy;\n appRole?: string;\n appPassword?: string;\n /**\n * Optional cross-workspace projection role. It receives schema USAGE and\n * EXECUTE only on the host-export API; it receives no table privileges.\n * Provision it after the first migration run so the schema exists. The\n * provisioner also registers same-owner default privileges for future\n * host-export functions; shipped migrations preserve existing exporter ACLs\n * when a migration-only upgrade adds a function.\n */\n hostExportRole?: string;\n hostExportPassword?: string;\n temporalRole?: string;\n temporalPassword?: string;\n temporalDatabases?: string[];\n};\n\n/**\n * SDK entry point (Step I): provision the OpenGeni database roles + grants over\n * a host-supplied admin connection. This is the named, parameterized form of the\n * historical env-driven `provision-roles` script (which still works as a CLI via\n * the `import.meta.main` block at the bottom — it just reads env into these\n * options).\n *\n * STANDALONE (default): `provisionRoles(adminConnection)` with no options →\n * `targetSchema: \"public\"`, `rlsStrategy: \"force\"`, reads `opengeni_app` creds\n * from env. Byte-for-byte the historical script behavior.\n *\n * EMBEDDED: `provisionRoles(adminConnection, { targetSchema, rlsStrategy })` lets\n * a host provision the app role over a dedicated schema (force) OR skip the\n * app role entirely and own the connection role itself (scoped).\n */\nexport async function provisionRoles(\n adminConnection: string,\n options: ProvisionRolesOptions = {},\n): Promise<ProvisionResult> {\n const schema = validateIdentifier(\"targetSchema\", options.targetSchema ?? \"public\");\n const rlsStrategy: RlsStrategy = options.rlsStrategy ?? \"force\";\n\n const appRole = validateIdentifier(\n \"appRole\",\n options.appRole ?? (process.env.OPENGENI_APP_DATABASE_USER?.trim() || \"opengeni_app\"),\n );\n const appPassword = options.appPassword ?? process.env.OPENGENI_APP_DATABASE_PASSWORD;\n const hostExportRole = validateIdentifier(\n \"hostExportRole\",\n options.hostExportRole ??\n (process.env.OPENGENI_HOST_EXPORT_DATABASE_USER?.trim() || \"opengeni_host_exporter\"),\n );\n const hostExportPassword =\n options.hostExportPassword ?? process.env.OPENGENI_HOST_EXPORT_DATABASE_PASSWORD;\n const temporalRole = validateIdentifier(\n \"temporalRole\",\n options.temporalRole ??\n (process.env.OPENGENI_TEMPORAL_DATABASE_USER?.trim() || \"opengeni_temporal\"),\n );\n const temporalPassword =\n options.temporalPassword ?? process.env.OPENGENI_TEMPORAL_DATABASE_PASSWORD;\n const temporalDatabases = (\n options.temporalDatabases ??\n commaSeparated(process.env.OPENGENI_TEMPORAL_DATABASES ?? \"temporal,temporal_visibility\")\n ).map((name) => validateIdentifier(\"temporalDatabases\", name));\n\n const sql = postgres(adminConnection, { max: 1 });\n try {\n // FORCE strategy provisions the non-owner app role OpenGeni connects as.\n // SCOPED strategy: the host owns the connection role; OpenGeni provisions no\n // app role (skipped here), only the optional Temporal role.\n let provisionedAppRole: string | null = null;\n if (rlsStrategy === \"force\") {\n if (!appPassword) {\n throw new Error(\n \"OPENGENI_APP_DATABASE_PASSWORD (or appPassword) is required for rlsStrategy 'force'\",\n );\n }\n // Ownership and privilege-bearing role-graph edges cannot be safely\n // guessed away. Refuse to mutate an existing role until an operator has\n // explicitly transferred objects/removed those memberships; role\n // attributes and direct grants, however, are deterministic and are\n // converged below on every run. PostgreSQL 16+'s exact non-runtime-bearing\n // creator-management edge is classified separately.\n await assertAppRoleSafeToNormalize(sql, appRole);\n await ensureRestrictedAppLoginRole(sql, appRole, appPassword);\n provisionedAppRole = appRole;\n }\n\n if (temporalPassword) {\n await ensureLoginRole(sql, temporalRole, temporalPassword);\n for (const database of temporalDatabases) {\n await ensureDatabase(sql, database, temporalRole);\n await grantTemporalRoleInDatabase(adminConnection, database, temporalRole);\n }\n }\n\n if (hostExportPassword) {\n await ensureLoginRole(sql, hostExportRole, hostExportPassword);\n await grantHostExportRoleIfSchemaExists(sql, hostExportRole);\n }\n\n if (rlsStrategy === \"force\") {\n await grantAppRoleIfSchemaExists(sql, appRole, schema);\n }\n\n return {\n appRole: provisionedAppRole,\n hostExportRole: hostExportPassword ? hostExportRole : null,\n temporalRole: temporalPassword ? temporalRole : null,\n temporalDatabases: temporalPassword ? temporalDatabases : [],\n schema,\n rlsStrategy,\n };\n } finally {\n await sql.end();\n }\n}\n\n/**\n * The exporter is intentionally separate from `opengeni_app`: its functions\n * project every workspace into a host-owned sink and therefore cannot be made\n * available to the tenant-scoped application role.\n */\nasync function grantHostExportRoleIfSchemaExists(sql: postgres.Sql, role: string): Promise<void> {\n await sql.unsafe(`\nDO $$\nBEGIN\n IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_host_export') THEN\n EXECUTE format('GRANT USAGE ON SCHEMA opengeni_host_export TO %I', ${literal(role)});\n EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_host_export TO %I', ${literal(role)});\n EXECUTE format('ALTER DEFAULT PRIVILEGES IN SCHEMA opengeni_host_export GRANT EXECUTE ON FUNCTIONS TO %I', ${literal(role)});\n END IF;\nEND $$;\n`);\n}\n\nasync function ensureLoginRole(sql: postgres.Sql, role: string, password: string): Promise<void> {\n await sql.unsafe(`\nDO $$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN\n EXECUTE format('CREATE ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});\n ELSE\n EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', ${literal(role)}, ${literal(password)});\n END IF;\nEND $$;\n`);\n}\n\nasync function ensureRestrictedAppLoginRole(\n sql: postgres.Sql,\n role: string,\n password: string,\n): Promise<void> {\n await sql.unsafe(`\nDO $$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = ${literal(role)}) THEN\n EXECUTE format(\n 'CREATE ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',\n ${literal(role)},\n ${literal(password)}\n );\n ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = current_user AND rolsuper) THEN\n EXECUTE format(\n 'ALTER ROLE %I WITH LOGIN NOSUPERUSER NOBYPASSRLS NOCREATEROLE NOCREATEDB NOREPLICATION NOINHERIT PASSWORD %L',\n ${literal(role)},\n ${literal(password)}\n );\n ELSE\n -- PostgreSQL requires elevated attributes merely to name SUPERUSER,\n -- BYPASSRLS, REPLICATION, or CREATEDB in ALTER ROLE, even when setting them\n -- false. The preflight has already proved those protected attributes are\n -- false, so a managed CREATEROLE administrator converges only the\n -- attributes it may change.\n EXECUTE format(\n 'ALTER ROLE %I WITH LOGIN NOCREATEROLE NOINHERIT PASSWORD %L',\n ${literal(role)},\n ${literal(password)}\n );\n END IF;\nEND $$;\n`);\n}\n\n/**\n * Fail rather than silently revoking role relationships or transferring owned\n * objects. Those operations have effects outside OpenGeni's runtime grant\n * contract and require an explicit, audited operator decision.\n */\nasync function assertAppRoleSafeToNormalize(sql: postgres.Sql, role: string): Promise<void> {\n const exists = await sql<{ exists: boolean }[]>`\n select exists(select 1 from pg_roles where rolname = ${role}) as exists\n `;\n if (!exists[0]?.exists) {\n return;\n }\n\n const [roleAttributes] = await sql<\n {\n administrator_superuser: boolean;\n app_superuser: boolean;\n app_bypass_rls: boolean;\n app_create_database: boolean;\n app_replication: boolean;\n }[]\n >`\n select\n administrator.rolsuper as administrator_superuser,\n app.rolsuper as app_superuser,\n app.rolbypassrls as app_bypass_rls,\n app.rolcreatedb as app_create_database,\n app.rolreplication as app_replication\n from pg_roles app\n join pg_roles administrator on administrator.rolname = current_user\n where app.rolname = ${role}\n `;\n if (roleAttributes && !roleAttributes.administrator_superuser) {\n const protectedAttributes = [\n roleAttributes.app_superuser ? \"SUPERUSER\" : null,\n roleAttributes.app_bypass_rls ? \"BYPASSRLS\" : null,\n roleAttributes.app_create_database ? \"CREATEDB\" : null,\n roleAttributes.app_replication ? \"REPLICATION\" : null,\n ].filter((attribute): attribute is string => attribute !== null);\n if (protectedAttributes.length > 0) {\n throw new Error(\n `Refusing to normalize app role ${role}: a non-superuser administrator cannot clear protected attributes (${protectedAttributes.join(\", \")})`,\n );\n }\n }\n\n const relationshipRows = await sql.unsafe<RoleRelationshipCatalogRow[]>(\n roleRelationshipsCatalogQuery(\"$1\"),\n [role],\n );\n const { unsafeRelationships } = classifyRoleRelationships(relationshipRows);\n if (unsafeRelationships.length > 0) {\n throw new Error(\n `Refusing to normalize app role ${role}: remove privilege-bearing role relationships first (${unsafeRelationships.join(\", \")})`,\n );\n }\n\n const ownedObjects = await sql<{ object_name: string }[]>`\n select ('database:' || d.datname)::text as object_name\n from pg_database d\n join pg_roles owner on owner.oid = d.datdba\n where owner.rolname = ${role}\n union all\n select ('schema:' || n.nspname)::text as object_name\n from pg_namespace n\n join pg_roles owner on owner.oid = n.nspowner\n where owner.rolname = ${role}\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n union all\n select ('relation:' || n.nspname || '.' || c.relname)::text as object_name\n from pg_class c\n join pg_namespace n on n.oid = c.relnamespace\n join pg_roles owner on owner.oid = c.relowner\n where owner.rolname = ${role}\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n union all\n select (\n 'routine:' || n.nspname || '.' || p.proname || '(' ||\n pg_get_function_identity_arguments(p.oid) || ')'\n )::text as object_name\n from pg_proc p\n join pg_namespace n on n.oid = p.pronamespace\n join pg_roles owner on owner.oid = p.proowner\n where owner.rolname = ${role}\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n order by object_name\n `;\n if (ownedObjects.length > 0) {\n throw new Error(\n `Refusing to normalize app role ${role}: transfer owned objects first (${ownedObjects\n .map((row) => row.object_name)\n .join(\", \")})`,\n );\n }\n}\n\nasync function ensureDatabase(sql: postgres.Sql, database: string, owner: string): Promise<void> {\n const existing = await sql<{ exists: boolean }[]>`\n select exists(select 1 from pg_database where datname = ${database}) as exists\n `;\n if (!existing[0]?.exists) {\n await sql.unsafe(`CREATE DATABASE ${identifier(database)} OWNER ${identifier(owner)}`);\n }\n await sql.unsafe(\n `GRANT ALL PRIVILEGES ON DATABASE ${identifier(database)} TO ${identifier(owner)}`,\n );\n}\n\nasync function grantTemporalRoleInDatabase(\n adminConnection: string,\n database: string,\n role: string,\n): Promise<void> {\n const databaseUrl = databaseUrlFor(adminConnection, database);\n const databaseSql = postgres(databaseUrl, { max: 1 });\n try {\n await databaseSql.unsafe(`GRANT USAGE, CREATE ON SCHEMA public TO ${identifier(role)}`);\n } finally {\n await databaseSql.end();\n }\n}\n\n/**\n * Grant the app role table DML in the OpenGeni data schema + EXECUTE on the\n * `opengeni_private` helper functions. Schema-parameterized (Step I): standalone\n * passes `public`; embedded passes the dedicated schema. The grants are guarded\n * on schema existence so provisioning before migrate is a safe no-op.\n */\nasync function grantAppRoleIfSchemaExists(\n sql: postgres.Sql,\n role: string,\n schema: string,\n): Promise<void> {\n const runtimeFullDmlTables = `ARRAY[${RUNTIME_FULL_DML_TABLES.map(literal).join(\", \")}]`;\n const runtimeReadOnlyTables = `ARRAY[${RUNTIME_READ_ONLY_TABLES.map(literal).join(\", \")}]`;\n const runtimeReadInsertTables = `ARRAY[${RUNTIME_READ_INSERT_TABLES.map(literal).join(\", \")}]`;\n await sql.unsafe(`\nDO $$\nDECLARE\n owner_role text := current_user;\n runtime_table text;\nBEGIN\n EXECUTE format('REVOKE CREATE ON DATABASE %I FROM %I', current_database(), ${literal(role)});\n IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = ${literal(schema)}) THEN\n EXECUTE format('GRANT USAGE ON SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});\n EXECUTE format('REVOKE CREATE ON SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});\n EXECUTE format('REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA %I FROM %I', ${literal(schema)}, ${literal(role)});\n FOREACH runtime_table IN ARRAY ${runtimeFullDmlTables} LOOP\n IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE %I.%I TO %I',\n ${literal(schema)},\n runtime_table,\n ${literal(role)}\n );\n END IF;\n END LOOP;\n FOREACH runtime_table IN ARRAY ${runtimeReadOnlyTables} LOOP\n IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT SELECT ON TABLE %I.%I TO %I',\n ${literal(schema)},\n runtime_table,\n ${literal(role)}\n );\n END IF;\n END LOOP;\n FOREACH runtime_table IN ARRAY ${runtimeReadInsertTables} LOOP\n IF to_regclass(format('%I.%I', ${literal(schema)}, runtime_table)) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT SELECT, INSERT ON TABLE %I.%I TO %I',\n ${literal(schema)},\n runtime_table,\n ${literal(role)}\n );\n END IF;\n END LOOP;\n -- Migration 0110 creates this target-schema-local SECURITY DEFINER\n -- capability before opengeni_app may exist. Re-converge its exact EXECUTE\n -- grant here so the supported migrate-then-provision order is equivalent to\n -- provisioning the role before that migration.\n IF to_regprocedure(\n format('%I.lock_nested_agent_depth_configuration()', ${literal(schema)})\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.lock_nested_agent_depth_configuration() TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.preference_registry_apply_lifecycle(text,uuid,integer,uuid,uuid,text,uuid,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.preference_registry_apply_lifecycle(text, uuid, integer, uuid, uuid, text, uuid, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format('%I.preference_registry_lock_heads(uuid[])', ${literal(schema)})\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.preference_registry_lock_heads(uuid[]) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.knowledge_memory_apply_operation(jsonb,text,text,text,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_apply_operation(jsonb, text, text, text, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.knowledge_memory_revert_operation(uuid,uuid,text,text,text,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.knowledge_memory_revert_operation(uuid, uuid, text, text, text, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.preference_registry_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.preference_registry_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.workspace_instruction_policy_get_or_create_snapshot(uuid,uuid,uuid,uuid,uuid,integer)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.workspace_instruction_policy_get_or_create_snapshot(uuid, uuid, uuid, uuid, uuid, integer) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_apply_lifecycle(uuid,text,uuid,text,bigint,text,text,text,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_apply_lifecycle(uuid, text, uuid, text, bigint, text, text, text, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_advance_source_acl(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_source_acl(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_complete_sync(uuid,uuid,text,text,timestamptz,jsonb,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_complete_sync(uuid, uuid, text, text, timestamptz, jsonb, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF to_regprocedure(\n format(\n '%I.scoped_knowledge_advance_object_version(uuid,uuid,bigint,bigint,uuid,text,text,text,text,text,text)',\n ${literal(schema)}\n )\n ) IS NOT NULL THEN\n EXECUTE format(\n 'GRANT EXECUTE ON FUNCTION %I.scoped_knowledge_advance_object_version(uuid, uuid, bigint, bigint, uuid, text, text, text, text, text, text) TO %I',\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n EXECUTE format('GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA %I TO %I', ${literal(schema)}, ${literal(role)});\n EXECUTE format(\n 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I REVOKE ALL PRIVILEGES ON TABLES FROM %I',\n owner_role,\n ${literal(schema)},\n ${literal(role)}\n );\n EXECUTE format(\n 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA %I GRANT USAGE, SELECT ON SEQUENCES TO %I',\n owner_role,\n ${literal(schema)},\n ${literal(role)}\n );\n END IF;\n IF EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'opengeni_private') THEN\n EXECUTE format('GRANT USAGE ON SCHEMA opengeni_private TO %I', ${literal(role)});\n EXECUTE format('REVOKE CREATE ON SCHEMA opengeni_private FROM %I', ${literal(role)});\n EXECUTE format('GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA opengeni_private TO %I', ${literal(role)});\n EXECUTE format(\n 'ALTER DEFAULT PRIVILEGES FOR ROLE %I IN SCHEMA opengeni_private GRANT EXECUTE ON FUNCTIONS TO %I',\n owner_role,\n ${literal(role)}\n );\n END IF;\nEND $$;\n`);\n}\n\nfunction commaSeparated(value: string): string[] {\n return value\n .split(\",\")\n .map((item) => item.trim())\n .filter(Boolean);\n}\n\nfunction validateIdentifier(name: string, value: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {\n throw new Error(`${name} contains an invalid Postgres identifier: ${value}`);\n }\n return value;\n}\n\nfunction identifier(value: string): string {\n return `\"${value.replace(/\"/g, '\"\"')}\"`;\n}\n\nfunction literal(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\nfunction databaseUrlFor(value: string, database: string): string {\n const url = new URL(value);\n url.pathname = `/${database}`;\n return url.toString();\n}\n\n// CLI form (unchanged behavior): read env into the SDK options and run. This is\n// what `bun src/provision-roles.ts` / the `provision-roles` package script\n// invokes — standalone byte-for-byte the historical script (public schema,\n// force strategy, env-driven creds).\nif (import.meta.main) {\n const adminUrl =\n process.env.OPENGENI_MIGRATIONS_DATABASE_URL ??\n process.env.OPENGENI_DATABASE_ADMIN_URL ??\n process.env.OPENGENI_DATABASE_URL;\n if (!adminUrl) {\n throw new Error(\n \"OPENGENI_MIGRATIONS_DATABASE_URL, OPENGENI_DATABASE_ADMIN_URL, or OPENGENI_DATABASE_URL is required\",\n );\n }\n const result = await provisionRoles(adminUrl, {\n ...(process.env.OPENGENI_DB_SCHEMA?.trim()\n ? { targetSchema: process.env.OPENGENI_DB_SCHEMA.trim() }\n : {}),\n });\n console.log(JSON.stringify(result, null, 2));\n}\n","import { sql } from \"drizzle-orm\";\nimport type { Database, RlsStrategy } from \"./index\";\nimport {\n classifyRoleRelationships,\n roleRelationshipsCatalogQuery,\n type RoleRelationshipCatalogRow,\n} from \"./role-relationships\";\n\n/**\n * The complete standalone tenant-table contract. Adding or removing a\n * FORCE-RLS table is an architectural change: update this list in the same\n * commit as the migration so startup cannot silently accept an unreviewed gap.\n */\nexport const FORCE_RLS_TABLES = [\n \"agent_run_states\",\n \"api_keys\",\n \"audit_events\",\n \"billing_customers\",\n \"capability_catalog_items\",\n \"capability_installations\",\n \"codex_capacity_waiters\",\n \"codex_credential_leases\",\n \"codex_reset_redemption_attempts\",\n \"codex_rotation_settings\",\n \"codex_subscription_credentials\",\n \"composer_drafts\",\n \"connection_disconnect_operations\",\n \"connections\",\n \"connector_action_policies\",\n \"connector_action_requests\",\n \"credit_ledger_entries\",\n \"device_enrollment_requests\",\n \"document_bases\",\n \"document_chunks\",\n \"documents\",\n \"enrollments\",\n \"file_uploads\",\n \"files\",\n \"github_installation_repositories\",\n \"github_installations\",\n \"host_export_config\",\n \"host_export_consumers\",\n \"host_export_cursor_state\",\n \"host_export_dead_letters\",\n \"host_export_outbox\",\n \"import_batches\",\n \"integration_oauth_state_nonces\",\n \"knowledge_change_proposals\",\n \"knowledge_claim_evidence\",\n \"knowledge_claim_relations\",\n \"knowledge_claim_reviews\",\n \"knowledge_claims\",\n \"knowledge_document_versions\",\n \"knowledge_entities\",\n \"knowledge_entity_aliases\",\n \"knowledge_facts\",\n \"knowledge_lifecycle_events\",\n \"knowledge_memories\",\n \"knowledge_memory_lifecycle_events\",\n \"knowledge_memory_relationships\",\n \"knowledge_operation_receipts\",\n \"knowledge_providers\",\n \"knowledge_source_acl_versions\",\n \"knowledge_source_objects\",\n \"knowledge_sources\",\n \"knowledge_sync_runs\",\n \"machine_metrics_latest\",\n \"machine_metrics_series\",\n \"model_call_facts\",\n \"new_session_drafts\",\n \"pack_installations\",\n \"preference_registry_events\",\n \"preference_registry_preferences\",\n \"preference_registry_revisions\",\n \"preference_registry_snapshots\",\n \"rig_changes\",\n \"rig_versions\",\n \"rigs\",\n \"sandbox_checkpoint_artifacts\",\n \"sandbox_lease_holders\",\n \"sandbox_leases\",\n \"sandbox_pty_sessions\",\n \"sandbox_retained_processes\",\n \"sandbox_session_envelopes\",\n \"sandbox_workspace_mutation_admissions\",\n \"sandboxes\",\n \"scheduled_task_runs\",\n \"scheduled_tasks\",\n \"session_attempt_interruptions\",\n \"session_command_receipts\",\n \"session_events\",\n \"session_goals\",\n \"session_history_items\",\n \"session_human_input_requests\",\n \"session_list_snapshots\",\n \"session_mcp_servers\",\n \"session_pending_tool_calls\",\n \"session_pins\",\n \"session_realtime_connections\",\n \"session_realtime_context_projections\",\n \"session_realtime_entries\",\n \"session_realtime_modes\",\n \"session_recordings\",\n \"session_spawn_denials\",\n \"session_stream_acknowledgments\",\n \"session_system_update_outbox\",\n \"session_system_updates\",\n \"session_turn_attempts\",\n \"session_turns\",\n \"session_workflow_wake_outbox\",\n \"sessions\",\n \"slack_bot_delete_operations\",\n \"slack_bot_post_operations\",\n \"slack_bot_user_links\",\n \"slack_interaction_inbox\",\n \"slack_interaction_progress_deliveries\",\n \"slack_interactions\",\n \"social_connections\",\n \"social_posts\",\n \"usage_events\",\n \"workspace_artifact_events\",\n \"workspace_artifact_versions\",\n \"workspace_artifacts\",\n \"workspace_captures\",\n \"workspace_control_events\",\n \"workspace_inference_controls\",\n \"workspace_instruction_policy_activation_events\",\n \"workspace_instruction_policy_heads\",\n \"workspace_instruction_policy_onboarding_proposals\",\n \"workspace_instruction_policy_revisions\",\n \"workspace_instruction_policy_snapshots\",\n \"workspace_model_policies\",\n \"workspace_packs\",\n \"workspace_session_activity_revisions\",\n \"workspace_variable_set_variables\",\n \"workspace_variable_sets\",\n] as const;\n\n/**\n * Deployment-global and authentication tables used by ordinary API/worker\n * traffic. They intentionally do not carry workspace RLS: their access model\n * is implemented by the authentication/access layer or by exact global keys.\n */\nexport const NON_RLS_RUNTIME_TABLES = [\n \"auth_identities\",\n \"auth_rate_limits\",\n \"auth_sessions\",\n \"auth_users\",\n \"auth_verifications\",\n \"integration_oauth_clients\",\n \"managed_accounts\",\n \"nested_agent_depth_configuration\",\n \"stripe_webhook_events\",\n \"workspace_memberships\",\n \"workspaces\",\n] as const;\n\n/**\n * Exact full-CRUD class for the standalone runtime role. This is deliberately\n * explicit instead of being derived from FORCE_RLS_TABLES: adding a protected\n * table must not silently grant it broader DML than its migration intended.\n */\nexport const RUNTIME_FULL_DML_TABLES = [\n \"agent_run_states\",\n \"api_keys\",\n \"audit_events\",\n \"auth_identities\",\n \"auth_rate_limits\",\n \"auth_sessions\",\n \"auth_users\",\n \"auth_verifications\",\n \"billing_customers\",\n \"capability_catalog_items\",\n \"capability_installations\",\n \"codex_capacity_waiters\",\n \"codex_credential_leases\",\n \"codex_reset_redemption_attempts\",\n \"codex_rotation_settings\",\n \"codex_subscription_credentials\",\n \"composer_drafts\",\n \"connection_disconnect_operations\",\n \"connections\",\n \"connector_action_policies\",\n \"connector_action_requests\",\n \"credit_ledger_entries\",\n \"device_enrollment_requests\",\n \"document_bases\",\n \"document_chunks\",\n \"documents\",\n \"enrollments\",\n \"file_uploads\",\n \"files\",\n \"github_installation_repositories\",\n \"github_installations\",\n \"import_batches\",\n \"integration_oauth_clients\",\n \"integration_oauth_state_nonces\",\n \"knowledge_memories\",\n \"machine_metrics_latest\",\n \"machine_metrics_series\",\n \"managed_accounts\",\n \"model_call_facts\",\n \"new_session_drafts\",\n \"pack_installations\",\n \"rig_changes\",\n \"rig_versions\",\n \"rigs\",\n \"sandbox_checkpoint_artifacts\",\n \"sandbox_lease_holders\",\n \"sandbox_leases\",\n \"sandbox_pty_sessions\",\n \"sandbox_retained_processes\",\n \"sandbox_session_envelopes\",\n \"sandbox_workspace_mutation_admissions\",\n \"sandboxes\",\n \"scheduled_task_runs\",\n \"scheduled_tasks\",\n \"session_attempt_interruptions\",\n \"session_command_receipts\",\n \"session_events\",\n \"session_goals\",\n \"session_history_items\",\n \"session_human_input_requests\",\n \"session_list_snapshots\",\n \"session_mcp_servers\",\n \"session_pending_tool_calls\",\n \"session_pins\",\n \"session_realtime_connections\",\n \"session_realtime_context_projections\",\n \"session_realtime_entries\",\n \"session_realtime_modes\",\n \"session_recordings\",\n \"session_stream_acknowledgments\",\n \"session_system_update_outbox\",\n \"session_system_updates\",\n \"session_turn_attempts\",\n \"session_turns\",\n \"session_workflow_wake_outbox\",\n \"sessions\",\n \"slack_bot_delete_operations\",\n \"slack_bot_post_operations\",\n \"slack_bot_user_links\",\n \"slack_interaction_inbox\",\n \"slack_interaction_progress_deliveries\",\n \"slack_interactions\",\n \"social_connections\",\n \"social_posts\",\n \"stripe_webhook_events\",\n \"usage_events\",\n \"workspace_artifacts\",\n \"workspace_captures\",\n \"workspace_control_events\",\n \"workspace_inference_controls\",\n \"workspace_instruction_policy_heads\",\n \"workspace_memberships\",\n \"workspace_model_policies\",\n \"workspace_packs\",\n \"workspace_session_activity_revisions\",\n \"workspace_variable_set_variables\",\n \"workspace_variable_sets\",\n \"workspaces\",\n] as const;\n\n/** Configuration and lifecycle-owned audit rows are read-only at runtime. */\nexport const RUNTIME_READ_ONLY_TABLES = [\n \"knowledge_lifecycle_events\",\n \"knowledge_memory_lifecycle_events\",\n \"knowledge_memory_relationships\",\n \"nested_agent_depth_configuration\",\n \"preference_registry_events\",\n \"preference_registry_snapshots\",\n \"workspace_instruction_policy_snapshots\",\n] as const;\n\n/** Append-only evidence/revision tables are insertable and queryable, never mutable. */\nexport const RUNTIME_READ_INSERT_TABLES = [\n \"knowledge_change_proposals\",\n \"knowledge_claim_evidence\",\n \"knowledge_claim_relations\",\n \"knowledge_claim_reviews\",\n \"knowledge_claims\",\n \"knowledge_document_versions\",\n \"knowledge_entities\",\n \"knowledge_entity_aliases\",\n \"knowledge_facts\",\n \"knowledge_operation_receipts\",\n \"knowledge_providers\",\n \"knowledge_source_acl_versions\",\n \"knowledge_source_objects\",\n \"knowledge_sources\",\n \"knowledge_sync_runs\",\n \"preference_registry_preferences\",\n \"preference_registry_revisions\",\n \"session_spawn_denials\",\n \"workspace_artifact_events\",\n \"workspace_artifact_versions\",\n \"workspace_instruction_policy_activation_events\",\n \"workspace_instruction_policy_onboarding_proposals\",\n \"workspace_instruction_policy_revisions\",\n] as const;\n\n/**\n * These FORCE-RLS tables are owned by security-definer host-export routines.\n * The ordinary application role must have no direct table privileges on them.\n */\nexport const PROTECTED_NO_DIRECT_DML_TABLES = [\n \"host_export_config\",\n \"host_export_consumers\",\n \"host_export_cursor_state\",\n \"host_export_dead_letters\",\n \"host_export_outbox\",\n] as const;\n\nexport type RuntimeTableDmlPrivilege = \"SELECT\" | \"INSERT\" | \"UPDATE\" | \"DELETE\";\nexport type RuntimeTablePrivilegeContract = Readonly<\n Record<string, readonly RuntimeTableDmlPrivilege[]>\n>;\n\nconst FULL_DML_PRIVILEGES = [\"SELECT\", \"INSERT\", \"UPDATE\", \"DELETE\"] as const;\n\n/** Exact per-table DML contract. Absence means no direct table privileges. */\nexport const RUNTIME_TABLE_PRIVILEGES: RuntimeTablePrivilegeContract = Object.freeze({\n ...Object.fromEntries(RUNTIME_FULL_DML_TABLES.map((table) => [table, FULL_DML_PRIVILEGES])),\n ...Object.fromEntries(RUNTIME_READ_ONLY_TABLES.map((table) => [table, [\"SELECT\"] as const])),\n ...Object.fromEntries(\n RUNTIME_READ_INSERT_TABLES.map((table) => [table, [\"SELECT\", \"INSERT\"] as const]),\n ),\n});\n\n/** All tables with any direct runtime DML; retained as the aggregate public contract. */\nexport const RUNTIME_DML_TABLES = Object.freeze(\n Object.keys(RUNTIME_TABLE_PRIVILEGES).sort((a, b) => a.localeCompare(b)),\n);\n\nexport type RuntimeDatabasePostureOptions = {\n rlsStrategy: RlsStrategy;\n expectedRole?: string;\n targetSchema?: string;\n protectedTables?: readonly string[];\n tablePrivileges?: RuntimeTablePrivilegeContract;\n protectedNoDirectDmlTables?: readonly string[];\n};\n\nexport type RuntimeDatabaseIdentity = {\n currentUser: string;\n sessionUser: string;\n databaseOwner: string;\n canConnectDatabase: boolean;\n canCreateInDatabase: boolean;\n rowSecurity: string;\n canLogin: boolean;\n superuser: boolean;\n inherit: boolean;\n createRole: boolean;\n createDatabase: boolean;\n replication: boolean;\n bypassRls: boolean;\n};\n\nexport type RuntimeSchemaPosture = {\n name: string;\n owner: string;\n usage: boolean;\n create: boolean;\n};\n\nexport type RuntimeTablePosture = {\n name: string;\n owner: string;\n rlsEnabled: boolean;\n rlsForced: boolean;\n rlsActive: boolean;\n policyCount: number;\n select: boolean;\n insert: boolean;\n update: boolean;\n delete: boolean;\n truncate: boolean;\n references: boolean;\n trigger: boolean;\n};\n\nexport type RuntimeRoutinePosture = {\n name: string;\n owner: string;\n execute: boolean;\n};\n\nexport type RuntimeDatabasePosture = {\n identity: RuntimeDatabaseIdentity;\n /** Privilege-bearing role relationships; exact PG16+ management-only grants are excluded. */\n memberships: string[];\n schemas: RuntimeSchemaPosture[];\n ownedSchemas: string[];\n ownedRelations: string[];\n tables: RuntimeTablePosture[];\n privateRoutines: RuntimeRoutinePosture[];\n};\n\nexport class RuntimeDatabasePostureError extends Error {\n readonly violations: readonly string[];\n\n constructor(violations: readonly string[]) {\n super(`Runtime database posture check failed: ${violations.join(\"; \")}`);\n this.name = \"RuntimeDatabasePostureError\";\n this.violations = violations;\n }\n}\n\ntype IdentityRow = {\n current_user: string;\n session_user: string;\n database_owner: string;\n can_connect_database: boolean;\n can_create_in_database: boolean;\n row_security: string;\n rolcanlogin: boolean;\n rolsuper: boolean;\n rolinherit: boolean;\n rolcreaterole: boolean;\n rolcreatedb: boolean;\n rolreplication: boolean;\n rolbypassrls: boolean;\n};\n\nfunction resultRows<T>(result: unknown): T[] {\n if (Array.isArray(result)) {\n return result as T[];\n }\n const rows = (result as { rows?: unknown } | null)?.rows;\n if (Array.isArray(rows)) {\n return rows as T[];\n }\n throw new Error(\"Runtime database posture query returned an unsupported result shape\");\n}\n\nfunction sorted(values: Iterable<string>): string[] {\n return [...values].sort((a, b) => a.localeCompare(b));\n}\n\nfunction difference(left: ReadonlySet<string>, right: ReadonlySet<string>): string[] {\n return sorted([...left].filter((value) => !right.has(value)));\n}\n\n/** Inspect only PostgreSQL catalogs and privilege functions; no tenant rows. */\nexport async function inspectRuntimeDatabasePosture(\n db: Database,\n options: RuntimeDatabasePostureOptions,\n): Promise<RuntimeDatabasePosture> {\n const targetSchema = options.targetSchema?.trim() || \"public\";\n\n return await db.transaction(\n async (tx) => {\n const identityRows = resultRows<IdentityRow>(\n await tx.execute(sql`\n select\n current_user::text as current_user,\n session_user::text as session_user,\n pg_get_userbyid(d.datdba)::text as database_owner,\n has_database_privilege(current_user, d.oid, 'CONNECT') as can_connect_database,\n has_database_privilege(current_user, d.oid, 'CREATE') as can_create_in_database,\n current_setting('row_security')::text as row_security,\n r.rolcanlogin,\n r.rolsuper,\n r.rolinherit,\n r.rolcreaterole,\n r.rolcreatedb,\n r.rolreplication,\n r.rolbypassrls\n from pg_roles r\n join pg_database d on d.datname = current_database()\n where r.rolname = current_user\n `),\n );\n const identity = identityRows[0];\n if (!identity) {\n throw new Error(\"Runtime database posture could not resolve the current PostgreSQL role\");\n }\n\n const mappedIdentity: RuntimeDatabaseIdentity = {\n currentUser: identity.current_user,\n sessionUser: identity.session_user,\n databaseOwner: identity.database_owner,\n canConnectDatabase: identity.can_connect_database,\n canCreateInDatabase: identity.can_create_in_database,\n rowSecurity: identity.row_security,\n canLogin: identity.rolcanlogin,\n superuser: identity.rolsuper,\n inherit: identity.rolinherit,\n createRole: identity.rolcreaterole,\n createDatabase: identity.rolcreatedb,\n replication: identity.rolreplication,\n bypassRls: identity.rolbypassrls,\n };\n\n // Scoped/embedded topology deliberately leaves ownership and isolation to\n // the host. Prove the connection identity is coherent, but do not impose\n // the standalone opengeni_app object/grant contract on the host's role.\n if (options.rlsStrategy === \"scoped\") {\n return {\n identity: mappedIdentity,\n memberships: [],\n schemas: [],\n ownedSchemas: [],\n ownedRelations: [],\n tables: [],\n privateRoutines: [],\n };\n }\n\n const relationshipRows = resultRows<RoleRelationshipCatalogRow>(\n await tx.execute(sql.raw(roleRelationshipsCatalogQuery(\"current_user\"))),\n );\n const memberships = classifyRoleRelationships(relationshipRows).unsafeRelationships;\n\n const schemas = resultRows<{\n name: string;\n owner: string;\n usage: boolean;\n create: boolean;\n }>(\n await tx.execute(sql`\n select\n n.nspname::text as name,\n pg_get_userbyid(n.nspowner)::text as owner,\n has_schema_privilege(current_user, n.oid, 'USAGE') as usage,\n has_schema_privilege(current_user, n.oid, 'CREATE') as create\n from pg_namespace n\n where n.nspname in (${targetSchema}, 'opengeni_private')\n order by n.nspname\n `),\n );\n\n const ownedSchemas = resultRows<{ name: string }>(\n await tx.execute(sql`\n select n.nspname::text as name\n from pg_namespace n\n join pg_roles r on r.oid = n.nspowner\n where r.rolname = current_user\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n order by n.nspname\n `),\n ).map((row) => row.name);\n\n const ownedRelations = resultRows<{ name: string }>(\n await tx.execute(sql`\n select (n.nspname || '.' || c.relname)::text as name\n from pg_class c\n join pg_namespace n on n.oid = c.relnamespace\n join pg_roles r on r.oid = c.relowner\n where r.rolname = current_user\n and c.relkind in ('r', 'p', 'S', 'v', 'm', 'f')\n and n.nspname <> 'information_schema'\n and n.nspname !~ '^pg_'\n order by n.nspname, c.relname\n `),\n ).map((row) => row.name);\n\n const tables = resultRows<{\n name: string;\n owner: string;\n rls_enabled: boolean;\n rls_forced: boolean;\n rls_active: boolean;\n policy_count: number;\n can_select: boolean;\n can_insert: boolean;\n can_update: boolean;\n can_delete: boolean;\n can_truncate: boolean;\n can_references: boolean;\n can_trigger: boolean;\n }>(\n await tx.execute(sql`\n select\n c.relname::text as name,\n pg_get_userbyid(c.relowner)::text as owner,\n c.relrowsecurity as rls_enabled,\n c.relforcerowsecurity as rls_forced,\n row_security_active(c.oid) as rls_active,\n (select count(*)::int from pg_policy policy where policy.polrelid = c.oid) as policy_count,\n has_table_privilege(current_user, c.oid, 'SELECT') as can_select,\n has_table_privilege(current_user, c.oid, 'INSERT') as can_insert,\n has_table_privilege(current_user, c.oid, 'UPDATE') as can_update,\n has_table_privilege(current_user, c.oid, 'DELETE') as can_delete,\n has_table_privilege(current_user, c.oid, 'TRUNCATE') as can_truncate,\n has_table_privilege(current_user, c.oid, 'REFERENCES') as can_references,\n has_table_privilege(current_user, c.oid, 'TRIGGER') as can_trigger\n from pg_class c\n join pg_namespace n on n.oid = c.relnamespace\n where n.nspname = ${targetSchema}\n and c.relkind in ('r', 'p')\n order by c.relname\n `),\n ).map((row) => ({\n name: row.name,\n owner: row.owner,\n rlsEnabled: row.rls_enabled,\n rlsForced: row.rls_forced,\n rlsActive: row.rls_active,\n policyCount: row.policy_count,\n select: row.can_select,\n insert: row.can_insert,\n update: row.can_update,\n delete: row.can_delete,\n truncate: row.can_truncate,\n references: row.can_references,\n trigger: row.can_trigger,\n }));\n\n const privateRoutines = resultRows<{\n name: string;\n owner: string;\n can_execute: boolean;\n }>(\n await tx.execute(sql`\n select\n (p.proname || '(' || pg_get_function_identity_arguments(p.oid) || ')')::text as name,\n pg_get_userbyid(p.proowner)::text as owner,\n has_function_privilege(current_user, p.oid, 'EXECUTE') as can_execute\n from pg_proc p\n join pg_namespace n on n.oid = p.pronamespace\n where n.nspname = 'opengeni_private'\n and p.prokind in ('f', 'p')\n order by p.proname, pg_get_function_identity_arguments(p.oid)\n `),\n ).map((row) => ({\n name: row.name,\n owner: row.owner,\n execute: row.can_execute,\n }));\n\n return {\n identity: mappedIdentity,\n memberships,\n schemas,\n ownedSchemas,\n ownedRelations,\n tables,\n privateRoutines,\n };\n },\n { isolationLevel: \"repeatable read\", accessMode: \"read only\" },\n );\n}\n\n/** Pure deterministic evaluator used by startup/readiness and unit tests. */\nexport function evaluateRuntimeDatabasePosture(\n posture: RuntimeDatabasePosture,\n options: RuntimeDatabasePostureOptions,\n): string[] {\n const violations: string[] = [];\n const identity = posture.identity;\n\n if (!identity.currentUser || !identity.sessionUser) {\n violations.push(\"database identity is empty\");\n }\n if (identity.currentUser !== identity.sessionUser) {\n violations.push(\n `current_user ${identity.currentUser} does not match session_user ${identity.sessionUser}`,\n );\n }\n if (!identity.canConnectDatabase) {\n violations.push(\"runtime role lacks CONNECT on the current database\");\n }\n\n if (options.rlsStrategy === \"scoped\") {\n return violations;\n }\n\n const expectedRole = options.expectedRole?.trim() || \"opengeni_app\";\n const targetSchema = options.targetSchema?.trim() || \"public\";\n const protectedTables = new Set(options.protectedTables ?? FORCE_RLS_TABLES);\n const tablePrivileges = options.tablePrivileges ?? RUNTIME_TABLE_PRIVILEGES;\n const directRuntimeTables = new Set(Object.keys(tablePrivileges));\n const protectedNoDirectDmlTables = new Set(\n options.protectedNoDirectDmlTables ??\n (options.protectedTables ? [] : PROTECTED_NO_DIRECT_DML_TABLES),\n );\n\n if (identity.currentUser !== expectedRole || identity.sessionUser !== expectedRole) {\n violations.push(\n `runtime identity must be ${expectedRole} (current_user=${identity.currentUser}, session_user=${identity.sessionUser})`,\n );\n }\n if (!identity.canLogin) violations.push(\"runtime role is not LOGIN\");\n if (identity.superuser) violations.push(\"runtime role is SUPERUSER\");\n if (identity.bypassRls) violations.push(\"runtime role has BYPASSRLS\");\n if (identity.createRole) violations.push(\"runtime role has CREATEROLE\");\n if (identity.createDatabase) violations.push(\"runtime role has CREATEDB\");\n if (identity.replication) violations.push(\"runtime role has REPLICATION\");\n if (identity.inherit) violations.push(\"runtime role must be NOINHERIT\");\n if (identity.databaseOwner === expectedRole) violations.push(\"runtime role owns the database\");\n if (identity.canCreateInDatabase) {\n violations.push(\"runtime role has CREATE on the current database\");\n }\n if (identity.rowSecurity.toLowerCase() !== \"on\") {\n violations.push(`row_security is ${identity.rowSecurity}, expected on`);\n }\n if (posture.memberships.length > 0) {\n violations.push(`runtime role has memberships: ${sorted(posture.memberships).join(\", \")}`);\n }\n if (posture.ownedSchemas.length > 0) {\n violations.push(`runtime role owns schemas: ${sorted(posture.ownedSchemas).join(\", \")}`);\n }\n if (posture.ownedRelations.length > 0) {\n violations.push(`runtime role owns relations: ${sorted(posture.ownedRelations).join(\", \")}`);\n }\n\n for (const schemaName of new Set([targetSchema, \"opengeni_private\"])) {\n const schema = posture.schemas.find((candidate) => candidate.name === schemaName);\n if (!schema) {\n violations.push(`required schema ${schemaName} is missing`);\n continue;\n }\n if (schema.owner === expectedRole) {\n violations.push(`runtime role owns schema ${schemaName}`);\n }\n if (!schema.usage) violations.push(`runtime role lacks USAGE on schema ${schemaName}`);\n if (schema.create) violations.push(`runtime role has CREATE on schema ${schemaName}`);\n }\n\n const tableByName = new Map(posture.tables.map((table) => [table.name, table]));\n const actualRlsTables = new Set(\n posture.tables.filter((table) => table.rlsEnabled).map((table) => table.name),\n );\n const classifiedProtectedTables = new Set([\n ...directRuntimeTables,\n ...protectedNoDirectDmlTables,\n ]);\n const unclassifiedProtectedTables = difference(protectedTables, classifiedProtectedTables);\n if (unclassifiedProtectedTables.length > 0) {\n violations.push(\n `protected tables lack an explicit privilege class: ${unclassifiedProtectedTables.join(\", \")}`,\n );\n }\n const protectedNoDirectDmlOverlap = difference(\n protectedNoDirectDmlTables,\n new Set([...protectedNoDirectDmlTables].filter((table) => !directRuntimeTables.has(table))),\n );\n if (protectedNoDirectDmlOverlap.length > 0) {\n violations.push(\n `protected no-direct-DML tables also declare runtime privileges: ${protectedNoDirectDmlOverlap.join(\", \")}`,\n );\n }\n const nonProtectedNoDirectDmlTables = difference(protectedNoDirectDmlTables, protectedTables);\n if (nonProtectedNoDirectDmlTables.length > 0) {\n violations.push(\n `no-direct-DML tables are absent from the protected contract: ${nonProtectedNoDirectDmlTables.join(\", \")}`,\n );\n }\n const catalogTables = new Set(tableByName.keys());\n const missingRuntimeTables = difference(directRuntimeTables, catalogTables);\n if (missingRuntimeTables.length > 0) {\n violations.push(`runtime privilege tables are missing: ${missingRuntimeTables.join(\", \")}`);\n }\n const missingTables = difference(protectedTables, catalogTables);\n if (missingTables.length > 0) {\n violations.push(`protected tables are missing: ${missingTables.join(\", \")}`);\n }\n const undeclaredRlsTables = difference(actualRlsTables, protectedTables);\n if (undeclaredRlsTables.length > 0) {\n violations.push(\n `RLS tables are absent from the declared contract: ${undeclaredRlsTables.join(\", \")}`,\n );\n }\n\n for (const table of posture.tables) {\n const privileges = [\n [\"SELECT\", table.select],\n [\"INSERT\", table.insert],\n [\"UPDATE\", table.update],\n [\"DELETE\", table.delete],\n [\"TRUNCATE\", table.truncate],\n [\"REFERENCES\", table.references],\n [\"TRIGGER\", table.trigger],\n ] as const;\n const expectedPrivileges = new Set<string>(tablePrivileges[table.name] ?? []);\n if (table.owner === expectedRole) {\n violations.push(`runtime role owns table ${table.name}`);\n }\n const missingPrivileges = privileges\n .filter(([privilege, granted]) => expectedPrivileges.has(privilege) && !granted)\n .map(([privilege]) => privilege);\n if (missingPrivileges.length > 0) {\n violations.push(\n `table ${table.name} lacks required runtime privileges: ${missingPrivileges.join(\", \")}`,\n );\n }\n const excessPrivileges = privileges\n .filter(([privilege, granted]) => !expectedPrivileges.has(privilege) && granted)\n .map(([privilege]) => privilege);\n if (excessPrivileges.length > 0) {\n violations.push(\n `table ${table.name} grants excess runtime privileges: ${excessPrivileges.join(\", \")}`,\n );\n }\n }\n\n for (const tableName of protectedTables) {\n const table = tableByName.get(tableName);\n if (!table) continue;\n if (!table.rlsEnabled) violations.push(`table ${tableName} does not ENABLE RLS`);\n if (!table.rlsForced) violations.push(`table ${tableName} does not FORCE RLS`);\n if (!table.rlsActive) violations.push(`table ${tableName} has inactive RLS for runtime role`);\n if (table.policyCount < 1) violations.push(`table ${tableName} has no RLS policy`);\n }\n\n if (posture.privateRoutines.length === 0) {\n violations.push(\"opengeni_private has no helper routines\");\n }\n for (const routine of posture.privateRoutines) {\n if (routine.owner === expectedRole) {\n violations.push(`runtime role owns private routine ${routine.name}`);\n }\n if (!routine.execute) {\n violations.push(`runtime role lacks EXECUTE on private routine ${routine.name}`);\n }\n }\n\n return violations;\n}\n\nexport async function assertRuntimeDatabasePosture(\n db: Database,\n options: RuntimeDatabasePostureOptions,\n): Promise<RuntimeDatabasePosture> {\n const posture = await inspectRuntimeDatabasePosture(db, options);\n const violations = evaluateRuntimeDatabasePosture(posture, options);\n if (violations.length > 0) {\n throw new RuntimeDatabasePostureError(violations);\n }\n return posture;\n}\n\nexport function runtimeDatabaseReadyCheck(\n db: Database,\n options: RuntimeDatabasePostureOptions,\n): () => Promise<void> {\n return async () => {\n await assertRuntimeDatabasePosture(db, options);\n };\n}\n","export type RoleRelationshipDirection = \"inherits\" | \"member\";\n\nexport type RoleRelationshipCatalogRow = {\n relationship: string;\n direction: RoleRelationshipDirection;\n server_version_num: number;\n admin_option: boolean | null;\n inherit_option: boolean | null;\n set_option: boolean | null;\n member_is_superuser: boolean | null;\n member_can_create_role: boolean | null;\n grantor_role: string | null;\n grantor_is_superuser: boolean | null;\n};\n\nexport type ClassifiedRoleRelationships = {\n relationships: string[];\n managementOnlyRelationships: string[];\n unsafeRelationships: string[];\n};\n\ntype RoleTargetExpression = \"current_user\" | \"$1\";\n\n/**\n * One PostgreSQL 15-compatible catalog query for both provisioning and runtime\n * posture. PostgreSQL 16 added per-membership INHERIT and SET columns; reading\n * the catalog row through to_jsonb keeps this statement parseable on 15 while\n * leaving the missing options null and therefore fail-closed.\n */\nexport function roleRelationshipsCatalogQuery(targetRole: RoleTargetExpression): string {\n return `\nwith recursive target_role(oid, rolname) as (\n select oid, rolname\n from pg_roles\n where rolname = ${targetRole}\n), inherited_roles(oid, rolname) as (\n select parent.oid, parent.rolname\n from pg_auth_members membership\n join target_role target on target.oid = membership.member\n join pg_roles parent on parent.oid = membership.roleid\n union\n select parent.oid, parent.rolname\n from inherited_roles inherited\n join pg_auth_members membership on membership.member = inherited.oid\n join pg_roles parent on parent.oid = membership.roleid\n), relationships as (\n select\n ('inherits:' || inherited.rolname)::text as relationship,\n 'inherits'::text as direction,\n null::boolean as admin_option,\n null::boolean as inherit_option,\n null::boolean as set_option,\n null::boolean as member_is_superuser,\n null::boolean as member_can_create_role,\n null::text as grantor_role,\n null::boolean as grantor_is_superuser\n from inherited_roles inherited\n union all\n select\n ('member:' || member.rolname)::text as relationship,\n 'member'::text as direction,\n membership.admin_option,\n case\n when current_setting('server_version_num')::integer >= 160000\n then (to_jsonb(membership) ->> 'inherit_option')::boolean\n else null::boolean\n end as inherit_option,\n case\n when current_setting('server_version_num')::integer >= 160000\n then (to_jsonb(membership) ->> 'set_option')::boolean\n else null::boolean\n end as set_option,\n member.rolsuper as member_is_superuser,\n member.rolcreaterole as member_can_create_role,\n grantor.rolname::text as grantor_role,\n grantor.rolsuper as grantor_is_superuser\n from pg_auth_members membership\n join target_role target on target.oid = membership.roleid\n join pg_roles member on member.oid = membership.member\n left join pg_roles grantor on grantor.oid = membership.grantor\n)\nselect\n relationship,\n direction,\n current_setting('server_version_num')::integer as server_version_num,\n admin_option,\n inherit_option,\n set_option,\n member_is_superuser,\n member_can_create_role,\n grantor_role,\n grantor_is_superuser\nfrom relationships\norder by relationship, direction, grantor_role nulls first\n`;\n}\n\n/**\n * PostgreSQL 16+ automatically gives a non-superuser CREATEROLE principal an\n * ADMIN-only grant on a role it creates. The exact edge below permits role\n * management but cannot inherit the app role's privileges or SET ROLE into it.\n */\nexport function isManagementOnlyRoleRelationship(row: RoleRelationshipCatalogRow): boolean {\n return (\n row.direction === \"member\" &&\n row.server_version_num >= 160000 &&\n row.admin_option === true &&\n row.inherit_option === false &&\n row.set_option === false &&\n row.member_is_superuser === false &&\n row.member_can_create_role === true &&\n row.grantor_is_superuser === true\n );\n}\n\nfunction sortedUnique(values: Iterable<string>): string[] {\n return [...new Set(values)].sort((a, b) => a.localeCompare(b));\n}\n\n/** Classify exact management-only reverse grants while rejecting every other edge. */\nexport function classifyRoleRelationships(\n rows: readonly RoleRelationshipCatalogRow[],\n): ClassifiedRoleRelationships {\n const managementOnlyRows = rows.filter(isManagementOnlyRoleRelationship);\n const unsafeRows = rows.filter((row) => !isManagementOnlyRoleRelationship(row));\n\n return {\n relationships: sortedUnique(rows.map((row) => row.relationship)),\n managementOnlyRelationships: sortedUnique(managementOnlyRows.map((row) => row.relationship)),\n unsafeRelationships: sortedUnique(unsafeRows.map((row) => row.relationship)),\n };\n}\n"],"mappings":";AAAA,OAAO,cAAc;;;ACArB,SAAS,WAAW;;;AC6Bb,SAAS,8BAA8B,YAA0C;AACtF,SAAO;AAAA;AAAA;AAAA;AAAA,oBAIW,UAAU;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;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;AAAA;AAAA;AA6D9B;AAOO,SAAS,iCAAiC,KAA0C;AACzF,SACE,IAAI,cAAc,YAClB,IAAI,sBAAsB,QAC1B,IAAI,iBAAiB,QACrB,IAAI,mBAAmB,SACvB,IAAI,eAAe,SACnB,IAAI,wBAAwB,SAC5B,IAAI,2BAA2B,QAC/B,IAAI,yBAAyB;AAEjC;AAEA,SAAS,aAAa,QAAoC;AACxD,SAAO,CAAC,GAAG,IAAI,IAAI,MAAM,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC;AAC/D;AAGO,SAAS,0BACd,MAC6B;AAC7B,QAAM,qBAAqB,KAAK,OAAO,gCAAgC;AACvE,QAAM,aAAa,KAAK,OAAO,CAAC,QAA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AA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,IAAM,yBAAyB;AAAA,EACpC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,IAAM,0BAA0B;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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F;AACA,QAAM,SAAS,MAAM,eAAe,UAAU;AAAA,IAC5C,GAAI,QAAQ,IAAI,oBAAoB,KAAK,IACrC,EAAE,cAAc,QAAQ,IAAI,mBAAmB,KAAK,EAAE,IACtD,CAAC;AAAA,EACP,CAAC;AACD,UAAQ,IAAI,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAC7C;","names":["sql"]}
package/dist/index.js CHANGED
@@ -104,6 +104,7 @@ import {
104
104
  workspaceInferenceControls,
105
105
  workspaceInstructionPolicyActivationEvents,
106
106
  workspaceInstructionPolicyHeads,
107
+ workspaceInstructionPolicyOnboardingProposals,
107
108
  workspaceInstructionPolicyRevisions,
108
109
  workspaceInstructionPolicySnapshots,
109
110
  workspaceMemberships,
@@ -113,7 +114,7 @@ import {
113
114
  workspaceVariableSetVariables,
114
115
  workspaceVariableSets,
115
116
  workspaces
116
- } from "./chunk-7WTDI7Y3.js";
117
+ } from "./chunk-EX7CDSGH.js";
117
118
  import {
118
119
  migrate,
119
120
  runMigrations
@@ -133,7 +134,7 @@ import {
133
134
  inspectRuntimeDatabasePosture,
134
135
  provisionRoles,
135
136
  runtimeDatabaseReadyCheck
136
- } from "./chunk-KW6U54V2.js";
137
+ } from "./chunk-IHPCI4GV.js";
137
138
  import "./chunk-PZ5AY32C.js";
138
139
 
139
140
  // src/index.ts
@@ -7531,6 +7532,32 @@ var WorkspaceInstructionPolicyLegacyUnavailableError = class extends Error {
7531
7532
  super("This workspace has no legacy agent instructions to import");
7532
7533
  }
7533
7534
  };
7535
+ var WorkspaceInstructionPolicyOnboardingProposalContentError = class extends Error {
7536
+ constructor(code) {
7537
+ super(
7538
+ code === "WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_EMPTY" ? "An onboarding proposal must contain non-blank instruction-policy content" : `An onboarding proposal must not exceed ${WORKSPACE_INSTRUCTION_POLICY_CONTENT_MAX_CHARS} characters`
7539
+ );
7540
+ this.code = code;
7541
+ }
7542
+ name = "WorkspaceInstructionPolicyOnboardingProposalContentError";
7543
+ };
7544
+ var WorkspaceInstructionPolicyOnboardingProposalStaleError = class extends Error {
7545
+ constructor(currentHead) {
7546
+ super("The onboarding proposal was prepared against a stale active policy baseline");
7547
+ this.currentHead = currentHead;
7548
+ }
7549
+ name = "WorkspaceInstructionPolicyOnboardingProposalStaleError";
7550
+ code = "WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_STALE";
7551
+ };
7552
+ var WorkspaceInstructionPolicyOnboardingProposalConflictError = class extends Error {
7553
+ constructor(existingProposalId, existingDraftRevisionId) {
7554
+ super("This onboarding source version already proposed a draft for the policy target");
7555
+ this.existingProposalId = existingProposalId;
7556
+ this.existingDraftRevisionId = existingDraftRevisionId;
7557
+ }
7558
+ name = "WorkspaceInstructionPolicyOnboardingProposalConflictError";
7559
+ code = "WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_CONFLICT";
7560
+ };
7534
7561
  var WorkspaceInstructionPolicySnapshotAuthorityError = class extends Error {
7535
7562
  name = "WorkspaceInstructionPolicySnapshotAuthorityError";
7536
7563
  };
@@ -7592,6 +7619,22 @@ function activeRevisionRequestFingerprint(input) {
7592
7619
  ["reason", true, input.reason]
7593
7620
  ]);
7594
7621
  }
7622
+ function onboardingProposalRequestFingerprint(input) {
7623
+ return operationRequestFingerprint("create_onboarding_proposal", [
7624
+ ["accountId", true, input.accountId],
7625
+ ["workspaceId", true, input.workspaceId],
7626
+ ["kind", true, input.kind],
7627
+ ["scope", true, input.scope],
7628
+ ["roleKey", true, input.roleKey],
7629
+ ["content", true, input.content],
7630
+ ["sourceId", true, input.sourceId],
7631
+ ["sourceVersion", true, input.sourceVersion],
7632
+ ["confidenceBps", true, input.confidenceBps],
7633
+ ["expectedCurrentRevisionId", true, input.expectedCurrentRevisionId],
7634
+ ["expectedActivationVersion", true, input.expectedActivationVersion],
7635
+ ["createdBySubjectId", true, input.createdBySubjectId]
7636
+ ]);
7637
+ }
7595
7638
  function iso(value) {
7596
7639
  return (value instanceof Date ? value : new Date(value)).toISOString();
7597
7640
  }
@@ -7756,6 +7799,37 @@ function eventFromRow(row) {
7756
7799
  createdAt: iso(row.createdAt)
7757
7800
  };
7758
7801
  }
7802
+ function onboardingProposalFromRow(row, draftRow) {
7803
+ return {
7804
+ id: row.id,
7805
+ operationId: row.operationId,
7806
+ accountId: row.accountId,
7807
+ workspaceId: row.workspaceId,
7808
+ kind: row.kind,
7809
+ scope: row.scope,
7810
+ roleKey: row.roleKey,
7811
+ source: {
7812
+ id: row.sourceId,
7813
+ version: row.sourceVersion,
7814
+ confidenceBps: row.confidenceBps
7815
+ },
7816
+ baseline: row.baselineRevisionId === null ? null : {
7817
+ workspaceId: row.workspaceId,
7818
+ kind: row.kind,
7819
+ scope: row.scope,
7820
+ roleKey: row.roleKey,
7821
+ revisionId: row.baselineRevisionId,
7822
+ revision: row.baselineRevision,
7823
+ contentHash: row.baselineContentHash,
7824
+ activationVersion: row.baselineActivationVersion,
7825
+ activatedAt: iso(row.baselineActivatedAt)
7826
+ },
7827
+ draft: revisionFromRow(draftRow),
7828
+ status: "proposed",
7829
+ createdBySubjectId: row.createdBySubjectId,
7830
+ createdAt: iso(row.createdAt)
7831
+ };
7832
+ }
7759
7833
  function headFromEventRow(row) {
7760
7834
  return {
7761
7835
  workspaceId: row.workspaceId,
@@ -7836,6 +7910,35 @@ async function getEventByOperationInTransaction(db, workspaceId, operationId) {
7836
7910
  ).limit(1);
7837
7911
  return row ?? null;
7838
7912
  }
7913
+ async function getOnboardingProposalByOperationInTransaction(db, workspaceId, operationId) {
7914
+ const [row] = await db.select().from(workspaceInstructionPolicyOnboardingProposals).where(
7915
+ and12(
7916
+ eq12(workspaceInstructionPolicyOnboardingProposals.workspaceId, workspaceId),
7917
+ eq12(workspaceInstructionPolicyOnboardingProposals.operationId, operationId)
7918
+ )
7919
+ ).limit(1);
7920
+ return row ?? null;
7921
+ }
7922
+ async function getOnboardingProposalBySourceVersionInTransaction(db, input) {
7923
+ const [row] = await db.select().from(workspaceInstructionPolicyOnboardingProposals).where(
7924
+ and12(
7925
+ eq12(workspaceInstructionPolicyOnboardingProposals.workspaceId, input.workspaceId),
7926
+ eq12(workspaceInstructionPolicyOnboardingProposals.kind, input.kind),
7927
+ eq12(workspaceInstructionPolicyOnboardingProposals.scope, input.scope),
7928
+ input.roleKey === null ? isNull4(workspaceInstructionPolicyOnboardingProposals.roleKey) : eq12(workspaceInstructionPolicyOnboardingProposals.roleKey, input.roleKey),
7929
+ eq12(workspaceInstructionPolicyOnboardingProposals.sourceId, input.sourceId),
7930
+ eq12(workspaceInstructionPolicyOnboardingProposals.sourceVersion, input.sourceVersion)
7931
+ )
7932
+ ).limit(1);
7933
+ return row ?? null;
7934
+ }
7935
+ async function resolveOnboardingProposalInTransaction(db, row) {
7936
+ const draftRow = await getRevisionInTransaction(db, row.workspaceId, row.draftRevisionId);
7937
+ if (!draftRow) {
7938
+ throw new Error("Workspace instruction-policy onboarding proposal lost its draft revision");
7939
+ }
7940
+ return onboardingProposalFromRow(row, draftRow);
7941
+ }
7839
7942
  async function getHeadInTransaction(db, workspaceId, target) {
7840
7943
  const [row] = await db.select().from(workspaceInstructionPolicyHeads).where(and12(...headTargetConditions(workspaceId, target))).for("update").limit(1);
7841
7944
  return row ?? null;
@@ -7887,8 +7990,18 @@ async function createDraftInTransaction(db, input) {
7887
7990
  provenanceSourceId: input.provenanceSourceId,
7888
7991
  supersedesRevisionId: input.supersedesRevisionId,
7889
7992
  createdBySubjectId: input.createdBySubjectId
7890
- }).returning();
7891
- if (!created) throw new Error("Workspace instruction-policy draft was not created");
7993
+ }).onConflictDoNothing().returning();
7994
+ if (!created) {
7995
+ const concurrent = await getRevisionByOperationInTransaction(
7996
+ db,
7997
+ input.workspaceId,
7998
+ input.operationId
7999
+ );
8000
+ if (!concurrent || concurrent.requestFingerprint !== input.requestFingerprint) {
8001
+ throw new WorkspaceInstructionPolicyOperationReuseError();
8002
+ }
8003
+ return revisionFromRow(concurrent);
8004
+ }
7892
8005
  return revisionFromRow(created);
7893
8006
  }
7894
8007
  async function createWorkspaceInstructionPolicyDraft(db, input) {
@@ -7948,6 +8061,175 @@ async function importLegacyWorkspaceInstructionPolicyDraft(db, input) {
7948
8061
  }
7949
8062
  );
7950
8063
  }
8064
+ async function createWorkspaceInstructionPolicyOnboardingProposal(db, input) {
8065
+ if (input.content.trim().length === 0) {
8066
+ throw new WorkspaceInstructionPolicyOnboardingProposalContentError(
8067
+ "WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_EMPTY"
8068
+ );
8069
+ }
8070
+ if (input.content.length > WORKSPACE_INSTRUCTION_POLICY_CONTENT_MAX_CHARS) {
8071
+ throw new WorkspaceInstructionPolicyOnboardingProposalContentError(
8072
+ "WORKSPACE_INSTRUCTION_POLICY_ONBOARDING_PROPOSAL_OVERSIZED"
8073
+ );
8074
+ }
8075
+ const request = {
8076
+ ...input,
8077
+ operationId: input.operationId ?? randomUUID(),
8078
+ sourceId: input.sourceId.trim(),
8079
+ sourceVersion: input.sourceVersion.trim()
8080
+ };
8081
+ const normalized = {
8082
+ ...request,
8083
+ requestFingerprint: onboardingProposalRequestFingerprint(request)
8084
+ };
8085
+ return await withRlsContext(
8086
+ db,
8087
+ { accountId: input.accountId, workspaceId: input.workspaceId },
8088
+ async (scopedDb) => {
8089
+ await lockWorkspace(scopedDb, input);
8090
+ const existing = await getOnboardingProposalByOperationInTransaction(
8091
+ scopedDb,
8092
+ input.workspaceId,
8093
+ normalized.operationId
8094
+ );
8095
+ if (existing) {
8096
+ if (existing.requestFingerprint !== normalized.requestFingerprint) {
8097
+ throw new WorkspaceInstructionPolicyOperationReuseError();
8098
+ }
8099
+ return await resolveOnboardingProposalInTransaction(scopedDb, existing);
8100
+ }
8101
+ if (await getEventByOperationInTransaction(
8102
+ scopedDb,
8103
+ input.workspaceId,
8104
+ normalized.operationId
8105
+ ) || await getRevisionByOperationInTransaction(
8106
+ scopedDb,
8107
+ input.workspaceId,
8108
+ normalized.operationId
8109
+ )) {
8110
+ throw new WorkspaceInstructionPolicyOperationReuseError();
8111
+ }
8112
+ const target = {
8113
+ kind: normalized.kind,
8114
+ scope: normalized.scope,
8115
+ roleKey: normalized.roleKey
8116
+ };
8117
+ const currentRow = await getHeadInTransaction(scopedDb, input.workspaceId, target);
8118
+ const currentHead = currentRow ? headFromRow(currentRow) : null;
8119
+ if ((currentHead?.revisionId ?? null) !== normalized.expectedCurrentRevisionId || (currentHead?.activationVersion ?? 0) !== normalized.expectedActivationVersion) {
8120
+ throw new WorkspaceInstructionPolicyOnboardingProposalStaleError(currentHead);
8121
+ }
8122
+ const sourceConflict = await getOnboardingProposalBySourceVersionInTransaction(
8123
+ scopedDb,
8124
+ normalized
8125
+ );
8126
+ if (sourceConflict) {
8127
+ throw new WorkspaceInstructionPolicyOnboardingProposalConflictError(
8128
+ sourceConflict.id,
8129
+ sourceConflict.draftRevisionId
8130
+ );
8131
+ }
8132
+ const proposalId = randomUUID();
8133
+ const draft = await createDraftInTransaction(scopedDb, {
8134
+ operationId: normalized.operationId,
8135
+ requestFingerprint: normalized.requestFingerprint,
8136
+ accountId: normalized.accountId,
8137
+ workspaceId: normalized.workspaceId,
8138
+ kind: normalized.kind,
8139
+ scope: normalized.scope,
8140
+ roleKey: normalized.roleKey,
8141
+ content: normalized.content,
8142
+ provenanceSource: "onboarding",
8143
+ provenanceSourceId: proposalId,
8144
+ supersedesRevisionId: currentHead?.revisionId ?? null,
8145
+ createdBySubjectId: normalized.createdBySubjectId
8146
+ });
8147
+ const createdAt = /* @__PURE__ */ new Date();
8148
+ const [created] = await scopedDb.insert(workspaceInstructionPolicyOnboardingProposals).values({
8149
+ id: proposalId,
8150
+ operationId: normalized.operationId,
8151
+ requestFingerprint: normalized.requestFingerprint,
8152
+ accountId: normalized.accountId,
8153
+ workspaceId: normalized.workspaceId,
8154
+ kind: normalized.kind,
8155
+ scope: normalized.scope,
8156
+ roleKey: normalized.roleKey,
8157
+ sourceId: normalized.sourceId,
8158
+ sourceVersion: normalized.sourceVersion,
8159
+ confidenceBps: normalized.confidenceBps,
8160
+ baselineRevisionId: currentHead?.revisionId ?? null,
8161
+ baselineRevision: currentHead?.revision ?? null,
8162
+ baselineContentHash: currentHead?.contentHash ?? null,
8163
+ baselineActivationVersion: currentHead?.activationVersion ?? 0,
8164
+ baselineActivatedAt: currentHead ? new Date(currentHead.activatedAt) : null,
8165
+ draftRevisionId: draft.id,
8166
+ draftRevision: draft.revision,
8167
+ draftContentHash: draft.contentHash,
8168
+ status: "proposed",
8169
+ createdBySubjectId: normalized.createdBySubjectId,
8170
+ createdAt
8171
+ }).onConflictDoNothing().returning();
8172
+ if (created) {
8173
+ const draftRow = await getRevisionInTransaction(scopedDb, input.workspaceId, draft.id);
8174
+ if (!draftRow) throw new Error("Onboarding proposal draft was not recorded");
8175
+ return onboardingProposalFromRow(created, draftRow);
8176
+ }
8177
+ const concurrentOperation = await getOnboardingProposalByOperationInTransaction(
8178
+ scopedDb,
8179
+ input.workspaceId,
8180
+ normalized.operationId
8181
+ );
8182
+ if (concurrentOperation) {
8183
+ if (concurrentOperation.requestFingerprint !== normalized.requestFingerprint) {
8184
+ throw new WorkspaceInstructionPolicyOperationReuseError();
8185
+ }
8186
+ return await resolveOnboardingProposalInTransaction(scopedDb, concurrentOperation);
8187
+ }
8188
+ const concurrentSource = await getOnboardingProposalBySourceVersionInTransaction(
8189
+ scopedDb,
8190
+ normalized
8191
+ );
8192
+ if (concurrentSource) {
8193
+ throw new WorkspaceInstructionPolicyOnboardingProposalConflictError(
8194
+ concurrentSource.id,
8195
+ concurrentSource.draftRevisionId
8196
+ );
8197
+ }
8198
+ throw new Error("Workspace instruction-policy onboarding proposal was not created");
8199
+ }
8200
+ );
8201
+ }
8202
+ async function listWorkspaceInstructionPolicyOnboardingProposals(db, workspaceId, query) {
8203
+ return await withWorkspaceRls(db, workspaceId, async (scopedDb) => {
8204
+ const rows = await scopedDb.select().from(workspaceInstructionPolicyOnboardingProposals).where(eq12(workspaceInstructionPolicyOnboardingProposals.workspaceId, workspaceId)).orderBy(
8205
+ desc4(workspaceInstructionPolicyOnboardingProposals.createdAt),
8206
+ desc4(workspaceInstructionPolicyOnboardingProposals.id)
8207
+ ).limit(query.limit + 1);
8208
+ const truncated = rows.length > query.limit;
8209
+ const page = rows.slice(0, query.limit);
8210
+ if (page.length === 0) return { proposals: [], truncated };
8211
+ const revisions = await scopedDb.select().from(workspaceInstructionPolicyRevisions).where(
8212
+ and12(
8213
+ eq12(workspaceInstructionPolicyRevisions.workspaceId, workspaceId),
8214
+ inArray7(
8215
+ workspaceInstructionPolicyRevisions.id,
8216
+ page.map((proposal) => proposal.draftRevisionId)
8217
+ )
8218
+ )
8219
+ );
8220
+ const revisionsById = new Map(revisions.map((revision) => [revision.id, revision]));
8221
+ return {
8222
+ proposals: page.map((proposal) => {
8223
+ const draft = revisionsById.get(proposal.draftRevisionId);
8224
+ if (!draft) {
8225
+ throw new Error("Workspace instruction-policy onboarding proposal lost its draft");
8226
+ }
8227
+ return onboardingProposalFromRow(proposal, draft);
8228
+ }),
8229
+ truncated
8230
+ };
8231
+ });
8232
+ }
7951
8233
  function listFilterConditions(workspaceId, query) {
7952
8234
  const conditions = [
7953
8235
  eq12(workspaceInstructionPolicyRevisions.workspaceId, workspaceId)
@@ -40676,6 +40958,9 @@ export {
40676
40958
  WorkspaceInstructionPolicyInvalidOperationError,
40677
40959
  WorkspaceInstructionPolicyLegacyUnavailableError,
40678
40960
  WorkspaceInstructionPolicyNotFoundError,
40961
+ WorkspaceInstructionPolicyOnboardingProposalConflictError,
40962
+ WorkspaceInstructionPolicyOnboardingProposalContentError,
40963
+ WorkspaceInstructionPolicyOnboardingProposalStaleError,
40679
40964
  WorkspaceInstructionPolicyOperationReuseError,
40680
40965
  WorkspaceInstructionPolicySnapshotAuthorityError,
40681
40966
  abandonCodexResetRedemptionBeforeProvider,
@@ -40847,6 +41132,7 @@ export {
40847
41132
  createWorkspaceArtifact,
40848
41133
  createWorkspaceEnvironment,
40849
41134
  createWorkspaceInstructionPolicyDraft,
41135
+ createWorkspaceInstructionPolicyOnboardingProposal,
40850
41136
  databaseFailureCode,
40851
41137
  sql15 as dbSql,
40852
41138
  deactivatePreferenceRegistry,
@@ -41112,6 +41398,7 @@ export {
41112
41398
  listWorkspaceArtifacts,
41113
41399
  listWorkspaceControlEvents,
41114
41400
  listWorkspaceEnvironments,
41401
+ listWorkspaceInstructionPolicyOnboardingProposals,
41115
41402
  listWorkspaceInstructionPolicyRevisions,
41116
41403
  listWorkspaceMembers,
41117
41404
  listWorkspacePacks,