Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(entity_registry): add owner grant policy (MACRO-3382) (#6854)

Will Hutchinsonded6c57a8906
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 4e5d9415a7..f071af99d8 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -74,6 +74,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -165,6 +166,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -278,6 +280,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -397,6 +400,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -542,6 +546,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -666,6 +671,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -741,6 +747,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -817,6 +824,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -914,6 +922,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -1132,6 +1141,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -1318,6 +1328,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/favorites",
@@ -1473,6 +1484,8 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
+ "crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
"crates/frecency",
"crates/genai_telemetry",
@@ -1576,6 +1589,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -1878,6 +1892,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -2103,6 +2118,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -2180,6 +2196,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -2256,6 +2273,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -2341,6 +2359,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -2578,6 +2597,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/favorites",
@@ -2860,6 +2880,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -3018,6 +3039,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -3098,6 +3120,8 @@
"delete_chat_handler": [
"crates/bot_id",
"crates/cowlike",
+ "crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/macro_entrypoint",
@@ -3106,7 +3130,10 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/model-entity",
+ "crates/model_file_type",
"crates/model_owner",
+ "crates/models_entity_access_management",
+ "crates/models_permissions",
"crates/workspace-hack",
"services/delete_chat_handler"
],
@@ -3143,6 +3170,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -3283,6 +3311,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -3440,6 +3469,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/favorites",
@@ -3666,6 +3696,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -3753,6 +3784,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -3837,6 +3869,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -4231,6 +4264,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -4466,6 +4500,7 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -4630,11 +4665,17 @@
"entity_registry_db_utils": [
"crates/bot_id",
"crates/cowlike",
+ "crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/macro_user_id",
+ "crates/macro_uuid",
"crates/model-entity",
+ "crates/model_file_type",
"crates/model_owner",
+ "crates/models_entity_access_management",
+ "crates/models_permissions",
"crates/workspace-hack"
],
"favorites": [
@@ -4772,6 +4813,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -5121,6 +5163,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -5243,6 +5286,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/favorites",
@@ -5505,6 +5549,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -5679,6 +5724,7 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -6118,6 +6164,7 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -6197,6 +6244,7 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -6408,6 +6456,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -6558,6 +6607,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -7255,6 +7305,7 @@
"crates/document_sub_type",
"crates/email_formatting",
"crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -7603,6 +7654,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -7946,6 +7998,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8085,6 +8138,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8205,6 +8259,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8433,6 +8488,7 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8572,6 +8628,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8687,6 +8744,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8792,6 +8850,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -8903,6 +8962,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -9008,6 +9068,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
@@ -9652,6 +9713,7 @@
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/genai_telemetry",
@@ -9725,6 +9787,7 @@
"crates/entity_access_db_utils",
"crates/entity_access_management",
"crates/entity_mutation",
+ "crates/entity_registry/entity_registry",
"crates/entity_registry/entity_registry_db_utils",
"crates/entity_registry/shared_entity_registry",
"crates/filter_ast",
diff --git a/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json b/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json
new file mode 100644
index 0000000000..f599ee3f78
--- /dev/null
+++ b/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT created_at, updated_at, deleted_at\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 2,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ true
+ ]
+ },
+ "hash": "02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a"
+}
diff --git a/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json b/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json
new file mode 100644
index 0000000000..4ee3b36f55
--- /dev/null
+++ b/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT count(*) AS \"count!\"\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "count!",
+ "type_info": "Int8"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5"
+}
diff --git a/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json b/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json
new file mode 100644
index 0000000000..de1be84b86
--- /dev/null
+++ b/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT deleted_at\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "deleted_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true
+ ]
+ },
+ "hash": "2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68"
+}
diff --git a/.sqlx/query-4dd5e1d3f6244ad18760fe3827baffcc5433d3e134144f34ce44650295f7540f.json b/.sqlx/query-4dd5e1d3f6244ad18760fe3827baffcc5433d3e134144f34ce44650295f7540f.json
new file mode 100644
index 0000000000..d1236236f2
--- /dev/null
+++ b/.sqlx/query-4dd5e1d3f6244ad18760fe3827baffcc5433d3e134144f34ce44650295f7540f.json
@@ -0,0 +1,45 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT entity_type, owner_type AS \"owner_type: OwnerType\", owner_id\n FROM entity WHERE id = $1\n FOR UPDATE\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_type",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_type: OwnerType",
+ "type_info": {
+ "Custom": {
+ "name": "entity_owner_type",
+ "kind": {
+ "Enum": [
+ "user",
+ "bot",
+ "team"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 2,
+ "name": "owner_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "4dd5e1d3f6244ad18760fe3827baffcc5433d3e134144f34ce44650295f7540f"
+}
diff --git a/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json b/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json
new file mode 100644
index 0000000000..d45c527cb6
--- /dev/null
+++ b/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT created_at, updated_at\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 1,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90"
+}
diff --git a/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json b/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json
new file mode 100644
index 0000000000..13f1afb64b
--- /dev/null
+++ b/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json
@@ -0,0 +1,20 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT now() AS \"now!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "now!",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": []
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab"
+}
diff --git a/.sqlx/query-9f2a13d4dd04581b65566aa5eb00679fac726265af9ad7aadc4d0f5b7e14fd0e.json b/.sqlx/query-9f2a13d4dd04581b65566aa5eb00679fac726265af9ad7aadc4d0f5b7e14fd0e.json
new file mode 100644
index 0000000000..000ae34291
--- /dev/null
+++ b/.sqlx/query-9f2a13d4dd04581b65566aa5eb00679fac726265af9ad7aadc4d0f5b7e14fd0e.json
@@ -0,0 +1,34 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT source_type::text AS \"source_type!\", source_id,\n access_level::text AS \"access_level!\"\n FROM entity_access\n WHERE entity_id = $1 AND granted_from_project_id IS NULL\n ORDER BY source_type::text, source_id\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "source_type!",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "source_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "access_level!",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null,
+ false,
+ null
+ ]
+ },
+ "hash": "9f2a13d4dd04581b65566aa5eb00679fac726265af9ad7aadc4d0f5b7e14fd0e"
+}
diff --git a/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json b/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json
new file mode 100644
index 0000000000..61f2382a73
--- /dev/null
+++ b/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json
@@ -0,0 +1,45 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT owner_type AS \"owner_type: OwnerType\", owner_id, entity_type\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner_type: OwnerType",
+ "type_info": {
+ "Custom": {
+ "name": "entity_owner_type",
+ "kind": {
+ "Enum": [
+ "user",
+ "bot",
+ "team"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3"
+}
diff --git a/.sqlx/query-b8bebd828019c7a0d8b9638e76bd3c7866017f7dda1a20ea7339a03ae07b5aa3.json b/.sqlx/query-b8bebd828019c7a0d8b9638e76bd3c7866017f7dda1a20ea7339a03ae07b5aa3.json
new file mode 100644
index 0000000000..4230593cb8
--- /dev/null
+++ b/.sqlx/query-b8bebd828019c7a0d8b9638e76bd3c7866017f7dda1a20ea7339a03ae07b5aa3.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT EXISTS(SELECT 1 FROM entity WHERE id = $1) AS \"exists!\"",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "exists!",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "b8bebd828019c7a0d8b9638e76bd3c7866017f7dda1a20ea7339a03ae07b5aa3"
+}
diff --git a/.sqlx/query-df0711cec9b33f65e0e78edbfee37533a470b01479f3fd8e062a2877306e8d26.json b/.sqlx/query-df0711cec9b33f65e0e78edbfee37533a470b01479f3fd8e062a2877306e8d26.json
new file mode 100644
index 0000000000..15c2846b68
--- /dev/null
+++ b/.sqlx/query-df0711cec9b33f65e0e78edbfee37533a470b01479f3fd8e062a2877306e8d26.json
@@ -0,0 +1,28 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT owner_user_id, team_id\n FROM bots\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner_user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "team_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ true,
+ true
+ ]
+ },
+ "hash": "df0711cec9b33f65e0e78edbfee37533a470b01479f3fd8e062a2877306e8d26"
+}
diff --git a/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json b/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json
new file mode 100644
index 0000000000..a3ee67dabe
--- /dev/null
+++ b/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json
@@ -0,0 +1,39 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT owner_type AS \"owner_type: OwnerType\", owner_id\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "owner_type: OwnerType",
+ "type_info": {
+ "Custom": {
+ "name": "entity_owner_type",
+ "kind": {
+ "Enum": [
+ "user",
+ "bot",
+ "team"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 1,
+ "name": "owner_id",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false
+ ]
+ },
+ "hash": "e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f"
+}
diff --git a/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json b/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json
new file mode 100644
index 0000000000..1cb9540fe6
--- /dev/null
+++ b/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT entity_type\n FROM entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "entity_type",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c"
+}
diff --git a/Cargo.lock b/Cargo.lock
index 8e59713f67..5fa4e20a39 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2931,6 +2931,7 @@ dependencies = [
"channels",
"chrono",
"entity_access",
+ "entity_registry",
"harness_id",
"hex",
"macro_authorization",
@@ -2942,6 +2943,7 @@ dependencies = [
"messages",
"mockall",
"model-error-response",
+ "model_owner",
"rand 0.9.4",
"rootcause",
"schemars 1.2.1",
@@ -6614,6 +6616,7 @@ dependencies = [
name = "entity_registry"
version = "0.1.0"
dependencies = [
+ "bot_id",
"chrono",
"macro_db_migrator",
"model-entity",
@@ -6631,7 +6634,10 @@ dependencies = [
name = "entity_registry_db_utils"
version = "0.1.0"
dependencies = [
+ "bot_id",
"chrono",
+ "entity_access_db_utils",
+ "entity_registry",
"macro_db_migrator",
"model_owner",
"rootcause",
diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.toml
index 19a5f4c236..f6efa948f9 100644
--- a/crates/bots/Cargo.toml
+++ b/crates/bots/Cargo.toml
@@ -27,7 +27,7 @@ inbound = [
"dep:utoipa",
"ports",
]
-outbound = ["dep:sqlx", "dep:macro_uuid", "ports"]
+outbound = ["dep:sqlx", "dep:macro_uuid", "dep:entity_registry", "dep:model_owner", "dep:rootcause", "ports"]
ports = ["dep:entity_access", "entity_access/ports", "dep:tokio", "messages/ports"]
test-utils = ["dep:mockall", "ports"]
@@ -42,6 +42,9 @@ harness_id = { path = "../harness_id", features = ["schema", "sqlx"] }
channels = { path = "../channels", optional = true, default-features = false, features = ["ports"] }
chrono = { workspace = true }
entity_access = { path = "../entity_access", optional = true, default-features = false }
+entity_registry = { path = "../entity_registry/entity_registry", optional = true }
+model_owner = { path = "../model_owner", optional = true }
+rootcause = { workspace = true, optional = true }
hex = { workspace = true }
macro_authorization = { path = "../macro_authorization", optional = true, default-features = false }
messages = { path = "../messages" }
diff --git a/crates/bots/fixtures/owner_grants.sql b/crates/bots/fixtures/owner_grants.sql
new file mode 100644
index 0000000000..d8f8cbeedc
--- /dev/null
+++ b/crates/bots/fixtures/owner_grants.sql
@@ -0,0 +1,11 @@
+INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES
+('90000000-0000-0000-0000-000000000001', 'sponsor', '[email protected]', 'owner-grants-sponsor'),
+('90000000-0000-0000-0000-000000000002', 'creator', '[email protected]', 'owner-grants-creator');
+INSERT INTO "User" (id, email, macro_user_id) VALUES
+('macro|[email protected]', '[email protected]', '90000000-0000-0000-0000-000000000001'),
+('macro|[email protected]', '[email protected]', '90000000-0000-0000-0000-000000000002');
+INSERT INTO team (id, name, owner_id) VALUES
+('90000000-0000-0000-0000-000000000011', 'Sponsor team', 'macro|[email protected]');
+INSERT INTO bots (id, kind, owner_user_id, team_id, name, handle, created_by) VALUES
+('90000000-0000-0000-0000-000000000021', 'owned', NULL, '90000000-0000-0000-0000-000000000011', 'Team bot', 'sponsor-team-bot', 'macro|[email protected]'),
+('90000000-0000-0000-0000-000000000022', 'owned', 'macro|[email protected]', NULL, 'User bot', 'sponsor-user-bot', 'macro|[email protected]');
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index 40ee16412a..19316ad504 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -3,6 +3,8 @@
#[cfg(test)]
mod tests;
+mod owner_grants;
+
use crate::domain::{
models::{
Agent, AgentChannelScope, AgentMcpServer, AgentMcpServers, AuthenticatedBot, Bot,
diff --git a/crates/bots/src/outbound/pg_bots_repo/owner_grants.rs b/crates/bots/src/outbound/pg_bots_repo/owner_grants.rs
new file mode 100644
index 0000000000..5368d8c636
--- /dev/null
+++ b/crates/bots/src/outbound/pg_bots_repo/owner_grants.rs
@@ -0,0 +1,39 @@
+//! Historical sponsor lookup for entity registration, owned by the bots adapter.
+
+#[cfg(test)]
+mod test;
+
+use bot_id::BotId;
+use entity_registry::{BotFacts, EntityRegistryError, EntityRegistryResult};
+use model_owner::{Owner, OwnerType};
+use rootcause::prelude::*;
+
+use super::PgBotsRepo;
+
+impl BotFacts for PgBotsRepo {
+ async fn sponsor(&self, bot: BotId) -> EntityRegistryResult<Option<Owner>> {
+ // Intentionally no deleted_at filter: deletion does not erase ownership.
+ // created_by is attribution, not the sponsor, and must never grant access.
+ let row = sqlx::query!(
+ r#"
+ SELECT owner_user_id, team_id
+ FROM bots
+ WHERE id = $1
+ "#,
+ bot.as_uuid(),
+ )
+ .fetch_optional(&self.pool)
+ .await
+ .context(EntityRegistryError::Infrastructure)?;
+ let Some(row) = row else {
+ return Ok(None);
+ };
+ match (row.owner_user_id, row.team_id) {
+ (Some(user), None) => Owner::parse(OwnerType::User, &user)
+ .map(Some)
+ .context(EntityRegistryError::InvalidBotSponsor),
+ (None, Some(team)) => Ok(Some(Owner::Team(team))),
+ _ => Err(EntityRegistryError::InvalidBotSponsor.into()),
+ }
+ }
+}
diff --git a/crates/bots/src/outbound/pg_bots_repo/owner_grants/test.rs b/crates/bots/src/outbound/pg_bots_repo/owner_grants/test.rs
new file mode 100644
index 0000000000..c4a00138c8
--- /dev/null
+++ b/crates/bots/src/outbound/pg_bots_repo/owner_grants/test.rs
@@ -0,0 +1,45 @@
+use super::*;
+use crate::domain::ports::BotRepo;
+use entity_registry::OwnerGrantPolicy;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("owner_grants"))
+)]
+async fn deleted_bots_keep_their_sponsor_not_their_creator(pool: PgPool) {
+ let repo = PgBotsRepo::new(pool);
+ let policy = OwnerGrantPolicy::new(repo.clone());
+ let cases = [
+ (
+ BotId::new_from_uuid(Uuid::from_u128(0x90000000_0000_0000_0000_000000000021)),
+ Owner::Team(Uuid::from_u128(0x90000000_0000_0000_0000_000000000011)),
+ ),
+ (
+ BotId::new_from_uuid(Uuid::from_u128(0x90000000_0000_0000_0000_000000000022)),
+ Owner::parse(OwnerType::User, "macro|[email protected]").unwrap(),
+ ),
+ ];
+ for (bot, sponsor) in cases {
+ let expected = vec![Owner::Bot(bot), sponsor];
+ assert_eq!(policy.grants_for(&Owner::Bot(bot)).await.unwrap(), expected);
+ assert!(repo.delete_bot(bot).await.unwrap());
+ assert!(repo.get_bot(bot).await.unwrap().is_none());
+ assert_eq!(policy.grants_for(&Owner::Bot(bot)).await.unwrap(), expected);
+ }
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn missing_bot_fails_closed(pool: PgPool) {
+ let policy = OwnerGrantPolicy::new(PgBotsRepo::new(pool));
+ let error = policy
+ .grants_for(&Owner::Bot(BotId::new_from_uuid(Uuid::from_u128(42))))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ *error.current_context(),
+ EntityRegistryError::InvalidBotSponsor
+ );
+}
diff --git a/crates/entity_registry/entity_registry/Cargo.toml b/crates/entity_registry/entity_registry/Cargo.toml
index 5f6bcdec3a..6327fb5925 100644
--- a/crates/entity_registry/entity_registry/Cargo.toml
+++ b/crates/entity_registry/entity_registry/Cargo.toml
@@ -9,6 +9,7 @@ default = []
postgres = ["dep:sqlx", "model_owner/sqlx"]
[dependencies]
+bot_id = { path = "../../bot_id" }
chrono = { workspace = true }
model-entity = { path = "../../model-entity" }
model_owner = { path = "../../model_owner" }
diff --git a/crates/entity_registry/entity_registry/src/domain.rs b/crates/entity_registry/entity_registry/src/domain.rs
index 7100f49ec7..57ac2dbc27 100644
--- a/crates/entity_registry/entity_registry/src/domain.rs
+++ b/crates/entity_registry/entity_registry/src/domain.rs
@@ -1,5 +1,6 @@
//! Domain models, ports, and the service implementation.
pub mod models;
+pub mod owner_grant_policy;
pub mod ports;
pub mod service;
diff --git a/crates/entity_registry/entity_registry/src/domain/owner_grant_policy.rs b/crates/entity_registry/entity_registry/src/domain/owner_grant_policy.rs
new file mode 100644
index 0000000000..db19e7fa53
--- /dev/null
+++ b/crates/entity_registry/entity_registry/src/domain/owner_grant_policy.rs
@@ -0,0 +1,48 @@
+//! Direct owner grants derived from the recorded owner, not the creating actor.
+
+#[cfg(test)]
+mod test;
+
+use model_owner::Owner;
+use shared_entity_registry::{EntityRegistryError, EntityRegistryResult};
+
+use super::ports::BotFacts;
+
+/// Expands ownership into direct owner-level grant sources.
+///
+/// This is not creation authorization. In particular, assigning a system bot as
+/// owner is supported; an autonomous system bot creating an entity must be
+/// rejected upstream before calling registration. An acting user's identity
+/// must never be substituted for the recorded owner or the bot's sponsor.
+#[derive(Clone)]
+pub struct OwnerGrantPolicy<B> {
+ bots: B,
+}
+
+impl<B: BotFacts> OwnerGrantPolicy<B> {
+ /// Construct a policy over bot facts supplied by the composition root.
+ pub fn new(bots: B) -> Self {
+ Self { bots }
+ }
+
+ /// Return typed `(source_type, source_id)` pairs as [`Owner`] principals.
+ ///
+ /// Users and teams receive one grant; owned bots receive a bot grant and a
+ /// sponsor grant. Known system bots receive only their own grant and require
+ /// no persisted bot row. Missing or invalid sponsors fail closed.
+ pub async fn grants_for(&self, owner: &Owner) -> EntityRegistryResult<Vec<Owner>> {
+ let mut grants = vec![owner.clone()];
+ if let Owner::Bot(bot) = owner
+ && !bot_id::is_system_bot(*bot)
+ {
+ let sponsor = self.bots.sponsor(*bot).await?;
+ match sponsor {
+ Some(sponsor @ (Owner::User(_) | Owner::Team(_))) => grants.push(sponsor),
+ Some(Owner::Bot(_)) | None => {
+ return Err(EntityRegistryError::InvalidBotSponsor.into());
+ }
+ }
+ }
+ Ok(grants)
+ }
+}
diff --git a/crates/entity_registry/entity_registry/src/domain/owner_grant_policy/test.rs b/crates/entity_registry/entity_registry/src/domain/owner_grant_policy/test.rs
new file mode 100644
index 0000000000..047eda7fbe
--- /dev/null
+++ b/crates/entity_registry/entity_registry/src/domain/owner_grant_policy/test.rs
@@ -0,0 +1,121 @@
+use super::*;
+use bot_id::{BotId, SYSTEM_BOTS};
+use model_owner::OwnerType;
+use uuid::Uuid;
+
+const OWNED_BOT: BotId = BotId::new_from_uuid(Uuid::from_u128(42));
+
+struct FakeBotFacts(Option<Owner>);
+
+impl BotFacts for FakeBotFacts {
+ async fn sponsor(&self, bot: BotId) -> EntityRegistryResult<Option<Owner>> {
+ assert_eq!(bot, OWNED_BOT);
+ Ok(self.0.clone())
+ }
+}
+
+struct NoLookup;
+
+impl BotFacts for NoLookup {
+ async fn sponsor(&self, _: BotId) -> EntityRegistryResult<Option<Owner>> {
+ panic!("this owner must not require a bot lookup")
+ }
+}
+
+fn user() -> Owner {
+ Owner::parse(OwnerType::User, "macro|[email protected]").unwrap()
+}
+
+#[tokio::test]
+async fn personal_owner_gets_only_the_user_grant() {
+ assert_eq!(
+ OwnerGrantPolicy::new(NoLookup)
+ .grants_for(&user())
+ .await
+ .unwrap(),
+ vec![user()]
+ );
+}
+
+#[tokio::test]
+async fn team_owner_gets_only_the_team_grant() {
+ let owner = Owner::Team(Uuid::from_u128(1));
+ assert_eq!(
+ OwnerGrantPolicy::new(NoLookup)
+ .grants_for(&owner)
+ .await
+ .unwrap(),
+ vec![owner]
+ );
+}
+
+#[tokio::test]
+async fn personal_bot_gets_bot_and_sponsor_grants() {
+ assert_eq!(
+ OwnerGrantPolicy::new(FakeBotFacts(Some(user())))
+ .grants_for(&Owner::Bot(OWNED_BOT))
+ .await
+ .unwrap(),
+ vec![Owner::Bot(OWNED_BOT), user()]
+ );
+}
+
+#[tokio::test]
+async fn team_bot_gets_bot_and_team_grants() {
+ let team = Owner::Team(Uuid::from_u128(1));
+ assert_eq!(
+ OwnerGrantPolicy::new(FakeBotFacts(Some(team.clone())))
+ .grants_for(&Owner::Bot(OWNED_BOT))
+ .await
+ .unwrap(),
+ vec![Owner::Bot(OWNED_BOT), team]
+ );
+}
+
+#[tokio::test]
+async fn assigned_system_bots_get_only_bot_grants_without_lookup() {
+ for bot in SYSTEM_BOTS {
+ let owner = Owner::Bot(bot.id);
+ assert_eq!(
+ OwnerGrantPolicy::new(NoLookup)
+ .grants_for(&owner)
+ .await
+ .unwrap(),
+ vec![owner]
+ );
+ }
+}
+
+#[tokio::test]
+async fn missing_and_bot_sponsors_fail_closed() {
+ for sponsor in [None, Some(Owner::Bot(OWNED_BOT))] {
+ let error = OwnerGrantPolicy::new(FakeBotFacts(sponsor))
+ .grants_for(&Owner::Bot(OWNED_BOT))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ *error.current_context(),
+ EntityRegistryError::InvalidBotSponsor
+ );
+ }
+}
+
+struct Unavailable;
+
+impl BotFacts for Unavailable {
+ async fn sponsor(&self, _: BotId) -> EntityRegistryResult<Option<Owner>> {
+ Err(EntityRegistryError::Infrastructure.into())
+ }
+}
+
+#[tokio::test]
+async fn lookup_errors_are_not_silently_replaced_by_bot_only_grants() {
+ let error = OwnerGrantPolicy::new(Unavailable)
+ .grants_for(&Owner::Bot(OWNED_BOT))
+ .await
+ .unwrap_err();
+ assert_eq!(
+ *error.current_context(),
+ EntityRegistryError::Infrastructure
+ );
+}
diff --git a/crates/entity_registry/entity_registry/src/domain/ports.rs b/crates/entity_registry/entity_registry/src/domain/ports.rs
index 17cea8e37a..794351ab55 100644
--- a/crates/entity_registry/entity_registry/src/domain/ports.rs
+++ b/crates/entity_registry/entity_registry/src/domain/ports.rs
@@ -1,4 +1,4 @@
-//! Read-side ports.
+//! Registry read and owner-grant fact ports.
use model_owner::Owner;
use shared_entity_registry::{EntityRegistryResult, RegisteredEntityType};
@@ -6,6 +6,19 @@ use uuid::Uuid;
use super::models::{EntityRecord, EntityTypeCount};
+/// Facts needed to expand a recorded bot owner into its sponsor grant.
+///
+/// Implementations must include soft-deleted bots and use the bot's owner,
+/// never its creator. Only user and team sponsors are valid. Missing bots
+/// return `None`; lookup/decoding failures must not be treated as missing.
+pub trait BotFacts: Send + Sync {
+ /// Look up the sponsor of an owned bot, including historical rows.
+ fn sponsor(
+ &self,
+ bot: bot_id::BotId,
+ ) -> impl Future<Output = EntityRegistryResult<Option<Owner>>> + Send;
+}
+
/// Persistence port for the registry.
pub trait EntityRegistryRepository: Clone + Send + Sync + 'static {
/// The row for `id`, deleted or not. `None` if never registered or hard-deleted.
diff --git a/crates/entity_registry/entity_registry/src/lib.rs b/crates/entity_registry/entity_registry/src/lib.rs
index afb864cc0a..1c521a026b 100644
--- a/crates/entity_registry/entity_registry/src/lib.rs
+++ b/crates/entity_registry/entity_registry/src/lib.rs
@@ -29,7 +29,8 @@ pub mod domain;
pub mod outbound;
pub use domain::models::{EntityRecord, EntityTypeCount};
-pub use domain::ports::{EntityRegistryRepository, EntityRegistryService};
+pub use domain::owner_grant_policy::OwnerGrantPolicy;
+pub use domain::ports::{BotFacts, EntityRegistryRepository, EntityRegistryService};
pub use domain::service::EntityRegistryServiceImpl;
pub use shared_entity_registry::{
EntityRegistryError, EntityRegistryResult, InsertOutcome, NewEntityRecord, Owner,
diff --git a/crates/entity_registry/entity_registry_db_utils/Cargo.toml b/crates/entity_registry/entity_registry_db_utils/Cargo.toml
index 85d7b789b6..9eafa2385c 100644
--- a/crates/entity_registry/entity_registry_db_utils/Cargo.toml
+++ b/crates/entity_registry/entity_registry_db_utils/Cargo.toml
@@ -5,6 +5,8 @@ publish = false
version = "0.1.0"
[dependencies]
+entity_access_db_utils = { path = "../../entity_access_db_utils" }
+entity_registry = { path = "../entity_registry" }
chrono = { workspace = true }
model_owner = { path = "../../model_owner", features = ["sqlx"] }
rootcause = { workspace = true }
@@ -15,5 +17,6 @@ uuid = { workspace = true }
workspace-hack = { version = "0.1", path = "../../workspace-hack" }
[dev-dependencies]
+bot_id = { path = "../../bot_id" }
macro_db_migrator = { path = "../../macro_db_migrator" }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/crates/entity_registry/entity_registry_db_utils/fixtures/fail_sponsor_grant.sql b/crates/entity_registry/entity_registry_db_utils/fixtures/fail_sponsor_grant.sql
new file mode 100644
index 0000000000..7aac4f15ae
--- /dev/null
+++ b/crates/entity_registry/entity_registry_db_utils/fixtures/fail_sponsor_grant.sql
@@ -0,0 +1,11 @@
+-- Fail the second grant after the bot grant has already succeeded.
+CREATE FUNCTION fail_sponsor_grant() RETURNS trigger LANGUAGE plpgsql AS $$
+BEGIN
+ IF NEW.source_type = 'user' THEN
+ RAISE EXCEPTION 'injected sponsor grant failure';
+ END IF;
+ RETURN NEW;
+END;
+$$;
+CREATE TRIGGER fail_sponsor_grant BEFORE INSERT ON entity_access
+FOR EACH ROW EXECUTE FUNCTION fail_sponsor_grant();
diff --git a/crates/entity_registry/entity_registry_db_utils/src/lib.rs b/crates/entity_registry/entity_registry_db_utils/src/lib.rs
index 4ee0d729fa..530be148a7 100644
--- a/crates/entity_registry/entity_registry_db_utils/src/lib.rs
+++ b/crates/entity_registry/entity_registry_db_utils/src/lib.rs
@@ -4,11 +4,15 @@
//! Other crates call these helpers from inside their own resource-row
//! transactions. The helpers never commit. Reads go through
//! `entity_registry::EntityRegistryService`. Shared types live in
-//! `shared_entity_registry`; this crate does not depend on the read service.
+//! `shared_entity_registry`. [`OwnedEntityRegistrar`] applies the registry's
+//! domain owner-grant policy alongside the row write in the caller's transaction.
#[cfg(test)]
mod test;
+mod owned;
+pub use owned::OwnedEntityRegistrar;
+
use chrono::{DateTime, Utc};
use model_owner::{Owner, OwnerType};
use rootcause::prelude::*;
diff --git a/crates/entity_registry/entity_registry_db_utils/src/owned.rs b/crates/entity_registry/entity_registry_db_utils/src/owned.rs
new file mode 100644
index 0000000000..ad6bd4d14a
--- /dev/null
+++ b/crates/entity_registry/entity_registry_db_utils/src/owned.rs
@@ -0,0 +1,86 @@
+//! Transaction mechanics for domain-selected owner grants.
+
+#[cfg(test)]
+mod test;
+
+use entity_registry::{BotFacts, OwnerGrantPolicy};
+use model_owner::OwnerType;
+use rootcause::prelude::*;
+use sqlx::{Acquire, Postgres, Transaction};
+
+use crate::{
+ EntityRegistryError, EntityRegistryResult, InsertOutcome, NewEntityRecord, insert_entity,
+};
+
+/// Atomic registration of an entity and all grants selected by its owner policy.
+///
+/// Construct this at the composition root with historical bot facts (for
+/// example `bots::outbound::pg_bots_repo::PgBotsRepo`). Callers must authorize
+/// creation and resolve the recorded owner before calling this persistence API.
+#[derive(Clone)]
+pub struct OwnedEntityRegistrar<B> {
+ policy: OwnerGrantPolicy<B>,
+}
+
+impl<B: BotFacts> OwnedEntityRegistrar<B> {
+ /// Use the supplied domain policy for all registrations.
+ pub fn new(policy: OwnerGrantPolicy<B>) -> Self {
+ Self { policy }
+ }
+
+ /// Register a row and upsert its direct owner grants in `tx`.
+ ///
+ /// Never commits the caller's transaction. A savepoint prevents partial
+ /// writes even if the caller handles an error and commits other work.
+ /// Matching retries repair missing grants; conflicting owners/types fail
+ /// without granting access to the conflicting principal. Timestamps on an
+ /// existing row are preserved. This is not an ownership-transfer API.
+ pub async fn register_owned_entity(
+ &self,
+ tx: &mut Transaction<'_, Postgres>,
+ record: NewEntityRecord,
+ ) -> EntityRegistryResult<InsertOutcome> {
+ let grants = self.policy.grants_for(&record.owner).await?;
+ let mut savepoint = tx
+ .begin()
+ .await
+ .context(EntityRegistryError::Infrastructure)?;
+ let outcome = insert_entity(&mut savepoint, record.clone()).await?;
+
+ // Serialize retries with ownership changes and verify the authoritative
+ // row: insert_entity's AlreadyRegistered alone does not imply a match.
+ let stored = sqlx::query!(
+ r#"
+ SELECT entity_type, owner_type AS "owner_type: OwnerType", owner_id
+ FROM entity WHERE id = $1
+ FOR UPDATE
+ "#,
+ record.id,
+ )
+ .fetch_one(savepoint.as_mut())
+ .await
+ .context(EntityRegistryError::Infrastructure)?;
+ if stored.entity_type != record.entity_type.as_str()
+ || stored.owner_type != record.owner.owner_type()
+ || stored.owner_id != record.owner.principal_id()
+ {
+ return Err(EntityRegistryError::RegistrationConflict.into());
+ }
+
+ for source in grants {
+ entity_access_db_utils::upsert_owner_grant(
+ &mut savepoint,
+ &record.id,
+ record.entity_type.into(),
+ &source,
+ )
+ .await
+ .context(EntityRegistryError::Infrastructure)?;
+ }
+ savepoint
+ .commit()
+ .await
+ .context(EntityRegistryError::Infrastructure)?;
+ Ok(outcome)
+ }
+}
diff --git a/crates/entity_registry/entity_registry_db_utils/src/owned/test.rs b/crates/entity_registry/entity_registry_db_utils/src/owned/test.rs
new file mode 100644
index 0000000000..091fb9e708
--- /dev/null
+++ b/crates/entity_registry/entity_registry_db_utils/src/owned/test.rs
@@ -0,0 +1,220 @@
+use super::*;
+use bot_id::{BotId, MACRO_AI_BOT_ID};
+use entity_registry::{Owner, RegisteredEntityType};
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+const OWNED_BOT: BotId = BotId::new_from_uuid(Uuid::from_u128(42));
+
+struct Facts(Option<Owner>);
+
+impl BotFacts for Facts {
+ async fn sponsor(&self, bot: BotId) -> EntityRegistryResult<Option<Owner>> {
+ assert_eq!(bot, OWNED_BOT);
+ Ok(self.0.clone())
+ }
+}
+
+fn user() -> Owner {
+ Owner::parse(OwnerType::User, "macro|[email protected]").unwrap()
+}
+
+fn registrar(sponsor: Option<Owner>) -> OwnedEntityRegistrar<Facts> {
+ OwnedEntityRegistrar::new(OwnerGrantPolicy::new(Facts(sponsor)))
+}
+
+async fn grants(tx: &mut Transaction<'_, Postgres>, id: Uuid) -> Vec<(String, String, String)> {
+ sqlx::query!(
+ r#"
+ SELECT source_type::text AS "source_type!", source_id,
+ access_level::text AS "access_level!"
+ FROM entity_access
+ WHERE entity_id = $1 AND granted_from_project_id IS NULL
+ ORDER BY source_type::text, source_id
+ "#,
+ id,
+ )
+ .fetch_all(tx.as_mut())
+ .await
+ .unwrap()
+ .into_iter()
+ .map(|r| (r.source_type, r.source_id, r.access_level))
+ .collect()
+}
+
+async fn registered(tx: &mut Transaction<'_, Postgres>, id: Uuid) -> bool {
+ sqlx::query_scalar!(
+ r#"SELECT EXISTS(SELECT 1 FROM entity WHERE id = $1) AS "exists!""#,
+ id
+ )
+ .fetch_one(tx.as_mut())
+ .await
+ .unwrap()
+}
+
+fn expected(sources: &[Owner]) -> Vec<(String, String, String)> {
+ let mut rows = sources
+ .iter()
+ .map(|owner| {
+ (
+ owner.owner_type().to_string(),
+ owner.principal_id(),
+ "owner".to_owned(),
+ )
+ })
+ .collect::<Vec<_>>();
+ rows.sort();
+ rows
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn registers_all_owner_kinds_and_entity_kinds_idempotently(pool: PgPool) {
+ let team = Owner::Team(Uuid::from_u128(1));
+ let cases = [
+ (user(), None, vec![user()]),
+ (team.clone(), None, vec![team.clone()]),
+ (
+ Owner::Bot(OWNED_BOT),
+ Some(user()),
+ vec![Owner::Bot(OWNED_BOT), user()],
+ ),
+ (
+ Owner::Bot(OWNED_BOT),
+ Some(team.clone()),
+ vec![Owner::Bot(OWNED_BOT), team],
+ ),
+ (
+ Owner::Bot(MACRO_AI_BOT_ID),
+ None,
+ vec![Owner::Bot(MACRO_AI_BOT_ID)],
+ ),
+ ];
+ let mut tx = pool.begin().await.unwrap();
+ for (owner, sponsor, sources) in cases {
+ let registrar = registrar(sponsor);
+ for kind in RegisteredEntityType::ALL {
+ let record = NewEntityRecord::new(Uuid::now_v7(), kind, owner.clone());
+ assert_eq!(
+ registrar
+ .register_owned_entity(&mut tx, record.clone())
+ .await
+ .unwrap(),
+ InsertOutcome::Inserted
+ );
+ assert_eq!(
+ registrar
+ .register_owned_entity(&mut tx, record.clone())
+ .await
+ .unwrap(),
+ InsertOutcome::AlreadyRegistered
+ );
+ assert!(registered(&mut tx, record.id).await);
+ assert_eq!(grants(&mut tx, record.id).await, expected(&sources));
+ }
+ }
+ tx.commit().await.unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn conflicting_registration_never_grants_access(pool: PgPool) {
+ let registrar = registrar(None);
+ let record = NewEntityRecord::new(Uuid::now_v7(), RegisteredEntityType::Document, user());
+ let mut tx = pool.begin().await.unwrap();
+ registrar
+ .register_owned_entity(&mut tx, record.clone())
+ .await
+ .unwrap();
+ for conflict in [
+ NewEntityRecord {
+ owner: Owner::Team(Uuid::from_u128(1)),
+ ..record.clone()
+ },
+ NewEntityRecord {
+ entity_type: RegisteredEntityType::Chat,
+ ..record.clone()
+ },
+ ] {
+ let error = registrar
+ .register_owned_entity(&mut tx, conflict)
+ .await
+ .unwrap_err();
+ assert_eq!(
+ *error.current_context(),
+ EntityRegistryError::RegistrationConflict
+ );
+ assert_eq!(grants(&mut tx, record.id).await, expected(&[user()]));
+ }
+ tx.commit().await.unwrap();
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn retry_repairs_missing_grants_and_outer_rollback_removes_both(pool: PgPool) {
+ let record = NewEntityRecord::new(
+ Uuid::now_v7(),
+ RegisteredEntityType::Chat,
+ Owner::Bot(OWNED_BOT),
+ );
+ let mut tx = pool.begin().await.unwrap();
+ insert_entity(&mut tx, record.clone()).await.unwrap();
+ assert_eq!(
+ registrar(Some(user()))
+ .register_owned_entity(&mut tx, record.clone())
+ .await
+ .unwrap(),
+ InsertOutcome::AlreadyRegistered
+ );
+ assert_eq!(
+ grants(&mut tx, record.id).await,
+ expected(&[record.owner.clone(), user()])
+ );
+ tx.rollback().await.unwrap();
+ let mut tx = pool.begin().await.unwrap();
+ assert!(!registered(&mut tx, record.id).await);
+ assert!(grants(&mut tx, record.id).await.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn missing_sponsor_writes_nothing(pool: PgPool) {
+ let record = NewEntityRecord::new(
+ Uuid::now_v7(),
+ RegisteredEntityType::Chat,
+ Owner::Bot(OWNED_BOT),
+ );
+ let mut tx = pool.begin().await.unwrap();
+ assert!(
+ registrar(None)
+ .register_owned_entity(&mut tx, record.clone())
+ .await
+ .is_err()
+ );
+ tx.commit().await.unwrap();
+ let mut tx = pool.begin().await.unwrap();
+ assert!(!registered(&mut tx, record.id).await);
+ assert!(grants(&mut tx, record.id).await.is_empty());
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("fail_sponsor_grant"))
+)]
+async fn second_grant_failure_rolls_back_registration_even_if_caller_commits(pool: PgPool) {
+ let record = NewEntityRecord::new(
+ Uuid::now_v7(),
+ RegisteredEntityType::Chat,
+ Owner::Bot(OWNED_BOT),
+ );
+ let mut tx = pool.begin().await.unwrap();
+ let error = registrar(Some(user()))
+ .register_owned_entity(&mut tx, record.clone())
+ .await
+ .unwrap_err();
+ assert_eq!(
+ *error.current_context(),
+ EntityRegistryError::Infrastructure
+ );
+ tx.commit().await.unwrap();
+ let mut tx = pool.begin().await.unwrap();
+ assert!(!registered(&mut tx, record.id).await);
+ assert!(grants(&mut tx, record.id).await.is_empty());
+}
diff --git a/crates/entity_registry/shared_entity_registry/src/lib.rs b/crates/entity_registry/shared_entity_registry/src/lib.rs
index f7bcffe887..bc29abd136 100644
--- a/crates/entity_registry/shared_entity_registry/src/lib.rs
+++ b/crates/entity_registry/shared_entity_registry/src/lib.rs
@@ -1,8 +1,9 @@
#![deny(missing_docs)]
//! Types shared by `entity_registry` and `entity_registry_db_utils`.
//!
-//! Reads go through `entity_registry`. Transactional writes go through
-//! `entity_registry_db_utils`. Neither crate depends on the other.
+//! Reads and owner-grant policy live in `entity_registry`. Transactional writes
+//! go through `entity_registry_db_utils`, which applies that policy when
+//! registering owned entities.
//!
//! ```
//! use model_entity::EntityType;
@@ -179,6 +180,12 @@ pub enum WriteOutcome {
/// Failure kinds of the registry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum EntityRegistryError {
+ /// An owned bot has no resolvable user/team sponsor.
+ #[error("bot sponsor is missing or invalid")]
+ InvalidBotSponsor,
+ /// An existing id has a different recorded owner or entity type.
+ #[error("entity registration conflicts with the recorded owner or type")]
+ RegistrationConflict,
/// A stored row could not be decoded into a registry record.
/// The attached id says which row.
#[error("entity row is corrupt")]
diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo.rs b/services/scheduled_action/src/outbound/pg_event_run_repo.rs
index b2627b0a5e..90217e71ab 100644
--- a/services/scheduled_action/src/outbound/pg_event_run_repo.rs
+++ b/services/scheduled_action/src/outbound/pg_event_run_repo.rs
@@ -298,6 +298,9 @@ impl EventRunRepository for PgEventRunRepo {
.fetch_optional(&mut *tx)
.await?;
let Some(action) = action else {
+ // Drop only queues rollback. Release the action lock before returning
+ // so an immediate SKIP LOCKED reconciliation can observe this action.
+ tx.rollback().await?;
return Ok(None);
};
let pending = sqlx::query_as!(
@@ -313,6 +316,7 @@ impl EventRunRepository for PgEventRunRepo {
.fetch_optional(&mut *tx)
.await?;
let Some(pending) = pending else {
+ tx.rollback().await?;
return Ok(None);
};
let pending = PendingEventRun::try_from(pending)?;
@@ -322,6 +326,7 @@ impl EventRunRepository for PgEventRunRepo {
|| pending.revision != run.pending.revision
|| pending.event != run.pending.event
{
+ tx.rollback().await?;
return Ok(None);
}
let action = ScheduledAction {
diff --git a/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs b/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs
index b4a550559f..885d7f8637 100644
--- a/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs
+++ b/services/scheduled_action/src/outbound/pg_event_run_repo/test.rs
@@ -630,6 +630,37 @@ async fn revision_disable_and_cancellation_rechecks(pool: PgPool) {
);
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn rejected_claims_release_locks_for_immediate_retry(pool: PgPool) {
+ let (repo, id, event) = setup(&pool).await;
+ admit(&repo, id, &event).await;
+ let pending = repo.pending_runs(page(1)).await.unwrap().remove(0);
+
+ for _ in 0..16 {
+ // Reserve another connection first so checking the lock cannot implicitly
+ // flush a queued rollback by reusing the claim's connection.
+ let mut observer = pool.begin().await.unwrap();
+ let mut stale = pending.clone();
+ stale.event = new_event(event.entity_id());
+ assert!(claim(&repo, stale).await.is_none());
+ assert!(lock_action(&mut observer, id).await.unwrap());
+ observer.rollback().await.unwrap();
+ }
+
+ repo.cancel_pending(
+ pending.key(),
+ pending.revision,
+ CancellationReason::AccessDenied,
+ )
+ .await
+ .unwrap();
+ // The no-pending-head rejection must release the action lock as well.
+ let mut observer = pool.begin().await.unwrap();
+ assert!(claim(&repo, pending).await.is_none());
+ assert!(lock_action(&mut observer, id).await.unwrap());
+ observer.rollback().await.unwrap();
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn locked_actions_do_not_block_independent_dispatch(pool: PgPool) {
let (repo, id, event) = setup(&pool).await;