Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(seed): config-driven scenario seeding for teams/perms/entities (#4812)
gbirman494241f1e3dc
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 8b6edeb6a5..f8360c9b4c 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -4714,9 +4714,11 @@"crates/attachment","crates/authentication_service_client","crates/bot_id",+ "crates/call","crates/channel_sender","crates/channels","crates/comms_db_client",+ "crates/connection","crates/connection_gateway_client","crates/connection_gateway_models","crates/contacts",@@ -4735,10 +4737,12 @@"crates/invite_email","crates/item_filters","crates/last_online_tracker",+ "crates/lexical_client","crates/macro_auth","crates/macro_authorization","crates/macro_aws_config","crates/macro_db_client",+ "crates/macro_db_migrator","crates/macro_entrypoint","crates/macro_env","crates/macro_env_var",@@ -4763,17 +4767,25 @@"crates/models_pagination","crates/models_permissions","crates/models_properties",+ "crates/models_search",+ "crates/models_search_cursor",+ "crates/models_soup","crates/models_team","crates/non_empty","crates/notification",+ "crates/opensearch_client",+ "crates/opensearch_query_builder","crates/prompt","crates/properties","crates/rate_limit","crates/remote_env_var",+ "crates/roles_and_permissions","crates/s3_key","crates/share_permission_db_utils","crates/sqs_client","crates/sqs_worker",+ "crates/sync_service",+ "crates/sync_service_client","crates/system_properties","crates/unfurl","crates/user_quota",diff --git a/.sqlx/query-08bd7c6f5b9f188bb4b70a71ab2f1d5483608926bd1a95ebe15a4e8b32f96cf4.json b/.sqlx/query-08bd7c6f5b9f188bb4b70a71ab2f1d5483608926bd1a95ebe15a4e8b32f96cf4.jsonnew file mode 100644index 0000000000..e5e213a9af--- /dev/null+++ b/.sqlx/query-08bd7c6f5b9f188bb4b70a71ab2f1d5483608926bd1a95ebe15a4e8b32f96cf4.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"Document\"\n SET uploaded = true, \"contentState\" = 'ready', \"contentLocation\" = $2, \"updatedAt\" = NOW()\n WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "08bd7c6f5b9f188bb4b70a71ab2f1d5483608926bd1a95ebe15a4e8b32f96cf4"+}diff --git a/.sqlx/query-0b834789998d86d421f4dff440dacee4c0870c84360148c91b5c214c7efb217c.json b/.sqlx/query-0b834789998d86d421f4dff440dacee4c0870c84360148c91b5c214c7efb217c.jsonnew file mode 100644index 0000000000..6cbb05dd8c--- /dev/null+++ b/.sqlx/query-0b834789998d86d421f4dff440dacee4c0870c84360148c91b5c214c7efb217c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)\n VALUES ($1, $2, $3)\n ON CONFLICT DO NOTHING",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "0b834789998d86d421f4dff440dacee4c0870c84360148c91b5c214c7efb217c"+}diff --git a/.sqlx/query-20a3deab69a58f900d9cd66e05dd5f009531d236fcf7bc3a61b6015312fcc8ef.json b/.sqlx/query-20a3deab69a58f900d9cd66e05dd5f009531d236fcf7bc3a61b6015312fcc8ef.jsonnew file mode 100644index 0000000000..5c1aedfb5b--- /dev/null+++ b/.sqlx/query-20a3deab69a58f900d9cd66e05dd5f009531d236fcf7bc3a61b6015312fcc8ef.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"Project\" (id, name, \"userId\", \"parentId\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, NOW(), NOW())",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "20a3deab69a58f900d9cd66e05dd5f009531d236fcf7bc3a61b6015312fcc8ef"+}diff --git a/.sqlx/query-3f9cd1b81768e34e744b6632b337220f55451cf8f39f48e02809cac33dcd742b.json b/.sqlx/query-3f9cd1b81768e34e744b6632b337220f55451cf8f39f48e02809cac33dcd742b.jsonnew file mode 100644index 0000000000..b5ccdf3df9--- /dev/null+++ b/.sqlx/query-3f9cd1b81768e34e744b6632b337220f55451cf8f39f48e02809cac33dcd742b.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO macro_user (id, username, email, stripe_customer_id, has_trialed)\n VALUES ($1, $2, $3, $4, false)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "3f9cd1b81768e34e744b6632b337220f55451cf8f39f48e02809cac33dcd742b"+}diff --git a/.sqlx/query-4a2f056c40c53586ff12cb2f737189620a31743bb6cccc3141a12b94a64e841d.json b/.sqlx/query-4a2f056c40c53586ff12cb2f737189620a31743bb6cccc3141a12b94a64e841d.jsonnew file mode 100644index 0000000000..5a911c5180--- /dev/null+++ b/.sqlx/query-4a2f056c40c53586ff12cb2f737189620a31743bb6cccc3141a12b94a64e841d.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"User\" (id, email, \"stripeCustomerId\", macro_user_id, \"tutorialComplete\", \"hasOnboardingDocuments\")\n VALUES ($1, $2, $3, $4, true, true)\n ON CONFLICT (id) DO UPDATE SET\n macro_user_id = EXCLUDED.macro_user_id,\n \"tutorialComplete\" = true,\n \"hasOnboardingDocuments\" = true",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "4a2f056c40c53586ff12cb2f737189620a31743bb6cccc3141a12b94a64e841d"+}diff --git a/.sqlx/query-4b7721366eaa1932a6b400c89bbb02156838e5f96fa525e8ddc25686c5039ee1.json b/.sqlx/query-4b7721366eaa1932a6b400c89bbb02156838e5f96fa525e8ddc25686c5039ee1.jsonnew file mode 100644index 0000000000..e7128919c2--- /dev/null+++ b/.sqlx/query-4b7721366eaa1932a6b400c89bbb02156838e5f96fa525e8ddc25686c5039ee1.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM \"RolesOnUsers\" WHERE \"userId\" = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4b7721366eaa1932a6b400c89bbb02156838e5f96fa525e8ddc25686c5039ee1"+}diff --git a/.sqlx/query-4b7b942c36c791e4d44c8dc81ae955fd03e1f39d4f8f7f1cbc69ac26cae41daa.json b/.sqlx/query-4b7b942c36c791e4d44c8dc81ae955fd03e1f39d4f8f7f1cbc69ac26cae41daa.jsonnew file mode 100644index 0000000000..5010fd79ae--- /dev/null+++ b/.sqlx/query-4b7b942c36c791e4d44c8dc81ae955fd03e1f39d4f8f7f1cbc69ac26cae41daa.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)\n VALUES ($1, $2, $3, $4)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "4b7b942c36c791e4d44c8dc81ae955fd03e1f39d4f8f7f1cbc69ac26cae41daa"+}diff --git a/.sqlx/query-4465cdde5f953cd550e7190572d8e5e4c70fce8558763d56a3f57e99474a9aeb.json b/.sqlx/query-8663960aa71e2aa7ecda4a72954c9e116633a2f4569d753127250dd2821c0b80.jsonsimilarity index 75%rename from .sqlx/query-4465cdde5f953cd550e7190572d8e5e4c70fce8558763d56a3f57e99474a9aeb.jsonrename to .sqlx/query-8663960aa71e2aa7ecda4a72954c9e116633a2f4569d753127250dd2821c0b80.jsonindex a891deb671..2a36f223c7 100644--- a/.sqlx/query-4465cdde5f953cd550e7190572d8e5e4c70fce8558763d56a3f57e99474a9aeb.json+++ b/.sqlx/query-8663960aa71e2aa7ecda4a72954c9e116633a2f4569d753127250dd2821c0b80.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n INSERT INTO comms_channels (id, name, owner_id, org_id, channel_type)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id\n ",+ "query": "\n INSERT INTO comms_channels (id, name, owner_id, org_id, channel_type, team_id)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id\n ","describe": {"columns": [{@@ -27,12 +27,13 @@]}}- }+ },+ "Uuid"]},"nullable": [false]},- "hash": "4465cdde5f953cd550e7190572d8e5e4c70fce8558763d56a3f57e99474a9aeb"+ "hash": "8663960aa71e2aa7ecda4a72954c9e116633a2f4569d753127250dd2821c0b80"}diff --git a/.sqlx/query-86cd66b302fbd4f382e29d0fc733b0f3c42ea13a63fa0af88a1ad0c8b2b4703d.json b/.sqlx/query-86cd66b302fbd4f382e29d0fc733b0f3c42ea13a63fa0af88a1ad0c8b2b4703d.jsonnew file mode 100644index 0000000000..35524a50f5--- /dev/null+++ b/.sqlx/query-86cd66b302fbd4f382e29d0fc733b0f3c42ea13a63fa0af88a1ad0c8b2b4703d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"RolesOnUsers\" (\"userId\", \"roleId\") VALUES ($1, 'self_serve')\n ON CONFLICT DO NOTHING",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "86cd66b302fbd4f382e29d0fc733b0f3c42ea13a63fa0af88a1ad0c8b2b4703d"+}diff --git a/.sqlx/query-91412298a485d8ae383851cf30f558ff23cb17d2dc6558bbb46505a9b5ad1b17.json b/.sqlx/query-91412298a485d8ae383851cf30f558ff23cb17d2dc6558bbb46505a9b5ad1b17.jsonnew file mode 100644index 0000000000..31e79192ec--- /dev/null+++ b/.sqlx/query-91412298a485d8ae383851cf30f558ff23cb17d2dc6558bbb46505a9b5ad1b17.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM macro_user WHERE email = $1 LIMIT 1",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "91412298a485d8ae383851cf30f558ff23cb17d2dc6558bbb46505a9b5ad1b17"+}diff --git a/.sqlx/query-9a57ecd731771930c6c2869109cee9db228479ee02deb82508aa91f7ec60c04f.json b/.sqlx/query-9a57ecd731771930c6c2869109cee9db228479ee02deb82508aa91f7ec60c04f.jsonnew file mode 100644index 0000000000..f794d7f2ef--- /dev/null+++ b/.sqlx/query-9a57ecd731771930c6c2869109cee9db228479ee02deb82508aa91f7ec60c04f.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO macro_user_info (macro_user_id, first_name, last_name)\n VALUES ($1, $2, $3)\n ON CONFLICT (macro_user_id) DO UPDATE SET\n first_name = EXCLUDED.first_name,\n last_name = EXCLUDED.last_name",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "9a57ecd731771930c6c2869109cee9db228479ee02deb82508aa91f7ec60c04f"+}diff --git a/.sqlx/query-a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843.json b/.sqlx/query-a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843.jsonnew file mode 100644index 0000000000..86dd19cf0a--- /dev/null+++ b/.sqlx/query-a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"SharePermission\" (id, \"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, false, NULL, NOW(), NOW())",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "a232bddebe04a4e984010888e73d170189e6d981cb7006220b0cffd692bf7843"+}diff --git a/.sqlx/query-a62e33143461ff0a63ffca3a0b3f42feedacf73457186d356cb07658482d9576.json b/.sqlx/query-a62e33143461ff0a63ffca3a0b3f42feedacf73457186d356cb07658482d9576.jsonnew file mode 100644index 0000000000..ce53652dd1--- /dev/null+++ b/.sqlx/query-a62e33143461ff0a63ffca3a0b3f42feedacf73457186d356cb07658482d9576.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"RolesOnUsers\" (\"userId\", \"roleId\") VALUES ($1, $2)\n ON CONFLICT DO NOTHING",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "a62e33143461ff0a63ffca3a0b3f42feedacf73457186d356cb07658482d9576"+}diff --git a/.sqlx/query-b5aa6e03cd40f1aa10adddb7e1c263219faae00127d4899204e9ab4f4808d927.json b/.sqlx/query-b5aa6e03cd40f1aa10adddb7e1c263219faae00127d4899204e9ab4f4808d927.jsonnew file mode 100644index 0000000000..fc46b9c232--- /dev/null+++ b/.sqlx/query-b5aa6e03cd40f1aa10adddb7e1c263219faae00127d4899204e9ab4f4808d927.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO call_records\n (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms,\n share_permission_id, share_with_team, custom_name)\n VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Int8",+ "Text",+ "Bool",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b5aa6e03cd40f1aa10adddb7e1c263219faae00127d4899204e9ab4f4808d927"+}diff --git a/.sqlx/query-b7544935880874038c3f173ee391fa126bd662957cddb81dbdbc4be8a324b177.json b/.sqlx/query-b7544935880874038c3f173ee391fa126bd662957cddb81dbdbc4be8a324b177.jsonnew file mode 100644index 0000000000..9a7fca32e6--- /dev/null+++ b/.sqlx/query-b7544935880874038c3f173ee391fa126bd662957cddb81dbdbc4be8a324b177.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO macro_user_email_verification (macro_user_id, email, is_verified)\n VALUES ($1, $2, true)\n ON CONFLICT (email) DO UPDATE SET\n macro_user_id = EXCLUDED.macro_user_id,\n is_verified = true",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b7544935880874038c3f173ee391fa126bd662957cddb81dbdbc4be8a324b177"+}diff --git a/.sqlx/query-cab8f8bc212efbd37288abd7c2228b4cd463466833e48fb04792e687eacc6b2a.json b/.sqlx/query-cab8f8bc212efbd37288abd7c2228b4cd463466833e48fb04792e687eacc6b2a.jsonnew file mode 100644index 0000000000..3e6abc307c--- /dev/null+++ b/.sqlx/query-cab8f8bc212efbd37288abd7c2228b4cd463466833e48fb04792e687eacc6b2a.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO contacts_connections(user1, user2)\n SELECT * FROM unnest($1::text[], $2::text[])\n ON CONFLICT(user1, user2) DO UPDATE SET updated_at = now()",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "cab8f8bc212efbd37288abd7c2228b4cd463466833e48fb04792e687eacc6b2a"+}diff --git a/.sqlx/query-e2d28eefdabb430c3f48e60c4305e709000859f72ea57cf592b112af88fbbac5.json b/.sqlx/query-e2d28eefdabb430c3f48e60c4305e709000859f72ea57cf592b112af88fbbac5.jsonnew file mode 100644index 0000000000..9096d394d0--- /dev/null+++ b/.sqlx/query-e2d28eefdabb430c3f48e60c4305e709000859f72ea57cf592b112af88fbbac5.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO \"Chat\" (id, \"userId\", name, \"isPersistent\") VALUES ($1, $2, $3, true)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "e2d28eefdabb430c3f48e60c4305e709000859f72ea57cf592b112af88fbbac5"+}diff --git a/.sqlx/query-0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa.json b/.sqlx/query-fab9a824cda630cab30894236104bd723c6473db79f05ce7fd94ccd1f02fcbc3.jsonsimilarity index 51%rename from .sqlx/query-0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa.jsonrename to .sqlx/query-fab9a824cda630cab30894236104bd723c6473db79f05ce7fd94ccd1f02fcbc3.jsonindex d80c3a400a..52288cbc23 100644--- a/.sqlx/query-0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa.json+++ b/.sqlx/query-fab9a824cda630cab30894236104bd723c6473db79f05ce7fd94ccd1f02fcbc3.json@@ -1,11 +1,11 @@{"db_name": "PostgreSQL",- "query": "\n SELECT\n m.id as message_id,\n c.email_address as \"sender!\",\n COALESCE(c.name, c.email_address) as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.id = ANY($1)\n AND m.link_id = ANY($2)\n ",+ "query": "\n SELECT\n m.id as \"message_id!\",\n c.email_address as \"sender!\",\n COALESCE(c.name, c.email_address) as \"pretty_sender!\"\n FROM email_messages m\n LEFT JOIN email_contacts c ON c.id = m.from_contact_id\n WHERE m.id = ANY($1)\n AND m.link_id = ANY($2)\n ","describe": {"columns": [{"ordinal": 0,- "name": "message_id",+ "name": "message_id!","type_info": "Uuid"},{@@ -26,10 +26,10 @@]},"nullable": [- false,true,+ false,null]},- "hash": "0fa9fb46a9895ff170c9bbf339ec2369429e7fdc40a531ac5296b5442fa4f5aa"+ "hash": "fab9a824cda630cab30894236104bd723c6473db79f05ce7fd94ccd1f02fcbc3"}diff --git a/.sqlx/query-fc3c43a6bde6daf8051c95de2aa5e7447acfb73a4d3b92ce5f52518dea32dc71.json b/.sqlx/query-fc3c43a6bde6daf8051c95de2aa5e7447acfb73a4d3b92ce5f52518dea32dc71.jsonnew file mode 100644index 0000000000..62d7e146a1--- /dev/null+++ b/.sqlx/query-fc3c43a6bde6daf8051c95de2aa5e7447acfb73a4d3b92ce5f52518dea32dc71.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO call_record_transcripts\n (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)\n VALUES ($1, $2, $3, $4, $5, $6, $7)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ "Text",+ "Timestamptz",+ "Timestamptz",+ "Int4"+ ]+ },+ "nullable": []+ },+ "hash": "fc3c43a6bde6daf8051c95de2aa5e7447acfb73a4d3b92ce5f52518dea32dc71"+}diff --git a/Cargo.lock b/Cargo.lockindex ff7f956aab..4b79f96a2d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -12648,11 +12648,14 @@ dependencies = ["clap","comms_db_client","email_db_client",+ "entity_access","entity_access_db_utils","fusionauth","futures",+ "lexical_client","macro_aws_config","macro_db_client",+ "macro_db_migrator","macro_entrypoint","macro_env","macro_env_var",@@ -12663,11 +12666,17 @@ dependencies = ["model-entity","models_email","models_permissions",+ "models_properties",+ "properties","rand 0.9.4","reqwest 0.13.4",+ "roles_and_permissions","serde","serde_json",+ "sha2 0.10.9","sqlx",+ "sync_service_client",+ "system_properties","tempfile","tokio","tracing",diff --git a/apps/web/src/features/auth/EmailForm.tsx b/apps/web/src/features/auth/EmailForm.tsxindex 83ea102203..e607a362de 100644--- a/apps/web/src/features/auth/EmailForm.tsx+++ b/apps/web/src/features/auth/EmailForm.tsx@@ -84,9 +84,34 @@ export const sendEmailCode = action(async (formData: FormData) => {return false; // passwordless login flow is not reached}+ // Local backends return the one-time code so dev tooling (seeded persona+ // tabs) can finish the login without the email round-trip.+ if (import.meta.env.DEV) {+ const body = (await response.json().catch(() => undefined)) as+ | { code?: string }+ | undefined;+ if (body?.code) return { autoCode: body.code };+ }+return true;}, 'passwordless-login');+/// True when the email step succeeded and the verify step should show.+export function sentEmailCode(+ result: Awaited<ReturnType<typeof sendEmailCode>> | undefined+): boolean {+ return result === true || (typeof result === 'object' && !!result);+}++/// The local-backend auto-login code, when the email step returned one.+export function autoLoginCode(+ result: Awaited<ReturnType<typeof sendEmailCode>> | undefined+): string | undefined {+ if (typeof result === 'object' && result && 'autoCode' in result) {+ return result.autoCode;+ }+}+export function useResetEmailCode(setStage: (next: Stage) => void) {const submission = useSubmission(sendEmailCode);return () => {@@ -105,7 +130,7 @@ export function EmailForm(props: { setStage: (next: Stage) => void }) {});createEffect(() => {- if (submission.result === true) {+ if (sentEmailCode(submission.result)) {props.setStage(Stage.Verify);} else if (submission.result === 'isPasswordLogin') {setIsPasswordLogin(true);diff --git a/apps/web/src/features/auth/LoginNew.tsx b/apps/web/src/features/auth/LoginNew.tsxindex 68c1f8013a..28ffb8746a 100644--- a/apps/web/src/features/auth/LoginNew.tsx+++ b/apps/web/src/features/auth/LoginNew.tsx@@ -39,7 +39,12 @@ import {Show,untrack,} from 'solid-js';-import { sendEmailCode, useResetEmailCode } from './EmailForm';+import {+ autoLoginCode,+ sendEmailCode,+ sentEmailCode,+ useResetEmailCode,+} from './EmailForm';import { Stage } from './Shared';import { useSsoLogin } from './useSsoLogin';@@ -161,14 +166,32 @@ function EmailFormNew(props: {}) {const [isPasswordLogin, setIsPasswordLogin] = createSignal(false);const submission = useSubmission(sendEmailCode);+ const send = useAction(sendEmailCode);const [searchParams] = useSearchParams();const searchParamsEmail = untrack(() => {const email = searchParams.email;if (typeof email === 'string') return email;});+ // Dev builds auto-start the flow for `?email=` links (the seeder prints+ // them per persona); combined with the local backend returning the code,+ // opening the link logs straight in.+ createEffect(() => {+ if (+ import.meta.env.DEV &&+ searchParamsEmail &&+ !submission.pending &&+ !submission.result &&+ !submission.error+ ) {+ const formData = new FormData();+ formData.append('email', searchParamsEmail);+ send(formData);+ }+ });+createEffect(() => {- if (submission.result === true) {+ if (sentEmailCode(submission.result)) {props.setStage(Stage.Verify);} else if (submission.result === 'isPasswordLogin') {setIsPasswordLogin(true);@@ -247,6 +270,23 @@ function VerifyFormNew(props: {const email = () => emailSubmission.input?.[0].get('email') as string;+ // Local backends return the code with the email step; submit it+ // automatically so seeded persona logins are one click.+ createEffect(() => {+ const code = autoLoginCode(emailSubmission.result);+ if (+ code &&+ !submission.pending &&+ !submission.result &&+ !submission.error+ ) {+ const formData = new FormData();+ formData.append('email', email());+ formData.append('one-time-code', code);+ submit(formData);+ }+ });+createEffect(() => {if (!showResendCode()) {const timer = setTimeout(() => {diff --git a/apps/web/src/lib/core/constant/servers.ts b/apps/web/src/lib/core/constant/servers.tsindex 62e2e29ed5..9c8fdcf3c5 100644--- a/apps/web/src/lib/core/constant/servers.ts+++ b/apps/web/src/lib/core/constant/servers.ts@@ -58,9 +58,24 @@ const rawLocalBackendOrigin: string | undefined = import.meta.envconst proxyOrigin: string | undefined =rawLocalBackendOrigin === 'same-origin'? globalThis.location?.origin- : rawLocalBackendOrigin;+ : resolveProxyOrigin(rawLocalBackendOrigin);const wsProxyOrigin = proxyOrigin?.replace(/^http/, 'ws');+// Follow the page's hostname (keeping the proxy's port) so the app works from+// any `*.localhost` alias. Hostnames get separate cookie jars while ports+// share them, so opening tabs like alice.localhost:3000 / carol.localhost:3000+// gives each seeded persona an isolated login session against the one backend.+function resolveProxyOrigin(configured: string | undefined) {+ if (!configured || typeof window === 'undefined') return configured;+ try {+ const url = new URL(configured);+ url.hostname = window.location.hostname;+ return url.origin;+ } catch {+ return configured;+ }+}+export const SERVER_HOSTS: Servers =import.meta.env.MODE === 'development'? selectLocalServers()diff --git a/apps/web/src/lib/service-clients/service-auth/generated/client.ts b/apps/web/src/lib/service-clients/service-auth/generated/client.tsindex dd1b18d4cb..90ce275257 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/client.ts@@ -34,6 +34,7 @@ import type {MacroApiTokenResponse,PasswordlessCallbackParams,PasswordlessRequest,+ PasswordlessStartedResponse,PasswordRequest,PatchTeamCrmSettingsRequest,PatchTeamCrmSettingsResponse,@@ -1079,7 +1080,7 @@ export const passwordLogin = async (* @summary Initiates a passwordless login*/export type passwordlessLoginResponse200 = {- data: EmptyResponse;+ data: PasswordlessStartedResponse;status: 200;};diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.tsindex 8a6264195f..92b4473a6d 100644--- a/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/index.ts@@ -70,6 +70,8 @@ export * from './macroApiTokenResponse';export * from './passwordlessCallbackParams';export * from './passwordlessRequest';export * from './passwordlessRequestReferralCode';+export * from './passwordlessStartedResponse';+export * from './passwordlessStartedResponseCode';export * from './passwordRequest';export * from './patchTeamCrmSettingsRequest';export * from './patchTeamCrmSettingsResponse';diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessStartedResponse.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessStartedResponse.tsnew file mode 100644index 0000000000..6514e30287--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessStartedResponse.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { PasswordlessStartedResponseCode } from './passwordlessStartedResponseCode';++export interface PasswordlessStartedResponse {+ /** The one-time login code, returned only by local environments so dev+tooling can complete the flow without reading the email. */+ code?: PasswordlessStartedResponseCode;+}diff --git a/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessStartedResponseCode.ts b/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessStartedResponseCode.tsnew file mode 100644index 0000000000..cf38162fca--- /dev/null+++ b/apps/web/src/lib/service-clients/service-auth/generated/schemas/passwordlessStartedResponseCode.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The one-time login code, returned only by local environments so dev+tooling can complete the flow without reading the email.+ */+export type PasswordlessStartedResponseCode = string | null;diff --git a/apps/web/src/lib/service-clients/service-auth/openapi.json b/apps/web/src/lib/service-clients/service-auth/openapi.jsonindex 5f1d01d7ed..0e7ead316b 100644--- a/apps/web/src/lib/service-clients/service-auth/openapi.json+++ b/apps/web/src/lib/service-clients/service-auth/openapi.json@@ -888,7 +888,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/PasswordlessStartedResponse"}}}@@ -4091,6 +4091,15 @@}}},+ "PasswordlessStartedResponse": {+ "type": "object",+ "properties": {+ "code": {+ "type": ["string", "null"],+ "description": "The one-time login code, returned only by local environments so dev\ntooling can complete the flow without reading the email."+ }+ }+ },"PatchTeamCrmSettingsRequest": {"type": "object","description": "Request body for `PATCH /team/crm`.",diff --git a/crates/comms_db_client/src/channels/seed_channel.rs b/crates/comms_db_client/src/channels/seed_channel.rsindex f63ef7875c..4616f1a025 100644--- a/crates/comms_db_client/src/channels/seed_channel.rs+++ b/crates/comms_db_client/src/channels/seed_channel.rs@@ -1,3 +1,6 @@+#[cfg(test)]+mod test;+use crate::activity;use anyhow::{Context, Result};use channels::domain::models::{ChannelType, ParticipantRole};@@ -19,6 +22,8 @@ pub struct SeedChannelOptions {pub channel_type: ChannelType,/// List of participant user IDs (excluding the owner, who is added automatically).pub participants: Vec<String>,+ /// Backing team ID. Required for team channels, null otherwise.+ pub team_id: Option<Uuid>,}/// Seed a channel with a pre-defined UUID.@@ -31,15 +36,16 @@ pub async fn seed_channel(db: &Pool<Postgres>, options: SeedChannelOptions) -> R// create the channellet channel = sqlx::query!(r#"- INSERT INTO comms_channels (id, name, owner_id, org_id, channel_type)- VALUES ($1, $2, $3, $4, $5)+ INSERT INTO comms_channels (id, name, owner_id, org_id, channel_type, team_id)+ VALUES ($1, $2, $3, $4, $5, $6)RETURNING id"#,options.channel_id,options.name,options.owner_id,options.org_id,- options.channel_type as ChannelType+ options.channel_type as ChannelType,+ options.team_id,).fetch_one(&mut *transaction).awaitdiff --git a/crates/comms_db_client/src/channels/seed_channel/test.rs b/crates/comms_db_client/src/channels/seed_channel/test.rsnew file mode 100644index 0000000000..a47e159d67--- /dev/null+++ b/crates/comms_db_client/src/channels/seed_channel/test.rs@@ -0,0 +1,112 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};++use super::*;++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn seeds_channel_without_team(pool: Pool<Postgres>) -> anyhow::Result<()> {+ const _: &sqlx::migrate::Migrator = &MACRO_DB_MIGRATIONS; // Dummy reference for IDE+ let channel_id: Uuid = "11111111-1111-1111-1111-111111111111".parse().unwrap();++ let id = seed_channel(+ &pool,+ SeedChannelOptions {+ channel_id,+ name: Some("general".to_string()),+ owner_id: "macro|[email protected]".to_string(),+ org_id: None,+ channel_type: ChannelType::Public,+ participants: vec!["macro|[email protected]".to_string()],+ team_id: None,+ },+ )+ .await?;++ assert_eq!(id, channel_id);++ let team_id: Option<Uuid> =+ sqlx::query_scalar("SELECT team_id FROM comms_channels WHERE id = $1")+ .bind(channel_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(team_id, None);++ let participants: i64 =+ sqlx::query_scalar("SELECT count(*) FROM comms_channel_participants WHERE channel_id = $1")+ .bind(channel_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(participants, 2);++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn seeds_team_channel_with_team_id(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let team_id: Uuid = "22222222-2222-2222-2222-222222222222".parse().unwrap();+ let channel_id: Uuid = "33333333-3333-3333-3333-333333333333".parse().unwrap();++ sqlx::query(+ "INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ('55555555-5555-5555-5555-555555555555', 'owner', '[email protected]', 'stripe-test')",+ )+ .execute(&pool)+ .await?;+ sqlx::query(+ r#"INSERT INTO "User" (id, email, macro_user_id)+ VALUES ('macro|[email protected]', '[email protected]', '55555555-5555-5555-5555-555555555555')"#,+ )+ .execute(&pool)+ .await?;+ sqlx::query(+ "INSERT INTO team (id, name, owner_id) VALUES ($1, 'acme', 'macro|[email protected]')",+ )+ .bind(team_id)+ .execute(&pool)+ .await?;++ seed_channel(+ &pool,+ SeedChannelOptions {+ channel_id,+ name: Some("acme-hq".to_string()),+ owner_id: "macro|[email protected]".to_string(),+ org_id: None,+ channel_type: ChannelType::Team,+ participants: vec![],+ team_id: Some(team_id),+ },+ )+ .await?;++ let stored: Option<Uuid> =+ sqlx::query_scalar("SELECT team_id FROM comms_channels WHERE id = $1")+ .bind(channel_id)+ .fetch_one(&pool)+ .await?;+ assert_eq!(stored, Some(team_id));++ Ok(())+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn rejects_team_channel_without_team_id(pool: Pool<Postgres>) -> anyhow::Result<()> {+ let channel_id: Uuid = "44444444-4444-4444-4444-444444444444".parse().unwrap();++ let result = seed_channel(+ &pool,+ SeedChannelOptions {+ channel_id,+ name: Some("orphan".to_string()),+ owner_id: "macro|[email protected]".to_string(),+ org_id: None,+ channel_type: ChannelType::Team,+ participants: vec![],+ team_id: None,+ },+ )+ .await;++ assert!(result.is_err(), "team channels require a team_id");+ Ok(())+}diff --git a/crates/email_db_client/src/messages/get.rs b/crates/email_db_client/src/messages/get.rsindex bbe071e73c..880efc2b10 100644--- a/crates/email_db_client/src/messages/get.rs+++ b/crates/email_db_client/src/messages/get.rs@@ -29,7 +29,7 @@ pub async fn get_message_sender_and_pretty_sender(let rows = sqlx::query!(r#"SELECT- m.id as message_id,+ m.id as "message_id!",c.email_address as "sender!",COALESCE(c.name, c.email_address) as "pretty_sender!"FROM email_messages mdiff --git a/crates/macro_cors/src/lib.rs b/crates/macro_cors/src/lib.rsindex 8c9feafec7..d5987d691c 100644--- a/crates/macro_cors/src/lib.rs+++ b/crates/macro_cors/src/lib.rs@@ -1,3 +1,6 @@+#[cfg(test)]+mod test;+use std::borrow::Cow;use axum::http::{@@ -59,7 +62,11 @@ fn is_allowed_origin(origin: &str) -> bool {return true;}- if let Some(port_str) = origin.strip_prefix("http://localhost:")+ // `localhost` and `*.localhost` (loopback-reserved per RFC 6761; used+ // locally to give each seeded persona its own cookie jar per hostname).+ if let Some(rest) = origin.strip_prefix("http://")+ && let Some((host, port_str)) = rest.rsplit_once(':')+ && (host == "localhost" || host.ends_with(".localhost"))&& let Ok(port) = port_str.parse::<u16>(){return (3000..=3999).contains(&port) || (20000..=60000).contains(&port);diff --git a/crates/macro_cors/src/test.rs b/crates/macro_cors/src/test.rsnew file mode 100644index 0000000000..498012788f--- /dev/null+++ b/crates/macro_cors/src/test.rs@@ -0,0 +1,35 @@+use super::*;++#[test]+fn allows_localhost_and_subdomain_localhost_dev_ports() {+ for origin in [+ "http://localhost:3000",+ "http://localhost:3999",+ "http://localhost:20000",+ "http://alice.localhost:3000",+ "http://carol.localhost:3005",+ ] {+ assert!(is_allowed_origin(origin), "{origin}");+ }+}++#[test]+fn rejects_non_local_and_out_of_range_origins() {+ for origin in [+ "http://localhost:2999",+ "http://localhost:9000",+ "http://alice.localhost:9000",+ "https://alice.localhost:3000",+ "http://evil-localhost:3000",+ "http://alice.localhost.evil.com:3000",+ "http://example.com:3000",+ ] {+ assert!(!is_allowed_origin(origin), "{origin}");+ }+}++#[test]+fn allows_static_origins() {+ assert!(is_allowed_origin("https://macro.com"));+ assert!(is_allowed_origin("tauri://localhost"));+}diff --git a/crates/model/src/authentication/login/response.rs b/crates/model/src/authentication/login/response.rsindex 6ffdc79965..814d4cd3c2 100644--- a/crates/model/src/authentication/login/response.rs+++ b/crates/model/src/authentication/login/response.rs@@ -5,3 +5,11 @@ pub struct SsoRequiredResponse {/// The idp_id you need to perform sso login with.pub idp_id: String,}++#[derive(serde::Serialize, serde::Deserialize, Debug, Default, ToSchema)]+pub struct PasswordlessStartedResponse {+ /// The one-time login code, returned only by local environments so dev+ /// tooling can complete the flow without reading the email.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub code: Option<String>,+}diff --git a/docs/RUNNING_LOCALLY.md b/docs/RUNNING_LOCALLY.mdindex 7ad2680bdc..ed02a9c4e0 100644--- a/docs/RUNNING_LOCALLY.md+++ b/docs/RUNNING_LOCALLY.md@@ -162,6 +162,14 @@ Run local binaries against shared dev resources instead of a fully local stack:just run_dev```+See what a running (or stopped) instance looks like — endpoints with live+reachability probes plus every container's state and host ports — without+starting or rebuilding anything:++```bash+just status_local+```+Stop an instance but keep its volumes:```bashdiff --git a/justfile b/justfileindex d5c06b6c6f..52bbc4569e 100644--- a/justfile+++ b/justfile@@ -44,6 +44,25 @@ docker_up *ARGS:echo "startup docker compose"{{ compose }} up {{ ARGS }}+# Reset and seed deterministic data used by local E2E tests.+local-e2e-seed:+ just run_dbs -d+ -just crates/macro_db_client/drop_db -y -f+ just initialize_dbs+ just tooling/seed_cli/local-e2e-smoke++# Apply a seed scenario (teams/perms/entities) to the local stack, e.g.+# `just seed-scenario apply --file seed/scenarios/team-perms.json`.+# Add --force to drop and re-migrate the local database first (pristine world).+# `just seed-scenario status` reports what's applied and re-prints login links.+[positional-arguments]+seed-scenario *ARGS:+ @just tooling/seed_cli/scenario "$@"++# Start only the services needed by the local E2E suites. Avoid unrelated+# local services with extra env/dependency requirements blocking E2E.+local-e2e-services := "authentication-service connection_gateway contacts_service document_storage_service email_service notification_service static_file_service static_file_cdn sync_service websocket_service"+# Update the fixed-output js node_modules hash after bun.lock changes.update-node-modules-hash:tooling/scripts/update-node-modules-hash.shdiff --git a/services/authentication_service/Cargo.toml b/services/authentication_service/Cargo.tomlindex 47c184a1dc..232e09d1c3 100644--- a/services/authentication_service/Cargo.toml+++ b/services/authentication_service/Cargo.toml@@ -25,6 +25,7 @@ path = "src/doppler_config.rs"default = ["rate_limit"]local = []rate_limit = []+return_passwordless_code = [][dependencies]analytics_client = { path = "../../crates/analytics_client" }diff --git a/services/authentication_service/justfile b/services/authentication_service/justfileindex 0fee57b0d0..9ccb7cd52e 100644--- a/services/authentication_service/justfile+++ b/services/authentication_service/justfile@@ -27,4 +27,4 @@ create_queue:AWS_REGION=us-east-1 aws --endpoint-url=http://localhost:4566 sqs create-queue --queue-name notification-queuerun-local:- SQLX_OFFLINE=true cargo run --features macro_middleware/local_auth+ SQLX_OFFLINE=true cargo run --features macro_middleware/local_auth,return_passwordless_codediff --git a/services/authentication_service/src/api/login/passwordless.rs b/services/authentication_service/src/api/login/passwordless.rsindex 500641d51b..47db48c92f 100644--- a/services/authentication_service/src/api/login/passwordless.rs+++ b/services/authentication_service/src/api/login/passwordless.rs@@ -12,8 +12,11 @@ use crate::{api::context::ApiContext, generate_password::generate_random_passworuse fusionauth::error::FusionAuthClientError;use macro_user_id::user_id::MacroUserId;use model::{- authentication::login::{request::PasswordlessRequest, response::SsoRequiredResponse},- response::{EmptyResponse, ErrorResponse},+ authentication::login::{+ request::PasswordlessRequest,+ response::{PasswordlessStartedResponse, SsoRequiredResponse},+ },+ response::ErrorResponse,};use referral::domain::{models::ReferralCode, ports::ReferralService};@@ -23,7 +26,7 @@ use referral::domain::{models::ReferralCode, ports::ReferralService};operation_id = "passwordless_login",path = "/login/passwordless",responses(- (status = 200, body = EmptyResponse),+ (status = 200, body = PasswordlessStartedResponse),(status = 202, body = SsoRequiredResponse),(status = 400, body=String),(status = 403, body=String),@@ -186,5 +189,11 @@ pub async fn handler(.into_response()})?;- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())+ // Hand the code back only when explicitly compiled for local/dev tooling+ // that needs to complete passwordless login without reading the email.+ let body = PasswordlessStartedResponse {+ code: cfg!(feature = "return_passwordless_code").then_some(code),+ };++ Ok((StatusCode::OK, Json(body)).into_response())}diff --git a/services/sync-service/src/durable_object.rs b/services/sync-service/src/durable_object.rsindex 05b6f7d947..652d654e53 100644--- a/services/sync-service/src/durable_object.rs+++ b/services/sync-service/src/durable_object.rs@@ -1111,7 +1111,11 @@ pub fn is_origin_allowed(origin: &str) -> bool {if ALLOWED_ORIGINS.contains(&origin) {return true;}- if let Some(port) = origin.strip_prefix("http://localhost:")+ // `localhost` and `*.localhost` (loopback-reserved; local dev uses+ // per-persona hostnames so each seeded user gets its own cookie jar).+ if let Some(rest) = origin.strip_prefix("http://")+ && let Some((host, port)) = rest.rsplit_once(':')+ && (host == "localhost" || host.ends_with(".localhost"))&& let Ok(port) = port.parse::<u16>(){return (3000..=3999).contains(&port) || (20000..=60000).contains(&port);diff --git a/tooling/just/xtask.just b/tooling/just/xtask.justindex 18c1d6baba..5e3ecc5df3 100644--- a/tooling/just/xtask.just+++ b/tooling/just/xtask.just@@ -20,6 +20,10 @@ run_dev *ARGS:doctor-local *ARGS:{{ xtask }} doctor-local "$@"+# Show an instance's endpoints and container states without starting anything.+status_local *ARGS:+ @{{ xtask }} status-local "$@"+# Reset (drop, recreate, migrate) the instance database.reset_local *ARGS:{{ xtask }} reset-local "$@"diff --git a/tooling/seed_cli/Cargo.toml b/tooling/seed_cli/Cargo.tomlindex 736c72c435..1e9b0a78f4 100644--- a/tooling/seed_cli/Cargo.toml+++ b/tooling/seed_cli/Cargo.toml@@ -12,11 +12,14 @@ chrono = { workspace = true }clap = { workspace = true }comms_db_client = { path = "../../crates/comms_db_client" }email_db_client = { path = "../../crates/email_db_client" }+entity_access = { path = "../../crates/entity_access", default-features = false, features = ["outbound"] }entity_access_db_utils = { path = "../../crates/entity_access_db_utils" }fusionauth = { path = "../../crates/fusionauth" }futures = { workspace = true }+lexical_client = { path = "../../crates/lexical_client" }macro_aws_config = { path = "../../crates/macro_aws_config", features = ["s3"] }macro_db_client = { path = "../../crates/macro_db_client" }+macro_db_migrator = { path = "../../crates/macro_db_migrator" }macro_entrypoint = { path = "../../crates/macro_entrypoint" }macro_env = { path = "../../crates/macro_env" }macro_env_var = { path = "../../crates/macro_env_var" }@@ -27,11 +30,17 @@ model = { path = "../../crates/model" }model-entity = { path = "../../crates/model-entity" }models_email = { path = "../../crates/models_email" }models_permissions = { path = "../../crates/models_permissions" }+models_properties = { path = "../../crates/models_properties" }rand = { workspace = true }reqwest = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }+properties = { path = "../../crates/properties", default-features = false, features = ["outbound"] }+roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false }+sha2 = { workspace = true }sqlx = { workspace = true }+sync_service_client = { path = "../../crates/sync_service_client" }+system_properties = { path = "../../crates/system_properties" }tokio = { workspace = true }tracing = { workspace = true }url = { workspace = true }diff --git a/tooling/seed_cli/README.md b/tooling/seed_cli/README.mdindex a8f8be930e..2e71d9a59f 100644--- a/tooling/seed_cli/README.md+++ b/tooling/seed_cli/README.md@@ -8,3 +8,55 @@ have your local environment setup.## UsageYou can explore the CLI and it's usage with `just seed help`. All commands canbe run through the `just seed` base command.++## Scenarios++A scenario file describes a complete world — users, teams, channels, and+entities (documents, tasks, projects, chats, calls, emails, messages) with the+access edges between them — so varied permission patterns are testable+locally. Tasks are markdown documents with the task subtype plus status and+assignee properties (and an optional share-with-team grant). See+`seed/scenarios/team-perms.json` for the reference example.++```bash+# From the repository root (postgres + localstack must be up):+just seed-scenario apply --file seed/scenarios/team-perms.json+just seed-scenario matrix --file seed/scenarios/team-perms.json+just seed-scenario status --file seed/scenarios/team-perms.json # or no --file+just seed-scenario reset --file seed/scenarios/team-perms.json # or --all+```++- `apply` deletes the scenario's own rows first and re-seeds, so it always+ converges on the config. Every seeded id is derived from+ `(scenario, kind, key)` and starts with the `5eed` marker — rows created+ through the app (random ids) are never touched, though content living+ inside a seeded container dies with it on re-apply (e.g. messages you sent+ in a seeded channel, which is recreated).+- `apply --force` is the pristine-world variant: it drops the local database+ entirely, re-runs migrations, and then seeds — everything goes, organic+ data included. Open the printed persona links afterwards to log back in.+- `matrix` computes the expected access level for every (user, entity) pair+ from the config and verifies it against the live database using the real+ `entity_access` service; it exits non-zero on any mismatch.+- `status` is read-only: with `--file` it reports which of the scenario's+ rows are present (per kind, with missing keys), whether the FusionAuth+ accounts and sync-service content exist, and re-prints the persona login+ links. Without `--file` it discovers every applied scenario by its id+ marker and reports on the ones matching a file in `seed/scenarios/`.+ Scenarios with distinct names (and distinct user emails) coexist in one+ database — ids are namespaced by a hash of the scenario name.+- `reset` deletes exactly the rows carrying the scenario's id marker, plus+ (with `--file`) the scenario's user accounts by email. `reset --all` cannot+ know emails, so accounts created through the signup webhook survive it.+- `apply` creates each user's FusionAuth account first (the signup webhook+ writes the base rows, which the seeder then adopts), so every seeded user+ can log in through the real passwordless flow. If FusionAuth is+ unreachable, apply seeds database rows only and says so.+- To drive several personas at once in one browser window, open the links+ apply prints (`http://alice.localhost:3000/app/login?email=…`) as plain+ tabs. Hostnames get separate cookie jars (ports don't), the app follows the+ page hostname to the backend proxy, and locally the login completes itself+ (the local backend returns the one-time code and dev builds auto-submit+ it) — so each link logs its persona straight in, one live session per tab+ against the same stack. For manual logins outside a dev build, the one-time+ codes land in mailpit (`just status_local` prints its UI address).diff --git a/tooling/seed_cli/justfile b/tooling/seed_cli/justfileindex d336113443..2373310a86 100644--- a/tooling/seed_cli/justfile+++ b/tooling/seed_cli/justfile@@ -14,3 +14,47 @@ get_environment:[positional-arguments]seed *ARGS:cargo r "$@"++# Reset and seed deterministic data for the local Playwright smoke suite.+local-e2e-smoke:+ LOCAL_E2E_SEED="true" \+ DATABASE_URL="postgres://user:password@localhost:5432/macrodb" \+ LOCAL_AWS_URL="http://localhost:4566" \+ DOCUMENT_STORAGE_BUCKET="doc-storage" \+ AWS_ACCESS_KEY_ID="test" \+ AWS_SECRET_ACCESS_KEY="test" \+ SQLX_OFFLINE="true" \+ ENVIRONMENT="local" \+ FUSIONAUTH_BASE_URL="http://localhost:9011" \+ FUSIONAUTH_API_KEY_SECRET_KEY="local" \+ FUSIONAUTH_TENANT_ID="local" \+ FUSIONAUTH_CLIENT_ID="local" \+ FUSIONAUTH_CLIENT_SECRET_KEY="local" \+ FUSIONAUTH_OAUTH_REDIRECT_URI="http://localhost:8080/oauth/redirect" \+ cargo r -- scenario local-e2e-smoke++# Run a scenario subcommand (apply/reset/matrix) against the local stack,+# e.g. `just scenario apply --file seed/scenarios/team-perms.json`.+# The FusionAuth values default to the deterministic `run_local` identity+# (tooling/xtask/crates/xtask_local/src/local/identity.rs).+[positional-arguments]+scenario *ARGS:+ @LOCAL_SEED="true" \+ DATABASE_URL="${DATABASE_URL:-postgres://user:password@localhost:5432/macrodb}" \+ LOCAL_AWS_URL="${LOCAL_AWS_URL:-http://localhost:4566}" \+ DOCUMENT_STORAGE_BUCKET="${DOCUMENT_STORAGE_BUCKET:-doc-storage}" \+ AWS_ACCESS_KEY_ID="test" \+ AWS_SECRET_ACCESS_KEY="test" \+ SQLX_OFFLINE="true" \+ ENVIRONMENT="local" \+ FUSIONAUTH_BASE_URL="${FUSIONAUTH_BASE_URL:-http://localhost:9011}" \+ FUSIONAUTH_API_KEY_SECRET_KEY="${FUSIONAUTH_API_KEY_SECRET_KEY:-bf69486b-4733-4954-a44e-2e1b5f2c8a91}" \+ FUSIONAUTH_TENANT_ID="${FUSIONAUTH_TENANT_ID:-11111111-1111-4111-8111-111111111111}" \+ FUSIONAUTH_CLIENT_ID="${FUSIONAUTH_CLIENT_ID:-22222222-2222-4222-8222-222222222222}" \+ FUSIONAUTH_CLIENT_SECRET_KEY="${FUSIONAUTH_CLIENT_SECRET_KEY:-local}" \+ FUSIONAUTH_OAUTH_REDIRECT_URI="http://localhost:8080/oauth/redirect" \+ SYNC_SERVICE_URL="${SYNC_SERVICE_URL:-http://localhost:8787}" \+ LEXICAL_SERVICE_URL="${LEXICAL_SERVICE_URL:-http://localhost:8096}" \+ INTERNAL_API_SECRET_KEY="${INTERNAL_API_SECRET_KEY:-local}" \+ FRONTEND_PORT="${FRONTEND_PORT:-3000}" \+ cargo r -q -- scenario "$@"diff --git a/tooling/seed_cli/seed/scenarios/team-perms.json b/tooling/seed_cli/seed/scenarios/team-perms.jsonnew file mode 100644index 0000000000..bd5e4be755--- /dev/null+++ b/tooling/seed_cli/seed/scenarios/team-perms.json@@ -0,0 +1,162 @@+{+ "scenario": "team-perms",+ "description": "One team (acme: alice owner, bob admin, carol member), dave collaborates via channels without being on the team, eve is an outsider. The Acme members carry team_subscriber + sub_opus like real paying-team members (join_team grants exactly those); dave is a solo professional_subscriber; eve is a free account. Exercises owner/user/team/channel/public/project/delegation access edges across every entity type.",+ "users": {+ "alice": {+ "email": "[email protected]",+ "first_name": "Alice",+ "roles": ["team_subscriber", "sub_opus"]+ },+ "bob": {+ "email": "[email protected]",+ "first_name": "Bob",+ "roles": ["team_subscriber", "sub_opus"]+ },+ "carol": {+ "email": "[email protected]",+ "first_name": "Carol",+ "roles": ["team_subscriber", "sub_opus"]+ },+ "dave": {+ "email": "[email protected]",+ "first_name": "Dave",+ "roles": ["professional_subscriber"]+ },+ "eve": { "email": "[email protected]", "first_name": "Eve" }+ },+ "teams": {+ "acme": {+ "name": "Acme",+ "owner": "alice",+ "members": { "bob": "admin", "carol": "member" }+ }+ },+ "channels": {+ "town-square": { "type": "public", "owner": "alice", "members": ["bob", "dave"] },+ "eng": { "type": "private", "owner": "alice", "members": ["bob", "dave"] },+ "acme-hq": { "type": "team", "team": "acme" },+ "dm-alice-dave": { "type": "direct_message", "members": ["alice", "dave"] }+ },+ "projects": {+ "roadmap": {+ "owner": "alice",+ "name": "Roadmap",+ "share": [{ "with": "team:acme", "level": "view" }]+ }+ },+ "documents": {+ "q3-plan": {+ "owner": "alice",+ "name": "Q3 Plan",+ "content": "# Q3 Plan\n\n- Ship the tagging system\n- Verify permissions across every entity type\n- Grow the Acme team\n",+ "project": "roadmap"+ },+ "design-doc": {+ "owner": "alice",+ "name": "Design Doc",+ "content": "# Design Doc\n\nDave has edit access; the eng channel can view this via the share and Bob's mention.\n",+ "share": [+ { "with": "user:dave", "level": "edit" },+ { "with": "channel:eng", "level": "view" }+ ]+ },+ "handbook": {+ "owner": "alice",+ "name": "Handbook",+ "file": "pdf.pdf",+ "public": "view"+ },+ "bob-notes": { "owner": "bob", "name": "Bob Notes", "file": "md.md" }+ },+ "tasks": {+ "ship-tags": {+ "owner": "alice",+ "name": "Ship the tagging system",+ "content": "# Ship the tagging system\n\n- [x] backend\n- [ ] verify perms across entity types\n",+ "project": "roadmap",+ "status": "in_progress",+ "assignees": ["alice", "bob"],+ "share_with_team": true+ },+ "fix-perms": {+ "owner": "dave",+ "name": "Fix the perms edge case",+ "assignees": ["alice"],+ "share": [{ "with": "channel:eng", "level": "view" }]+ },+ "write-docs": {+ "owner": "alice",+ "name": "Write the perms docs",+ "content": "# Write the perms docs\n\nCover every access edge the seeder exercises.\n",+ "status": "in_review",+ "assignees": ["carol"],+ "share_with_team": true+ }+ },+ "chats": {+ "alice-ai": {+ "owner": "alice",+ "name": "Alice AI chat",+ "share": [{ "with": "user:carol", "level": "view" }]+ }+ },+ "calls": {+ "eng-standup": {+ "channel": "eng",+ "created_by": "alice",+ "share_with_team": true,+ "participants": ["alice", "bob"],+ "duration_minutes": 30,+ "name": "Eng standup",+ "transcript": [+ { "speaker": "alice", "text": "Let's review the Q3 plan before we ship the design doc." },+ { "speaker": "bob", "text": "The tagging work is nearly done, verifying perms today." }+ ]+ },+ "dm-huddle": {+ "channel": "dm-alice-dave",+ "created_by": "dave",+ "participants": ["dave", "alice"],+ "duration_minutes": 10+ }+ },+ "emails": {+ "alice-inbox": {+ "owner": "alice",+ "delegated_to": ["bob"],+ "threads": {+ "welcome": {+ "subject": "Welcome to Acme",+ "from": "[email protected]",+ "body": "Welcome aboard! Here's everything you need to get started.",+ "unread": true+ },+ "renewal": {+ "subject": "Contract renewal",+ "from": "[email protected]",+ "body": "The renewal is attached, please review by Friday."+ }+ }+ },+ "dave-inbox": {+ "owner": "dave",+ "threads": {+ "invoice": {+ "subject": "Invoice #42",+ "from": "[email protected]",+ "body": "Your invoice for June is attached."+ }+ }+ }+ },+ "messages": [+ {+ "channel": "eng",+ "from": "bob",+ "text": "Design doc is ready for review",+ "mentions": ["document:design-doc"]+ },+ { "channel": "town-square", "from": "alice", "text": "Welcome everyone!" },+ { "channel": "acme-hq", "from": "carol", "text": "Team sync at 3pm." }+ ]+}diff --git a/tooling/seed_cli/src/config.rs b/tooling/seed_cli/src/config.rsindex 60f0c50bc0..2648750ece 100644--- a/tooling/seed_cli/src/config.rs+++ b/tooling/seed_cli/src/config.rs@@ -1,4 +1,6 @@-use macro_env_var::env_var;+use lexical_client::LexicalClient;+use macro_env_var::{env_var, maybe_env_vars};+use sync_service_client::SyncServiceClient;use crate::service::{auth::Auth, db::Db, s3::S3};@@ -23,6 +25,40 @@ env_var! {}}+maybe_env_vars! {+ /// sync-service base url (markdown document content lives there)+ pub struct SyncServiceUrl;+ /// lexical-service base url (markdown -> loro snapshot conversion)+ pub struct LexicalServiceUrl;+ /// internal auth key shared by sync/lexical locally+ pub struct InternalApiSecretKey;+ /// frontend dev server port, for the per-persona URLs apply prints+ pub struct FrontendPort;+}++/// Clients for initializing native markdown document content.+pub struct DocContentClients {+ /// Converts markdown to a loro snapshot.+ pub lexical: LexicalClient,+ /// Boots the document's durable object from a snapshot.+ pub sync: SyncServiceClient,+}++impl DocContentClients {+ /// Build the clients when the optional env vars are present.+ pub fn from_env() -> Option<Self> {+ let sync_url = SyncServiceUrl::new()?;+ let lexical_url = LexicalServiceUrl::new()?;+ let auth_key = InternalApiSecretKey::new()+ .map(|key| key.to_string())+ .unwrap_or_else(|| "local".to_string());+ Some(Self {+ lexical: LexicalClient::new(auth_key.clone(), lexical_url.to_string()),+ sync: SyncServiceClient::new(auth_key, sync_url.to_string()),+ })+ }+}+/// The context containing everything we need to use in the CLIpub struct SeedCliContext {/// Database connection to macrodb@@ -31,4 +67,6 @@ pub struct SeedCliContext {pub fusionauth_client: Auth,/// S3 clientpub s3: S3,+ /// Markdown content clients; absent when sync/lexical env vars are unset.+ pub doc_content: Option<DocContentClients>,}diff --git a/tooling/seed_cli/src/entity/channel/mod.rs b/tooling/seed_cli/src/entity/channel/mod.rsindex 85773072ef..9b84a1f419 100644--- a/tooling/seed_cli/src/entity/channel/mod.rs+++ b/tooling/seed_cli/src/entity/channel/mod.rs@@ -180,6 +180,7 @@ pub(crate) async fn seed_from_file_ref(channel_type: row.channel_type,org_id: None,participants,+ team_id: None,};match ctx.db.seed_channel(options).await {diff --git a/tooling/seed_cli/src/entity/channel/test.rs b/tooling/seed_cli/src/entity/channel/test.rsindex 2450c3a27a..d0111a5067 100644--- a/tooling/seed_cli/src/entity/channel/test.rs+++ b/tooling/seed_cli/src/entity/channel/test.rs@@ -195,6 +195,7 @@ fn mock_ctx(db: Db) -> SeedCliContext {db,fusionauth_client: Auth::default(),s3: S3::default(),+ doc_content: None,}}diff --git a/tooling/seed_cli/src/entity/channel_message/test.rs b/tooling/seed_cli/src/entity/channel_message/test.rsindex a705c9c5ac..99ca8ccd86 100644--- a/tooling/seed_cli/src/entity/channel_message/test.rs+++ b/tooling/seed_cli/src/entity/channel_message/test.rs@@ -162,6 +162,7 @@ fn mock_ctx(db: Db) -> SeedCliContext {db,fusionauth_client: Auth::default(),s3: S3::default(),+ doc_content: None,}}diff --git a/tooling/seed_cli/src/entity/document/test.rs b/tooling/seed_cli/src/entity/document/test.rsindex ad90d5cb7f..28019e9fcf 100644--- a/tooling/seed_cli/src/entity/document/test.rs+++ b/tooling/seed_cli/src/entity/document/test.rs@@ -164,6 +164,7 @@ fn mock_ctx(db: Db, s3: S3) -> SeedCliContext {db,fusionauth_client: Auth::default(),s3,+ doc_content: None,}}diff --git a/tooling/seed_cli/src/entity/email/test.rs b/tooling/seed_cli/src/entity/email/test.rsindex 293ee01814..4d1e134255 100644--- a/tooling/seed_cli/src/entity/email/test.rs+++ b/tooling/seed_cli/src/entity/email/test.rs@@ -158,6 +158,7 @@ fn mock_ctx(db: Db) -> SeedCliContext {db,fusionauth_client: Auth::default(),s3: S3::default(),+ doc_content: None,}}diff --git a/tooling/seed_cli/src/entity/mod.rs b/tooling/seed_cli/src/entity/mod.rsindex f8f0e3c79b..7ccef70785 100644--- a/tooling/seed_cli/src/entity/mod.rs+++ b/tooling/seed_cli/src/entity/mod.rs@@ -37,6 +37,15 @@ impl EntityCommand {}}+ /// Run destructive pre-connection setup (e.g. `scenario apply --force`+ /// dropping and re-migrating the database) before the pool opens.+ pub async fn pre_connect(&self, database_url: &str) -> anyhow::Result<()> {+ match self {+ EntityCommand::Scenario(args) => args.pre_connect(database_url).await,+ _ => Ok(()),+ }+ }+/// Execute the entity command.pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {match self {diff --git a/tooling/seed_cli/src/entity/scenario/apply.rs b/tooling/seed_cli/src/entity/scenario/apply.rsnew file mode 100644index 0000000000..b8e71d3120--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/apply.rs@@ -0,0 +1,1185 @@+//! Apply: compile a scenario spec into database rows.+//!+//! Applying always resets the scenario's own rows first (they are exactly+//! the rows carrying the scenario's id marker), then seeds fresh, so a+//! re-apply converges on the config.++use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;+use std::str::FromStr;++use anyhow::Context;+use channels::domain::models::ChannelType;+use chrono::{DateTime, Duration, Utc};+use comms_db_client::channels::seed_channel::SeedChannelOptions;+use comms_db_client::messages::seed_message::SeedMessageOptions;+use comms_db_client::model::SimpleMention;+use entity_access_db_utils::{AccessLevel, EntityAccessSourceType, EntityType};+use macro_db_client::document::v2::create::CreateDocumentArgs;+use macro_user_id::user_id::MacroUserIdStr;+use model::document::FileType;+use model::item::ShareableItemType;+use models_email::email::service::address::ContactInfo;+use models_email::email::service::label::{+ Label, LabelListVisibility, LabelType, MessageListVisibility,+};+use models_email::email::service::link::{Link, UserProvider};+use models_email::email::service::message::Message;+use models_email::email::service::thread::Thread;+use models_permissions::share_permission::SharePermissionV2;+use models_properties::service::property_value::PropertyValue;+use uuid::Uuid;++use super::reset::{reset_contacts_outbox_statement, reset_statements};+use super::spec::{+ ChannelKind, EntityRef, ScenarioSpec, ShareLevel, ShareSpec, TeamMemberRole, scenario_marker,+};+use super::{sql_string, values_sql};+use crate::config::SeedCliContext;++/// Canonical blank-markdown loro snapshot, matching the one production uses+/// to initialize empty documents.+const MARKDOWN_GOLDEN_SNAPSHOT: &[u8] =+ include_bytes!("../../../../../static_assets/markdown-golden.1.bin");++/// System labels created for every seeded inbox.+const EMAIL_SYSTEM_LABELS: &[&str] = &[+ "INBOX",+ "SENT",+ "UNREAD",+ "STARRED",+ "IMPORTANT",+ "DRAFT",+ "TRASH",+ "SPAM",+ "CATEGORY_PERSONAL",+];++impl From<ShareLevel> for AccessLevel {+ fn from(level: ShareLevel) -> Self {+ match level {+ ShareLevel::View => AccessLevel::View,+ ShareLevel::Comment => AccessLevel::Comment,+ ShareLevel::Edit => AccessLevel::Edit,+ }+ }+}++/// A resolved access grant to write to `entity_access`.+#[derive(Debug, Clone)]+pub(super) struct AccessRow {+ /// Source principal id: user id, team uuid, or channel uuid as text.+ pub source_id: String,+ /// Source principal type.+ pub source_type: EntityAccessSourceType,+ /// Granted level.+ pub access_level: AccessLevel,+ /// Project id the grant is inherited from, if any.+ pub granted_from_project_id: Option<String>,+}++/// Resolve a share spec into an access row.+pub(super) fn share_to_row(spec: &ScenarioSpec, share: &ShareSpec) -> AccessRow {+ let (source_id, source_type) = match EntityRef::parse(&share.with).expect("validated") {+ EntityRef::User(user) => (spec.user_id(&user), EntityAccessSourceType::User),+ EntityRef::Team(team) => (+ spec.team_id(&team).to_string(),+ EntityAccessSourceType::Team,+ ),+ EntityRef::Channel(channel) => (+ spec.channel_id(&channel).to_string(),+ EntityAccessSourceType::Channel,+ ),+ other => unreachable!("validated share target, got {other:?}"),+ };+ AccessRow {+ source_id,+ source_type,+ access_level: share.level.into(),+ granted_from_project_id: None,+ }+}++/// The direct (non-inherited) access rows of a project: owner + shares.+pub(super) fn project_direct_rows(spec: &ScenarioSpec, project_key: &str) -> Vec<AccessRow> {+ let project = &spec.projects[project_key];+ let mut rows = vec![AccessRow {+ source_id: spec.user_id(&project.owner),+ source_type: EntityAccessSourceType::User,+ access_level: AccessLevel::Owner,+ granted_from_project_id: None,+ }];+ rows.extend(project.share.iter().map(|s| share_to_row(spec, s)));+ rows+}++/// Access rows an entity inherits from living in `project_key`: every+/// ancestor project's direct rows, marked `granted_from` that ancestor.+pub(super) fn inherited_rows(spec: &ScenarioSpec, project_key: &str) -> Vec<AccessRow> {+ let mut rows = Vec::new();+ for ancestor in spec.project_chain(project_key) {+ let granted_from = spec.project_id(&ancestor);+ rows.extend(+ project_direct_rows(spec, &ancestor)+ .into_iter()+ .map(|mut row| {+ row.granted_from_project_id = Some(granted_from.clone());+ row+ }),+ );+ }+ rows+}++/// Order project keys parents-first.+pub(super) fn projects_parents_first(spec: &ScenarioSpec) -> Vec<String> {+ let mut ordered: Vec<String> = Vec::new();+ for key in spec.projects.keys() {+ for member in spec.project_chain(key).into_iter().rev() {+ if !ordered.contains(&member) {+ ordered.push(member);+ }+ }+ }+ ordered+}++/// Apply a scenario: reset its rows, then seed everything fresh.+#[tracing::instrument(skip(ctx, spec, seed_dir), fields(scenario = %spec.scenario), err)]+pub async fn apply(+ ctx: &SeedCliContext,+ spec: &ScenarioSpec,+ seed_dir: &Path,+) -> anyhow::Result<()> {+ let marker = scenario_marker(&spec.scenario);+ if let Some(description) = spec.description.as_deref() {+ println!("{description}\n");+ }++ println!("Resetting scenario `{}` (marker {marker})", spec.scenario);+ ctx.db+ .execute_sql_if_table_exists(+ "public.contacts_backfill_outbox",+ &reset_contacts_outbox_statement(&marker),+ )+ .await?;+ ctx.db+ .execute_statements(&reset_statements(&marker))+ .await?;++ seed_users(ctx, spec).await?;+ seed_teams(ctx, spec).await?;+ seed_channels(ctx, spec).await?;+ seed_contacts(ctx, spec).await?;+ seed_projects(ctx, spec).await?;+ seed_documents(ctx, spec, seed_dir).await?;+ seed_tasks(ctx, spec).await?;+ seed_chats(ctx, spec).await?;+ seed_calls(ctx, spec).await?;+ seed_emails(ctx, spec).await?;+ seed_messages(ctx, spec).await?;++ println!("\nScenario `{}` applied.", spec.scenario);+ print_login_links(spec);+ Ok(())+}++/// Print one login link per persona.+pub(super) fn print_login_links(spec: &ScenarioSpec) {+ let frontend_port = crate::config::FrontendPort::new()+ .map(|port| port.to_string())+ .unwrap_or_else(|| "3000".to_string());+ for (key, user) in &spec.users {+ // Per-persona hostnames get separate cookie jars, so each of these+ // can hold its own live session in ordinary tabs of one browser.+ if key+ .chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')+ {+ println!(+ " {key}: http://{key}.localhost:{frontend_port}/app/login?email={}",+ user.email+ );+ } else {+ println!(" {key}: log in as {}", user.email);+ }+ }+}++async fn seed_users(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.users.is_empty() {+ return Ok(());+ }+ println!("Seeding {} users", spec.users.len());++ // Create the FusionAuth accounts first: the signup webhook writes the+ // base macrodb rows, and it refuses to create an account whose email+ // already has a User row — so FusionAuth must come before our upserts+ // for seeded users to be log-in-able through the real flow.+ let mut fusionauth_reachable = true;+ for (key, user) in &spec.users {+ if !fusionauth_reachable {+ break;+ }+ match ctx.fusionauth_client.ensure_user(user.email.clone()).await {+ Ok(true) => println!(" user `{key}`: created FusionAuth account"),+ Ok(false) => {}+ Err(e) => {+ let message = format!("{e:#}");+ if message.contains("connect") || message.contains("Connection") {+ fusionauth_reachable = false;+ println!(+ " FusionAuth unreachable — seeding database rows only (users won't be able to log in until it's up)"+ );+ } else {+ println!(" user `{key}`: FusionAuth account creation failed: {message}");+ }+ }+ }+ }++ for (key, user) in &spec.users {+ let mut chars = key.chars();+ let capitalized = chars+ .next()+ .map(|c| c.to_uppercase().collect::<String>() + chars.as_str())+ .unwrap_or_default();++ ctx.db+ .adopt_or_seed_user(crate::service::db::AdoptOrSeedUserArgs {+ email: user.email.clone(),+ user_id: spec.user_id(key),+ derived_macro_user_id: spec.macro_user_uuid(key),+ first_name: user+ .first_name+ .clone()+ .unwrap_or_else(|| capitalized.clone()),+ last_name: user.last_name.clone().unwrap_or_else(|| "Seed".to_string()),+ stripe_customer_id: format!("stripe-seed-{}-{key}", spec.scenario),+ extra_roles: user.roles.clone(),+ })+ .await?;+ println!(" user `{key}` -> {}", spec.user_id(key));+ }+ Ok(())+}++async fn seed_teams(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.teams.is_empty() {+ return Ok(());+ }+ println!("Seeding {} teams", spec.teams.len());++ let team_values = values_sql(spec.teams.iter().map(|(key, team)| {+ vec![+ sql_string(&spec.team_id(key).to_string()),+ sql_string(team.name.as_deref().unwrap_or(key)),+ sql_string(&spec.user_id(&team.owner)),+ sql_string(&format!("sub_seed_{}_{key}", spec.scenario)),+ (team.members.len() + 1).to_string(),+ ]+ }));++ let member_rows = spec.teams.iter().flat_map(|(key, team)| {+ let team_id = spec.team_id(key).to_string();+ std::iter::once((team.owner.clone(), "owner"))+ .chain(team.members.iter().map(|(member, role)| {+ let role = match role {+ TeamMemberRole::Member => "member",+ TeamMemberRole::Admin => "admin",+ };+ (member.clone(), role)+ }))+ .map(move |(user, role)| {+ vec![+ sql_string(&spec.user_id(&user)),+ sql_string(&team_id),+ format!("{}::team_role", sql_string(role)),+ ]+ })+ .collect::<Vec<_>>()+ });+ let member_values = values_sql(member_rows);++ let crm_values = values_sql(spec.teams.iter().map(|(key, team)| {+ vec![+ sql_string(&spec.team_id(key).to_string()),+ if team.crm_enabled { "true" } else { "false" }.to_string(),+ ]+ }));++ let statements = vec![+ format!(+ "INSERT INTO team (id, name, owner_id, subscription_id, seat_count) VALUES\n {team_values}"+ ),+ format!("INSERT INTO team_user (user_id, team_id, team_role) VALUES\n {member_values}"),+ format!("INSERT INTO team_crm_settings (team_id, crm_enabled) VALUES\n {crm_values}"),+ ];++ ctx.db.execute_statements(&statements).await+}++async fn seed_channels(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.channels.is_empty() {+ return Ok(());+ }+ println!("Seeding {} channels", spec.channels.len());++ for (key, channel) in &spec.channels {+ let owner = spec.channel_owner(key);+ let participants = spec+ .channel_members(key)+ .iter()+ .map(|member| spec.user_id(member))+ .collect::<Vec<_>>();++ let channel_type = match channel.kind {+ ChannelKind::Public => ChannelType::Public,+ ChannelKind::Private => ChannelType::Private,+ ChannelKind::DirectMessage => ChannelType::DirectMessage,+ ChannelKind::Team => ChannelType::Team,+ };+ let name = match channel.kind {+ ChannelKind::DirectMessage => None,+ _ => Some(channel.name.clone().unwrap_or_else(|| key.clone())),+ };+ let team_id = channel.team.as_deref().map(|team| spec.team_id(team));++ let options = SeedChannelOptions {+ channel_id: spec.channel_id(key),+ name,+ owner_id: spec.user_id(&owner),+ org_id: None,+ channel_type,+ participants,+ team_id,+ };+ let id = ctx.db.seed_channel(options).await?;+ println!(" channel `{key}` -> {id}");+ }+ Ok(())+}++/// Seed the pairwise contact edges that production derives from channel and+/// team membership (via the contacts SQS pipeline): everyone in a group+/// becomes everyone else's contact, which is what makes teammates+/// mentionable and assignable.+async fn seed_contacts(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ let mut groups: Vec<Vec<String>> = Vec::new();+ for team in spec.teams.values() {+ let mut members = vec![team.owner.clone()];+ members.extend(team.members.keys().cloned());+ groups.push(members);+ }+ for channel_key in spec.channels.keys() {+ groups.push(spec.channel_members(channel_key));+ }++ let mut pairs: BTreeSet<(String, String)> = BTreeSet::new();+ for group in groups {+ for (i, a) in group.iter().enumerate() {+ for b in group.iter().skip(i + 1) {+ let (a, b) = (spec.user_id(a), spec.user_id(b));+ if a == b {+ continue;+ }+ pairs.insert(if a <= b { (a, b) } else { (b, a) });+ }+ }+ }++ if pairs.is_empty() {+ return Ok(());+ }+ println!("Seeding {} contact connections", pairs.len());+ ctx.db+ .insert_contact_connections(pairs.into_iter().collect())+ .await+}++async fn apply_access_rows(+ ctx: &SeedCliContext,+ entity_id: &str,+ entity_type: EntityType,+ rows: &[AccessRow],+) -> anyhow::Result<()> {+ for row in rows {+ ctx.db+ .upsert_entity_access(+ entity_id,+ entity_type,+ &row.source_id,+ row.source_type,+ row.access_level,+ row.granted_from_project_id.clone(),+ )+ .await?;+ }+ Ok(())+}++/// Write channel share-permission rows mirroring what mention-sharing does,+/// for entity kinds that carry a `SharePermission`.+async fn apply_channel_share_rows(+ ctx: &SeedCliContext,+ spec: &ScenarioSpec,+ entity_id: &str,+ item_type: ShareableItemType,+ shares: &[ShareSpec],+) -> anyhow::Result<()> {+ let item_type = item_type.to_string();+ for share in shares {+ if let Ok(EntityRef::Channel(channel)) = EntityRef::parse(&share.with) {+ ctx.db+ .upsert_channel_share_permission(+ entity_id,+ &item_type,+ &spec.channel_id(&channel).to_string(),+ share.level.into(),+ )+ .await?;+ }+ }+ Ok(())+}++async fn seed_projects(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.projects.is_empty() {+ return Ok(());+ }+ println!("Seeding {} projects", spec.projects.len());++ for key in projects_parents_first(spec) {+ let project = &spec.projects[&key];+ let project_id = spec.project_id(&key);+ let name = project.name.as_deref().unwrap_or(&key);+ let parent_id = project.parent.as_deref().map(|p| spec.project_id(p));++ ctx.db+ .insert_project(&project_id, name, &spec.user_id(&project.owner), parent_id)+ .await?;++ let mut rows = project_direct_rows(spec, &key);+ if let Some(parent) = project.parent.as_deref() {+ rows.extend(inherited_rows(spec, parent));+ }+ apply_access_rows(ctx, &project_id, EntityType::Project, &rows).await?;++ if let Some(level) = project.public {+ ctx.db+ .create_project_public_permission(+ &project_id,+ &share_permission(spec, &project.owner, level),+ )+ .await?;+ }+ apply_channel_share_rows(+ ctx,+ spec,+ &project_id,+ ShareableItemType::Project,+ &project.share,+ )+ .await?;++ println!(" project `{key}` -> {project_id}");+ }+ Ok(())+}++fn share_permission(spec: &ScenarioSpec, owner_key: &str, level: ShareLevel) -> SharePermissionV2 {+ SharePermissionV2 {+ id: String::new(),+ owner: spec.user_id(owner_key),+ is_public: true,+ public_access_level: Some(match level {+ ShareLevel::View => {+ models_permissions::share_permission::access_level::AccessLevel::View+ }+ ShareLevel::Comment => {+ models_permissions::share_permission::access_level::AccessLevel::Comment+ }+ ShareLevel::Edit => {+ models_permissions::share_permission::access_level::AccessLevel::Edit+ }+ }),+ channel_share_permissions: None,+ }+}++/// Native markdown documents live in sync-service, not object storage:+/// markdown -> loro snapshot (via lexical) -> boot the document's durable+/// object, then mark the content ready.+async fn initialize_markdown_content(+ ctx: &SeedCliContext,+ key: &str,+ document_id: &str,+ markdown: &str,+) -> anyhow::Result<()> {+ match ctx.doc_content.as_ref() {+ Some(clients) => {+ let snapshot = if markdown.trim().is_empty() {+ MARKDOWN_GOLDEN_SNAPSHOT.to_vec()+ } else {+ clients+ .lexical+ .markdown_to_loro_snapshot(markdown)+ .await+ .context("converting markdown via lexical-service")?+ };+ // Sync-service refuses to initialize a document that already+ // has a snapshot (and the local worker has no delete route), so+ // a re-apply keeps whatever content is already there. Probe via+ // the raw content route rather than `exists`: a stray websocket+ // connect instantiates an EMPTY durable object, which exists but+ // still needs initializing.+ if clients.sync.get_raw(document_id).await.is_ok() {+ println!(" `{key}`: sync-service already has content for this id, keeping it");+ } else {+ clients+ .sync+ .initialize_from_snapshot(document_id, &snapshot)+ .await+ .context("initializing document in sync-service")?;+ }+ ctx.db+ .set_document_content_ready(document_id, "sync_service")+ .await?;+ }+ None => println!(+ " `{key}`: SYNC_SERVICE_URL/LEXICAL_SERVICE_URL unset — content left pending, the doc won't open"+ ),+ }+ Ok(())+}++async fn seed_documents(+ ctx: &SeedCliContext,+ spec: &ScenarioSpec,+ seed_dir: &Path,+) -> anyhow::Result<()> {+ if spec.documents.is_empty() {+ return Ok(());+ }+ println!("Seeding {} documents", spec.documents.len());+ let files_dir = seed_dir.join("documents").join("files");++ for (key, document) in &spec.documents {+ let document_id = spec.document_id(key);+ let name = document.name.as_deref().unwrap_or(key);+ let owner_id = spec.user_id(&document.owner);+ let owner =+ MacroUserIdStr::parse_from_str(owner_id.clone().leak()).context("valid owner id")?;++ let file_type = match (&document.content, document.file.as_deref()) {+ (Some(_), _) => Some(FileType::Md),+ (None, Some(file)) => {+ let extension = file+ .split('.')+ .next_back()+ .context("document file needs an extension")?;+ Some(FileType::from_str(extension).context("valid file type")?)+ }+ (None, None) => None,+ };++ let is_public = document.public.is_some();+ let project_id = document.project.as_deref().map(|p| spec.project_id(p));+ let project_name = document.project.as_deref().map(|p| {+ spec.projects[p]+ .name+ .clone()+ .unwrap_or_else(|| p.to_string())+ });+ let created = ctx+ .db+ .create_document(CreateDocumentArgs {+ id: Some(&document_id),+ sha: "sha",+ document_name: name,+ user_id: owner.clone(),+ file_type,+ project_id: project_id.as_deref(),+ project_name: project_name.as_deref(),+ share_permission: &SharePermissionV2 {+ id: String::new(),+ owner: owner_id.clone(),+ is_public,+ public_access_level: document.public.map(|level| match level {+ ShareLevel::View => {+ models_permissions::share_permission::access_level::AccessLevel::View+ }+ ShareLevel::Comment => {+ models_permissions::share_permission::access_level::AccessLevel::Comment+ }+ ShareLevel::Edit => {+ models_permissions::share_permission::access_level::AccessLevel::Edit+ }+ }),+ channel_share_permissions: None,+ },+ skip_history: true,+ email_attachment_id: None,+ created_at: None,+ is_task: false,+ })+ .await?;++ let markdown = match (&document.content, document.file.as_deref()) {+ (Some(content), _) => Some(content.clone()),+ (None, Some(file)) if file_type == Some(FileType::Md) => {+ let path = files_dir.join(file);+ Some(+ std::fs::read_to_string(&path)+ .with_context(|| format!("reading {}", path.display()))?,+ )+ }+ _ => None,+ };++ if let Some(markdown) = markdown {+ initialize_markdown_content(ctx, key, &document_id, &markdown).await?;+ } else if let Some(file) = document.file.as_deref() {+ let file_type = file_type.expect("file implies file type");+ let s3_key = format!(+ "{}/{}/{}.{}",+ created.owner,+ created.document_id,+ created.document_version_id,+ file_type.as_str()+ );+ let path = files_dir.join(file);+ ctx.s3+ .upload_file(&s3_key, &path.to_string_lossy())+ .await+ .with_context(|| format!("uploading {}", path.display()))?;+ ctx.db+ .set_document_content_ready(&document_id, "object_storage")+ .await?;+ }++ let mut rows: Vec<AccessRow> = document+ .share+ .iter()+ .map(|s| share_to_row(spec, s))+ .collect();+ if let Some(project) = document.project.as_deref() {+ rows.extend(inherited_rows(spec, project));+ }+ apply_access_rows(ctx, &document_id, EntityType::Document, &rows).await?;+ apply_channel_share_rows(+ ctx,+ spec,+ &document_id,+ ShareableItemType::Document,+ &document.share,+ )+ .await?;++ println!(" document `{key}` -> {document_id}");+ }+ Ok(())+}++async fn seed_tasks(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.tasks.is_empty() {+ return Ok(());+ }+ println!("Seeding {} tasks", spec.tasks.len());++ for (key, task) in &spec.tasks {+ let document_id = spec.task_id(key);+ let name = task.name.as_deref().unwrap_or(key);+ let owner_id = spec.user_id(&task.owner);+ let owner =+ MacroUserIdStr::parse_from_str(owner_id.clone().leak()).context("valid owner id")?;++ let project_id = task.project.as_deref().map(|p| spec.project_id(p));+ let project_name = task.project.as_deref().map(|p| {+ spec.projects[p]+ .name+ .clone()+ .unwrap_or_else(|| p.to_string())+ });++ ctx.db+ .create_document(CreateDocumentArgs {+ id: Some(&document_id),+ sha: "sha",+ document_name: name,+ user_id: owner.clone(),+ file_type: Some(FileType::Md),+ project_id: project_id.as_deref(),+ project_name: project_name.as_deref(),+ share_permission: &SharePermissionV2 {+ id: String::new(),+ owner: owner_id.clone(),+ is_public: false,+ public_access_level: None,+ channel_share_permissions: None,+ },+ skip_history: true,+ email_attachment_id: None,+ created_at: None,+ is_task: true,+ })+ .await?;++ let markdown = task.content.clone().unwrap_or_default();+ initialize_markdown_content(ctx, key, &document_id, &markdown).await?;++ let mut rows: Vec<AccessRow> = task.share.iter().map(|s| share_to_row(spec, s)).collect();+ if task.share_with_team+ && let Some(team) = spec.team_of(&task.owner)+ {+ // Mirrors the app's share-with-team toggle on tasks: the owner's+ // team gets comment access.+ rows.push(AccessRow {+ source_id: spec.team_id(team).to_string(),+ source_type: EntityAccessSourceType::Team,+ access_level: AccessLevel::Comment,+ granted_from_project_id: None,+ });+ }+ if let Some(project) = task.project.as_deref() {+ rows.extend(inherited_rows(spec, project));+ }+ apply_access_rows(ctx, &document_id, EntityType::Document, &rows).await?;+ apply_channel_share_rows(+ ctx,+ spec,+ &document_id,+ ShareableItemType::Document,+ &task.share,+ )+ .await?;++ let status = task+ .status+ .as_deref()+ .map(system_properties::StatusOption::try_from)+ .transpose()+ .map_err(|e| anyhow::anyhow!("task `{key}`: {e}"))?+ .unwrap_or(system_properties::StatusOption::NotStarted);+ properties::outbound::entity_property_queries::upsert_entity_property(+ &ctx.db.pool(),+ &document_id,+ models_properties::EntityType::Task,+ system_properties::SystemPropertyKey::STATUS_UUID,+ Some(PropertyValue::SelectOption(vec![status.uuid()])),+ )+ .await?;++ let assignees: Vec<&String> = if task.assignees.is_empty() {+ vec![&task.owner]+ } else {+ task.assignees.iter().collect()+ };+ let references = assignees+ .iter()+ .map(|assignee| models_properties::EntityReference {+ entity_id: spec.user_id(assignee),+ entity_type: models_properties::EntityType::User,+ specific_message_id: None,+ })+ .collect();+ properties::outbound::entity_property_queries::upsert_entity_property(+ &ctx.db.pool(),+ &document_id,+ models_properties::EntityType::Task,+ system_properties::SystemPropertyKey::ASSIGNEES_UUID,+ Some(PropertyValue::EntityRef(references)),+ )+ .await?;++ println!(" task `{key}` -> {document_id}");+ }+ Ok(())+}++async fn seed_chats(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.chats.is_empty() {+ return Ok(());+ }+ println!("Seeding {} chats", spec.chats.len());++ for (key, chat) in &spec.chats {+ let chat_id = spec.chat_id(key);+ let owner_id = spec.user_id(&chat.owner);+ let name = chat.name.as_deref().unwrap_or(key);++ ctx.db.insert_chat(&chat_id, &owner_id, name).await?;++ let mut rows = vec![AccessRow {+ source_id: owner_id.clone(),+ source_type: EntityAccessSourceType::User,+ access_level: AccessLevel::Owner,+ granted_from_project_id: None,+ }];+ rows.extend(chat.share.iter().map(|s| share_to_row(spec, s)));+ apply_access_rows(ctx, &chat_id, EntityType::Chat, &rows).await?;++ if let Some(level) = chat.public {+ ctx.db+ .create_chat_public_permission(+ &chat_id,+ &share_permission(spec, &chat.owner, level),+ )+ .await?;+ }+ apply_channel_share_rows(ctx, spec, &chat_id, ShareableItemType::Chat, &chat.share).await?;++ println!(" chat `{key}` -> {chat_id}");+ }+ Ok(())+}++async fn seed_calls(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.calls.is_empty() {+ return Ok(());+ }+ println!("Seeding {} calls", spec.calls.len());++ for (index, (key, call)) in spec.calls.iter().enumerate() {+ let call_id = spec.call_id(key);+ let channel_id = spec.channel_id(&call.channel);+ let creator_id = spec.user_id(&call.created_by);+ let share_permission_id =+ super::spec::derive_id(&spec.scenario, "call_share_permission", key);++ let duration = Duration::minutes(i64::from(call.duration_minutes.unwrap_or(15)));+ let ended_at = Utc::now()+ - Duration::minutes(i64::from(+ call.ended_minutes_ago.unwrap_or((index as u32 + 1) * 30),+ ));+ let started_at = ended_at - duration;++ let creator_team = if call.share_with_team {+ spec.team_of(&call.created_by)+ .map(|team| spec.team_id(team))+ } else {+ None+ };++ let participants: Vec<(String, DateTime<Utc>, DateTime<Utc>)> = spec+ .call_participants(key)+ .iter()+ .map(|participant| (spec.user_id(participant), started_at, ended_at))+ .collect();++ let segment_count = call.transcript.len().max(1) as i64;+ let segment_length = duration / (segment_count as i32);+ let transcripts: Vec<(String, String, DateTime<Utc>, DateTime<Utc>)> = call+ .transcript+ .iter()+ .enumerate()+ .map(|(i, segment)| {+ let seg_start = started_at + segment_length * (i as i32);+ (+ spec.user_id(&segment.speaker),+ segment.text.clone(),+ seg_start,+ seg_start + segment_length,+ )+ })+ .collect();++ ctx.db+ .insert_call_record(crate::service::db::InsertCallRecordArgs {+ call_id,+ channel_id,+ room_name: format!("seed-{}-{key}", spec.scenario),+ created_by: creator_id.clone(),+ started_at,+ ended_at,+ share_permission_id: share_permission_id.to_string(),+ share_with_team: call.share_with_team,+ custom_name: call.name.clone(),+ team_id: creator_team,+ participants,+ transcripts,+ })+ .await?;++ println!(" call `{key}` -> {call_id}");+ }+ Ok(())+}++async fn seed_emails(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.emails.is_empty() {+ return Ok(());+ }+ println!("Seeding {} inboxes", spec.emails.len());+ let now = Utc::now();++ for (key, account) in &spec.emails {+ let owner = &spec.users[&account.owner];+ let address = account+ .address+ .clone()+ .unwrap_or_else(|| owner.email.clone());+ let link_id = spec.email_link_id(key);++ let macro_id = MacroUserIdStr::parse_from_str(spec.user_id(&account.owner).leak())+ .context("valid inbox owner id")?;+ let email_str = macro_user_id::email::EmailStr::try_from(address.clone())+ .map_err(|e| anyhow::anyhow!("invalid inbox address {address}: {e:?}"))?;+ let is_primary = Link::derive_is_primary(¯o_id, &email_str);++ let link = ctx+ .db+ .upsert_email_link(Link {+ id: link_id,+ macro_id,+ fusionauth_user_id: spec.user_id(&account.owner),+ email_address: email_str,+ provider: UserProvider::Gmail,+ is_sync_active: true,+ is_primary,+ needs_reauth: false,+ last_sync_error_at: None,+ created_at: now,+ updated_at: now,+ })+ .await?;++ let labels: Vec<Label> = EMAIL_SYSTEM_LABELS+ .iter()+ .map(|id| Label {+ id: None,+ link_id: link.id,+ provider_label_id: (*id).to_string(),+ name: Some((*id).to_string()),+ created_at: now,+ message_list_visibility: Some(MessageListVisibility::Show),+ label_list_visibility: Some(LabelListVisibility::LabelShow),+ type_: Some(LabelType::System),+ })+ .collect();+ ctx.db.insert_email_labels(labels).await?;++ for (thread_index, (thread_key, thread_spec)) in account.threads.iter().enumerate() {+ let thread = build_thread(+ spec,+ key,+ thread_key,+ thread_spec,+ link.id,+ &address,+ now - Duration::minutes(i64::from(+ thread_spec+ .sent_minutes_ago+ .unwrap_or((thread_index as u32 + 1) * 60),+ )),+ );+ let thread_id = thread.db_id.to_string();+ ctx.db.insert_email_thread(thread, link.id).await?;++ let rows: Vec<AccessRow> = thread_spec+ .share+ .iter()+ .map(|s| share_to_row(spec, s))+ .collect();+ apply_access_rows(ctx, &thread_id, EntityType::EmailThread, &rows).await?;+ println!(" inbox `{key}` thread `{thread_key}` -> {thread_id}");+ }++ for delegate in &account.delegated_to {+ ctx.db+ .insert_macro_user_link(+ &spec.user_id(delegate),+ &spec.user_id(&account.owner),+ link.id,+ )+ .await?;+ println!(" inbox `{key}` delegated to `{delegate}`");+ }+ }+ Ok(())+}++#[allow(clippy::too_many_arguments)]+fn build_thread(+ spec: &ScenarioSpec,+ account_key: &str,+ thread_key: &str,+ thread_spec: &super::spec::EmailThreadSpec,+ link_id: Uuid,+ owner_address: &str,+ sent_at: DateTime<Utc>,+) -> Thread {+ let thread_id = spec.email_thread_id(account_key, thread_key);+ let message_id = spec.email_message_id(account_key, thread_key);+ let provider_id = format!("seed-{}-{account_key}-{thread_key}", spec.scenario);++ let from_address = thread_spec+ .from+ .clone()+ .unwrap_or_else(|| "[email protected]".to_string());+ let body_text = thread_spec.body.clone().unwrap_or_else(|| {+ format!(+ "{}\n\n(seeded by scenario `{}`)",+ thread_spec.subject, spec.scenario+ )+ });+ let snippet: String = body_text.chars().take(100).collect();++ let mut label_ids = vec!["INBOX".to_string(), "CATEGORY_PERSONAL".to_string()];+ if thread_spec.unread {+ label_ids.push("UNREAD".to_string());+ }+ let labels: Vec<Label> = label_ids+ .iter()+ .map(|lid| Label {+ id: None,+ link_id,+ provider_label_id: lid.clone(),+ name: Some(lid.clone()),+ created_at: sent_at,+ message_list_visibility: None,+ label_list_visibility: None,+ type_: None,+ })+ .collect();++ let message = Message {+ db_id: message_id,+ provider_id: Some(format!("{provider_id}-m0")),+ thread_db_id: thread_id,+ provider_thread_id: Some(provider_id.clone()),+ replying_to_id: None,+ global_id: None,+ link_id,+ subject: Some(thread_spec.subject.clone()),+ snippet: Some(snippet),+ provider_history_id: None,+ internal_date_ts: Some(sent_at),+ sent_at: Some(sent_at),+ size_estimate: None,+ is_read: !thread_spec.unread,+ is_starred: false,+ is_sent: false,+ is_draft: false,+ scheduled_send_time: None,+ has_attachments: false,+ from: Some(ContactInfo {+ email: from_address,+ name: None,+ photo_url: None,+ }),+ to: vec![ContactInfo {+ email: owner_address.to_string(),+ name: None,+ photo_url: None,+ }],+ cc: vec![],+ bcc: vec![],+ labels,+ body_text: Some(body_text.clone()),+ body_html_sanitized: Some(format!("<p>{body_text}</p>")),+ body_macro: None,+ attachments: vec![],+ attachments_draft: vec![],+ attachments_forwarded: vec![],+ headers_json: None,+ created_at: sent_at,+ updated_at: sent_at,+ };++ Thread {+ db_id: thread_id,+ provider_id: Some(provider_id),+ link_id,+ inbox_visible: true,+ is_read: !thread_spec.unread,+ latest_inbound_message_ts: Some(sent_at),+ latest_outbound_message_ts: None,+ latest_non_spam_message_ts: Some(sent_at),+ created_at: sent_at,+ updated_at: sent_at,+ messages: vec![message],+ }+}++async fn seed_messages(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ if spec.messages.is_empty() {+ return Ok(());+ }+ println!("Seeding {} messages", spec.messages.len());++ for (index, message) in spec.messages.iter().enumerate() {+ let channel_id = spec.channel_id(&message.channel);+ let message_id = ctx+ .db+ .seed_message(SeedMessageOptions {+ message_id: spec.message_id(index),+ channel_id,+ sender_id: spec.user_id(&message.from),+ content: message.text.clone(),+ thread_id: None,+ })+ .await?;++ println!(" message #{index} in `{}`", message.channel);+ if message.mentions.is_empty() {+ continue;+ }++ let mentions: Vec<SimpleMention> = message+ .mentions+ .iter()+ .map(|mention| {+ let (entity_type, entity_id) = match EntityRef::parse(mention).expect("validated") {+ EntityRef::User(user) => ("user", spec.user_id(&user)),+ EntityRef::Document(doc) => ("document", spec.document_id(&doc)),+ EntityRef::Project(project) => ("project", spec.project_id(&project)),+ EntityRef::Chat(chat) => ("chat", spec.chat_id(&chat)),+ EntityRef::Call(call) => ("call", spec.call_id(&call).to_string()),+ other => unreachable!("validated mention, got {other:?}"),+ };+ SimpleMention {+ entity_id,+ entity_type: entity_type.to_string(),+ }+ })+ .collect();++ ctx.db+ .create_message_mentions(message_id, mentions.clone())+ .await?;++ for mention in &mentions {+ if mention.entity_type == "user"+ || ShareableItemType::from_str(&mention.entity_type).is_err()+ {+ continue;+ }+ ctx.db+ .upsert_channel_share_permission(+ &mention.entity_id,+ &mention.entity_type,+ &channel_id.to_string(),+ AccessLevel::View,+ )+ .await?;+ }+ }+ Ok(())+}++/// Map a `BTreeMap` share list into level lookups for matrix expectations.+pub(super) fn max_level(+ current: &mut BTreeMap<String, AccessLevel>,+ user: &str,+ level: AccessLevel,+) {+ current+ .entry(user.to_string())+ .and_modify(|existing| {+ if level > *existing {+ *existing = level;+ }+ })+ .or_insert(level);+}diff --git a/tooling/seed_cli/src/entity/scenario/matrix.rs b/tooling/seed_cli/src/entity/scenario/matrix.rsnew file mode 100644index 0000000000..2ca790231b--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/matrix.rs@@ -0,0 +1,357 @@+//! Matrix: the scenario's expected access matrix, verified against the real+//! authorization service.+//!+//! Expected levels are computed purely from the config; actual levels come+//! from `entity_access`'s domain service running over the local database —+//! the same code production uses — so a mismatch means either the seeder or+//! the access model changed.++#[cfg(test)]+mod test;++use std::collections::BTreeMap;++use entity_access::domain::ports::EntityAccessService;+use entity_access::domain::service::EntityAccessServiceImpl;+use entity_access::outbound::PgAccessRepository;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use models_permissions::share_permission::access_level::AccessLevel;++use super::apply;+use super::spec::{ScenarioSpec, ShareLevel};++/// One row of the matrix: an entity and the level each user should have.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ExpectedRow {+ /// `kind:key` label of the entity.+ pub label: String,+ /// Entity id as text (what the access service is asked about).+ pub entity_id: String,+ /// Entity type for the access service.+ pub entity_type: EntityType,+ /// Expected level per user key; absent means no access.+ pub levels: BTreeMap<String, AccessLevel>,+}++fn share_level_to_access(level: ShareLevel) -> AccessLevel {+ match level {+ ShareLevel::View => AccessLevel::View,+ ShareLevel::Comment => AccessLevel::Comment,+ ShareLevel::Edit => AccessLevel::Edit,+ }+}++/// The channel/team/user source ids a user resolves to, as text.+fn user_sources(spec: &ScenarioSpec, user_key: &str) -> Vec<String> {+ let mut sources = vec![spec.user_id(user_key)];+ if let Some(team) = spec.team_of(user_key) {+ sources.push(spec.team_id(team).to_string());+ }+ for channel_key in spec.channels.keys() {+ if spec+ .channel_members(channel_key)+ .contains(&user_key.to_string())+ {+ sources.push(spec.channel_id(channel_key).to_string());+ }+ }+ sources+}++fn levels_from_rows(+ spec: &ScenarioSpec,+ rows: &[apply::AccessRow],+ public: Option<ShareLevel>,+) -> BTreeMap<String, AccessLevel> {+ let mut levels: BTreeMap<String, AccessLevel> = BTreeMap::new();+ for user_key in spec.users.keys() {+ let sources = user_sources(spec, user_key);+ for row in rows {+ if sources.contains(&row.source_id) {+ apply::max_level(&mut levels, user_key, row.access_level);+ }+ }+ if let Some(level) = public {+ apply::max_level(&mut levels, user_key, share_level_to_access(level));+ }+ }+ levels+}++fn owner_row(spec: &ScenarioSpec, owner_key: &str) -> apply::AccessRow {+ apply::AccessRow {+ source_id: spec.user_id(owner_key),+ source_type: entity_access_db_utils::EntityAccessSourceType::User,+ access_level: AccessLevel::Owner,+ granted_from_project_id: None,+ }+}++/// Channel view rows granted by message mentions of `kind:key`, mirroring+/// the mention-sharing that seeding messages performs.+fn mention_channel_rows(spec: &ScenarioSpec, kind: &str, key: &str) -> Vec<apply::AccessRow> {+ let reference = format!("{kind}:{key}");+ spec.messages+ .iter()+ .filter(|message| message.mentions.contains(&reference))+ .map(|message| apply::AccessRow {+ source_id: spec.channel_id(&message.channel).to_string(),+ source_type: entity_access_db_utils::EntityAccessSourceType::Channel,+ access_level: AccessLevel::View,+ granted_from_project_id: None,+ })+ .collect()+}++/// Compute the full expected matrix for a scenario.+pub fn expected_matrix(spec: &ScenarioSpec) -> Vec<ExpectedRow> {+ let mut rows = Vec::new();++ for channel_key in spec.channels.keys() {+ let mut levels = BTreeMap::new();+ for user_key in spec.users.keys() {+ if spec.channel_members(channel_key).contains(user_key) {+ levels.insert(user_key.clone(), AccessLevel::View);+ }+ }+ rows.push(ExpectedRow {+ label: format!("channel:{channel_key}"),+ entity_id: spec.channel_id(channel_key).to_string(),+ entity_type: EntityType::Channel,+ levels,+ });+ }++ for (project_key, project) in &spec.projects {+ let mut access_rows = apply::project_direct_rows(spec, project_key);+ if let Some(parent) = project.parent.as_deref() {+ access_rows.extend(apply::inherited_rows(spec, parent));+ }+ access_rows.extend(mention_channel_rows(spec, "project", project_key));+ rows.push(ExpectedRow {+ label: format!("project:{project_key}"),+ entity_id: spec.project_id(project_key),+ entity_type: EntityType::Project,+ levels: levels_from_rows(spec, &access_rows, project.public),+ });+ }++ for (document_key, document) in &spec.documents {+ let mut access_rows = vec![owner_row(spec, &document.owner)];+ access_rows.extend(document.share.iter().map(|s| apply::share_to_row(spec, s)));+ if let Some(project) = document.project.as_deref() {+ access_rows.extend(apply::inherited_rows(spec, project));+ }+ access_rows.extend(mention_channel_rows(spec, "document", document_key));+ rows.push(ExpectedRow {+ label: format!("document:{document_key}"),+ entity_id: spec.document_id(document_key),+ entity_type: EntityType::Document,+ levels: levels_from_rows(spec, &access_rows, document.public),+ });+ }++ for (task_key, task) in &spec.tasks {+ let mut access_rows = vec![owner_row(spec, &task.owner)];+ access_rows.extend(task.share.iter().map(|s| apply::share_to_row(spec, s)));+ if task.share_with_team+ && let Some(team) = spec.team_of(&task.owner)+ {+ access_rows.push(apply::AccessRow {+ source_id: spec.team_id(team).to_string(),+ source_type: entity_access_db_utils::EntityAccessSourceType::Team,+ access_level: AccessLevel::Comment,+ granted_from_project_id: None,+ });+ }+ if let Some(project) = task.project.as_deref() {+ access_rows.extend(apply::inherited_rows(spec, project));+ }+ rows.push(ExpectedRow {+ label: format!("task:{task_key}"),+ entity_id: spec.task_id(task_key),+ entity_type: EntityType::Document,+ levels: levels_from_rows(spec, &access_rows, None),+ });+ }++ for (chat_key, chat) in &spec.chats {+ let mut access_rows = vec![owner_row(spec, &chat.owner)];+ access_rows.extend(chat.share.iter().map(|s| apply::share_to_row(spec, s)));+ access_rows.extend(mention_channel_rows(spec, "chat", chat_key));+ rows.push(ExpectedRow {+ label: format!("chat:{chat_key}"),+ entity_id: spec.chat_id(chat_key),+ entity_type: EntityType::Chat,+ levels: levels_from_rows(spec, &access_rows, chat.public),+ });+ }++ for (call_key, call) in &spec.calls {+ let mut access_rows = vec![+ owner_row(spec, &call.created_by),+ apply::AccessRow {+ source_id: spec.channel_id(&call.channel).to_string(),+ source_type: entity_access_db_utils::EntityAccessSourceType::Channel,+ access_level: AccessLevel::Edit,+ granted_from_project_id: None,+ },+ ];+ if call.share_with_team+ && let Some(team) = spec.team_of(&call.created_by)+ {+ access_rows.push(apply::AccessRow {+ source_id: spec.team_id(team).to_string(),+ source_type: entity_access_db_utils::EntityAccessSourceType::Team,+ access_level: AccessLevel::View,+ granted_from_project_id: None,+ });+ }+ access_rows.extend(mention_channel_rows(spec, "call", call_key));+ rows.push(ExpectedRow {+ label: format!("call:{call_key}"),+ entity_id: spec.call_id(call_key).to_string(),+ entity_type: EntityType::Call,+ levels: levels_from_rows(spec, &access_rows, None),+ });+ }++ for (account_key, account) in &spec.emails {+ for (thread_key, thread) in &account.threads {+ let mut levels: BTreeMap<String, AccessLevel> = BTreeMap::new();+ levels.insert(account.owner.clone(), AccessLevel::Owner);+ for delegate in &account.delegated_to {+ levels.insert(delegate.clone(), AccessLevel::Owner);+ }+ let share_rows: Vec<apply::AccessRow> = thread+ .share+ .iter()+ .map(|s| apply::share_to_row(spec, s))+ .collect();+ for (user, level) in levels_from_rows(spec, &share_rows, None) {+ apply::max_level(&mut levels, &user, level);+ }+ rows.push(ExpectedRow {+ label: format!("email:{account_key}/{thread_key}"),+ entity_id: spec.email_thread_id(account_key, thread_key).to_string(),+ entity_type: EntityType::EmailThread,+ levels,+ });+ }+ }++ rows+}++fn level_cell(level: Option<AccessLevel>) -> &'static str {+ match level {+ Some(AccessLevel::Owner) => "owner",+ Some(AccessLevel::Edit) => "edit",+ Some(AccessLevel::Comment) => "comment",+ Some(AccessLevel::View) => "view",+ None => "-",+ }+}++/// Verify the expected matrix against the live database and print the diff.+/// Returns the number of mismatched cells.+pub async fn verify(pool: sqlx::PgPool, spec: &ScenarioSpec) -> anyhow::Result<usize> {+ let service = EntityAccessServiceImpl::new(PgAccessRepository::new(pool));+ let expected = expected_matrix(spec);+ let user_keys: Vec<&String> = spec.users.keys().collect();++ let mut user_ids = BTreeMap::new();+ for user_key in &user_keys {+ let user_id = spec.user_id(user_key);+ let parsed = MacroUserIdStr::parse_from_str(user_id.clone().leak())+ .map_err(|e| anyhow::anyhow!("invalid user id {user_id}: {e:?}"))?;+ user_ids.insert((*user_key).clone(), parsed);+ }++ let label_width = expected+ .iter()+ .map(|row| row.label.len())+ .chain(std::iter::once(spec.scenario.len()))+ .max()+ .unwrap_or(8)+ .max(8);+ let col_width = user_keys+ .iter()+ .map(|k| k.len())+ .max()+ .unwrap_or(5)+ .max("comment≠comment".len());++ let mut header = format!("{:label_width$}", spec.scenario);+ for user_key in &user_keys {+ header.push_str(&format!(" | {user_key:col_width$}"));+ }+ println!("{header}");+ println!("{}", "-".repeat(header.len()));++ let mut mismatches = 0usize;+ for row in &expected {+ let mut line = format!("{:label_width$}", row.label);+ for user_key in &user_keys {+ let parsed = &user_ids[*user_key];+ let actual = service+ .get_access_level(Some(&**parsed), &row.entity_id, row.entity_type)+ .await+ .map_err(|e| anyhow::anyhow!("access check failed for {}: {e}", row.label))?;+ let expected_level = row.levels.get(*user_key).copied();++ let cell = if actual == expected_level {+ level_cell(expected_level).to_string()+ } else {+ mismatches += 1;+ format!("{}≠{}", level_cell(expected_level), level_cell(actual))+ };+ line.push_str(&format!(" | {cell:col_width$}"));+ }+ println!("{line}");+ }++ if mismatches == 0 {+ println!(+ "\nAll {} entities match the expected access matrix.",+ expected.len()+ );+ } else {+ println!(+ "\n{mismatches} cell(s) differ from the expected matrix (shown as expected≠actual)."+ );+ }+ Ok(mismatches)+}++/// Print the expected matrix without touching the database.+pub fn print_expected(spec: &ScenarioSpec) {+ let expected = expected_matrix(spec);+ let user_keys: Vec<&String> = spec.users.keys().collect();++ let label_width = expected+ .iter()+ .map(|row| row.label.len())+ .max()+ .unwrap_or(8)+ .max(8);+ let col_width = user_keys.iter().map(|k| k.len()).max().unwrap_or(5).max(7);++ let mut header = format!("{:label_width$}", spec.scenario);+ for user_key in &user_keys {+ header.push_str(&format!(" | {user_key:col_width$}"));+ }+ println!("{header}");+ println!("{}", "-".repeat(header.len()));+ for row in &expected {+ let mut line = format!("{:label_width$}", row.label);+ for user_key in &user_keys {+ line.push_str(&format!(+ " | {:col_width$}",+ level_cell(row.levels.get(*user_key).copied())+ ));+ }+ println!("{line}");+ }+}diff --git a/tooling/seed_cli/src/entity/scenario/matrix/test.rs b/tooling/seed_cli/src/entity/scenario/matrix/test.rsnew file mode 100644index 0000000000..d17f20c760--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/matrix/test.rs@@ -0,0 +1,241 @@+use models_permissions::share_permission::access_level::AccessLevel;++use super::*;++fn example() -> ScenarioSpec {+ let path =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("seed/scenarios/team-perms.json");+ let content = std::fs::read_to_string(path).expect("example scenario file exists");+ ScenarioSpec::parse(&content).expect("example scenario is valid")+}++fn row<'a>(rows: &'a [ExpectedRow], label: &str) -> &'a ExpectedRow {+ rows.iter()+ .find(|row| row.label == label)+ .unwrap_or_else(|| panic!("row {label} exists"))+}++fn level(rows: &[ExpectedRow], label: &str, user: &str) -> Option<AccessLevel> {+ row(rows, label).levels.get(user).copied()+}++#[test]+fn expected_matrix_covers_owner_team_channel_public_edges() {+ let spec = example();+ let rows = expected_matrix(&spec);++ // Documents.+ assert_eq!(+ level(&rows, "document:q3-plan", "alice"),+ Some(AccessLevel::Owner)+ );+ // bob and carol inherit view through the project's team share.+ assert_eq!(+ level(&rows, "document:q3-plan", "bob"),+ Some(AccessLevel::View)+ );+ assert_eq!(+ level(&rows, "document:q3-plan", "carol"),+ Some(AccessLevel::View)+ );+ assert_eq!(level(&rows, "document:q3-plan", "dave"), None);+ assert_eq!(level(&rows, "document:q3-plan", "eve"), None);++ // design-doc: dave has a direct edit share; channel share + mention give+ // eng members view; carol/eve see nothing.+ assert_eq!(+ level(&rows, "document:design-doc", "dave"),+ Some(AccessLevel::Edit)+ );+ assert_eq!(+ level(&rows, "document:design-doc", "bob"),+ Some(AccessLevel::View)+ );+ assert_eq!(level(&rows, "document:design-doc", "carol"), None);+ assert_eq!(level(&rows, "document:design-doc", "eve"), None);++ // Public document is visible to everyone.+ for user in ["alice", "bob", "carol", "dave", "eve"] {+ assert!(level(&rows, "document:handbook", user).is_some(), "{user}");+ }+ assert_eq!(+ level(&rows, "document:handbook", "eve"),+ Some(AccessLevel::View)+ );++ // Unshared document stays private.+ assert_eq!(+ level(&rows, "document:bob-notes", "bob"),+ Some(AccessLevel::Owner)+ );+ for user in ["alice", "carol", "dave", "eve"] {+ assert_eq!(level(&rows, "document:bob-notes", user), None, "{user}");+ }++ // Chats.+ assert_eq!(+ level(&rows, "chat:alice-ai", "carol"),+ Some(AccessLevel::View)+ );+ assert_eq!(level(&rows, "chat:alice-ai", "bob"), None);++ // Calls: channel members get edit, the creator's team gets view.+ assert_eq!(+ level(&rows, "call:eng-standup", "alice"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(+ level(&rows, "call:eng-standup", "bob"),+ Some(AccessLevel::Edit)+ );+ assert_eq!(+ level(&rows, "call:eng-standup", "carol"),+ Some(AccessLevel::View)+ );+ assert_eq!(+ level(&rows, "call:eng-standup", "dave"),+ Some(AccessLevel::Edit)+ );+ assert_eq!(level(&rows, "call:eng-standup", "eve"), None);++ // dave created dm-huddle but has no team, so no team share exists.+ assert_eq!(+ level(&rows, "call:dm-huddle", "dave"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(+ level(&rows, "call:dm-huddle", "alice"),+ Some(AccessLevel::Edit)+ );+ assert_eq!(level(&rows, "call:dm-huddle", "bob"), None);++ // Email: owner and delegate both act as owners; nobody else sees it.+ assert_eq!(+ level(&rows, "email:alice-inbox/welcome", "alice"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(+ level(&rows, "email:alice-inbox/welcome", "bob"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(level(&rows, "email:alice-inbox/welcome", "carol"), None);++ // Channels resolve to view for active participants only.+ assert_eq!(level(&rows, "channel:eng", "dave"), Some(AccessLevel::View));+ assert_eq!(level(&rows, "channel:eng", "carol"), None);+ assert_eq!(+ level(&rows, "channel:acme-hq", "carol"),+ Some(AccessLevel::View)+ );+ assert_eq!(level(&rows, "channel:acme-hq", "dave"), None);+}++#[test]+fn mentions_grant_channel_view_to_projects_and_calls() {+ let spec = ScenarioSpec::parse(+ &serde_json::json!({+ "scenario": "mention-check",+ "users": {+ "owner": { "email": "[email protected]" },+ "peer": { "email": "[email protected]" },+ "member": { "email": "[email protected]" }+ },+ "channels": {+ "dm": { "type": "direct_message", "members": ["owner", "peer"] },+ "room": { "type": "private", "owner": "owner", "members": ["member"] }+ },+ "projects": { "plans": { "owner": "owner" } },+ "calls": { "huddle": { "channel": "dm", "created_by": "owner" } },+ "messages": [+ { "channel": "room", "from": "owner", "text": "fyi",+ "mentions": ["project:plans", "call:huddle"] }+ ]+ })+ .to_string(),+ )+ .unwrap();+ let rows = expected_matrix(&spec);++ // `member` is only in `room`; the mentions there grant view on both the+ // project and the call, mirroring what seeding the message does.+ assert_eq!(+ level(&rows, "project:plans", "member"),+ Some(AccessLevel::View)+ );+ assert_eq!(+ level(&rows, "call:huddle", "member"),+ Some(AccessLevel::View)+ );++ // The call's own channel keeps edit; the mention's view doesn't lower it.+ assert_eq!(level(&rows, "call:huddle", "peer"), Some(AccessLevel::Edit));+ assert_eq!(+ level(&rows, "call:huddle", "owner"),+ Some(AccessLevel::Owner)+ );++ // `peer` isn't in `room`, so the mention grants them nothing.+ assert_eq!(level(&rows, "project:plans", "peer"), None);+}++#[test]+fn expected_matrix_row_count_matches_entities() {+ let spec = example();+ let rows = expected_matrix(&spec);+ let email_threads: usize = spec.emails.values().map(|a| a.threads.len()).sum();+ let expected = spec.channels.len()+ + spec.projects.len()+ + spec.documents.len()+ + spec.tasks.len()+ + spec.chats.len()+ + spec.calls.len()+ + email_threads;+ assert_eq!(rows.len(), expected);+}++#[test]+fn task_expectations_cover_team_share_and_inheritance() {+ let spec = example();+ let rows = expected_matrix(&spec);++ // ship-tags: alice owns it; the team gets comment via share_with_team;+ // the project's team view is subsumed by comment; dave/eve see nothing.+ assert_eq!(+ level(&rows, "task:ship-tags", "alice"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(+ level(&rows, "task:ship-tags", "bob"),+ Some(AccessLevel::Comment)+ );+ assert_eq!(+ level(&rows, "task:ship-tags", "carol"),+ Some(AccessLevel::Comment)+ );+ assert_eq!(level(&rows, "task:ship-tags", "dave"), None);+ assert_eq!(level(&rows, "task:ship-tags", "eve"), None);++ // fix-perms: dave's personal task shared to the eng channel; assigning+ // alice grants nothing by itself — her view comes from the channel.+ assert_eq!(+ level(&rows, "task:fix-perms", "dave"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(+ level(&rows, "task:fix-perms", "alice"),+ Some(AccessLevel::View)+ );+ assert_eq!(level(&rows, "task:fix-perms", "carol"), None);++ // write-docs: alice owns it, carol is the assignee and sees it through+ // the team share.+ assert_eq!(+ level(&rows, "task:write-docs", "alice"),+ Some(AccessLevel::Owner)+ );+ assert_eq!(+ level(&rows, "task:write-docs", "carol"),+ Some(AccessLevel::Comment)+ );+ assert_eq!(level(&rows, "task:write-docs", "dave"), None);+}diff --git a/tooling/seed_cli/src/entity/scenario/mod.rs b/tooling/seed_cli/src/entity/scenario/mod.rsindex 61dc8c8894..144e73c256 100644--- a/tooling/seed_cli/src/entity/scenario/mod.rs+++ b/tooling/seed_cli/src/entity/scenario/mod.rs@@ -1,5 +1,11 @@//! Predefined seed scenarios for local development and e2e tests.+pub mod apply;+pub mod matrix;+pub mod reset;+pub mod spec;+pub mod status;+use std::path::{Path, PathBuf};use anyhow::{Context, ensure};@@ -192,11 +198,64 @@ pub struct ScenarioArgs {pub command: ScenarioCommand,}+/// Arguments for applying a scenario config file.+#[derive(Debug, Args)]+pub struct ApplyScenarioArgs {+ /// Path to the scenario JSON file.+ #[arg(long)]+ pub file: String,+ /// Drop the local database entirely and re-run migrations before+ /// seeding. Destroys ALL local data, organic included.+ #[arg(long, short = 'f')]+ pub force: bool,+}++/// Arguments for resetting scenario data.+#[derive(Debug, Args)]+pub struct ResetScenarioArgs {+ /// Path to the scenario JSON file whose rows should be deleted.+ #[arg(long, conflicts_with = "all")]+ pub file: Option<String>,+ /// Delete the rows of every scenario (anything carrying the seed marker).+ #[arg(long)]+ pub all: bool,+}++/// Arguments for reporting a scenario's applied state.+#[derive(Debug, Args)]+pub struct StatusScenarioArgs {+ /// Path to a scenario JSON file. Omit to discover every applied+ /// scenario by its id marker.+ #[arg(long)]+ pub file: Option<String>,+}++/// Arguments for printing/verifying a scenario's access matrix.+#[derive(Debug, Args)]+pub struct MatrixScenarioArgs {+ /// Path to the scenario JSON file.+ #[arg(long)]+ pub file: String,+ /// Only print the expected matrix; skip the live database check.+ #[arg(long)]+ pub expected_only: bool,+}+/// Available seed scenarios.#[derive(Debug, Subcommand)]pub enum ScenarioCommand {/// Reset and apply the local Playwright smoke-test fixture data.LocalE2eSmoke,+ /// Apply a scenario config file (resets the scenario's own rows first).+ Apply(ApplyScenarioArgs),+ /// Delete every row a scenario seeded.+ Reset(ResetScenarioArgs),+ /// Print the scenario's expected access matrix and verify it against+ /// the live database.+ Matrix(MatrixScenarioArgs),+ /// Report which of a scenario's rows are present and re-print the+ /// persona login links (read-only).+ Status(StatusScenarioArgs),}impl ScenarioArgs {@@ -206,6 +265,12 @@ impl ScenarioArgs {ScenarioCommand::LocalE2eSmoke => {validate_local_e2e_environment(env_vars.database_url.as_ref())}+ ScenarioCommand::Apply(_) | ScenarioCommand::Reset(_) => {+ validate_scenario_environment(env_vars.database_url.as_ref())+ }+ ScenarioCommand::Matrix(_) | ScenarioCommand::Status(_) => {+ validate_scenario_database_url(env_vars.database_url.as_ref())+ }}}@@ -213,8 +278,158 @@ impl ScenarioArgs {pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {match self.command {ScenarioCommand::LocalE2eSmoke => local_e2e_smoke(&ctx).await,+ ScenarioCommand::Apply(args) => apply_scenario(&ctx, &args).await,+ ScenarioCommand::Reset(args) => reset_scenario(&ctx, &args).await,+ ScenarioCommand::Matrix(args) => matrix_scenario(&ctx, &args).await,+ ScenarioCommand::Status(args) => status_scenario(&ctx, &args).await,}}++ /// Run destructive pre-connection setup (`apply --force` drops and+ /// re-migrates the database) before the CLI opens its connection pool.+ #[allow(clippy::disallowed_methods, reason = "seed-only dynamic SQL")]+ pub async fn pre_connect(&self, database_url: &str) -> anyhow::Result<()> {+ let ScenarioCommand::Apply(args) = &self.command else {+ return Ok(());+ };+ if !args.force {+ return Ok(());+ }++ use sqlx::migrate::MigrateDatabase;++ if !sqlx::Postgres::database_exists(database_url)+ .await+ .unwrap_or(false)+ {+ sqlx::Postgres::create_database(database_url)+ .await+ .context("creating database")?;+ }++ // Reset the schema rather than dropping the database: the running+ // services hold connection pools that reconnect instantly, which+ // makes DROP DATABASE lose its termination race. Dropping the+ // schema wipes every table (and the migrations ledger) while the+ // connections survive.+ println!("--force: resetting the local database schema");+ let pool = sqlx::PgPool::connect(database_url)+ .await+ .context("connecting for schema reset")?;+ for statement in [+ "DROP SCHEMA public CASCADE",+ "CREATE SCHEMA public",+ "GRANT ALL ON SCHEMA public TO PUBLIC",+ ] {+ sqlx::query(statement)+ .execute(&pool)+ .await+ .with_context(|| format!("running `{statement}`"))?;+ }++ println!("--force: running migrations");+ macro_db_migrator::MACRO_DB_MIGRATIONS+ .run(&pool)+ .await+ .context("running migrations")?;+ pool.close().await;+ Ok(())+ }+}++fn load_scenario(file: &str) -> anyhow::Result<spec::ScenarioSpec> {+ let content = std::fs::read_to_string(file)+ .with_context(|| format!("failed to read scenario file: {file}"))?;+ spec::ScenarioSpec::parse(&content)+}++#[tracing::instrument(skip(ctx), err)]+async fn apply_scenario(ctx: &SeedCliContext, args: &ApplyScenarioArgs) -> anyhow::Result<()> {+ let scenario = load_scenario(&args.file)?;+ apply::apply(ctx, &scenario, &seed_path("seed")).await+}++#[tracing::instrument(skip(ctx), err)]+async fn reset_scenario(ctx: &SeedCliContext, args: &ResetScenarioArgs) -> anyhow::Result<()> {+ let (marker, emails) = if args.all {+ (spec::SEED_MARKER.to_string(), Vec::new())+ } else {+ let file = args+ .file+ .as_deref()+ .context("pass --file <scenario.json> or --all")?;+ let scenario = load_scenario(file)?;+ let emails = scenario+ .users+ .values()+ .map(|user| user.email.clone())+ .collect();+ (spec::scenario_marker(&scenario.scenario), emails)+ };++ println!("Deleting seeded rows with marker {marker}");+ ctx.db+ .execute_sql_if_table_exists(+ "public.contacts_backfill_outbox",+ &reset::reset_contacts_outbox_statement(&marker),+ )+ .await?;+ let mut statements = reset::reset_statements(&marker);+ statements.extend(reset::reset_user_statements(&emails));+ ctx.db.execute_statements(&statements).await?;+ println!("Done.");+ Ok(())+}++#[tracing::instrument(skip(ctx), err)]+async fn matrix_scenario(ctx: &SeedCliContext, args: &MatrixScenarioArgs) -> anyhow::Result<()> {+ let scenario = load_scenario(&args.file)?;+ if args.expected_only {+ matrix::print_expected(&scenario);+ return Ok(());+ }+ let mismatches = matrix::verify(ctx.db.pool(), &scenario).await?;+ anyhow::ensure!(mismatches == 0, "{mismatches} matrix cell(s) mismatched");+ Ok(())+}++#[tracing::instrument(skip(ctx), err)]+async fn status_scenario(ctx: &SeedCliContext, args: &StatusScenarioArgs) -> anyhow::Result<()> {+ match args.file.as_deref() {+ Some(file) => {+ let scenario = load_scenario(file)?;+ status::report(ctx, &scenario).await+ }+ None => status::discover(ctx, &seed_path("seed").join("scenarios")).await,+ }+}++#[allow(clippy::disallowed_methods, reason = "Only used when running locally")]+fn validate_scenario_environment(database_url: &str) -> anyhow::Result<()> {+ ensure!(+ std::env::var("LOCAL_SEED").as_deref() == Ok("true"),+ "refusing to run scenario seeding without LOCAL_SEED=true"+ );+ validate_scenario_database_url(database_url)+}++/// Like the local-e2e guard, but allows any port so named `run_local`+/// instances work.+fn validate_scenario_database_url(database_url: &str) -> anyhow::Result<()> {+ let parsed = url::Url::parse(database_url).context("DATABASE_URL must be a valid URL")?;+ let host = parsed.host_str().unwrap_or_default();+ let username = parsed.username();+ let database = parsed.path().trim_start_matches('/');++ let is_local_host = matches!(host, "localhost" | "127.0.0.1" | "::1" | "postgres");+ let is_local_db = username == "user" && database == "macrodb";++ ensure!(+ is_local_host && is_local_db,+ "refusing to run scenario seeding against DATABASE_URL host={host:?} user={username:?} database={database:?}; expected the local docker database postgres://user:...@(localhost|127.0.0.1|postgres):<port>/macrodb"+ );++ Ok(())}#[allow(clippy::disallowed_methods, reason = "Only used when running locally")]diff --git a/tooling/seed_cli/src/entity/scenario/reset.rs b/tooling/seed_cli/src/entity/scenario/reset.rsnew file mode 100644index 0000000000..893e03b2b9--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/reset.rs@@ -0,0 +1,119 @@+//! Reset: delete every row a scenario seeded, keyed by the id marker prefix.+//!+//! Every seeded uuid starts with `5eed` + a 4-hex-char scenario hash, so a+//! scenario's rows are exactly the ones matching `LIKE '5eed<scen>%'` (and+//! `LIKE '5eed%'` matches every scenario). Rows the seeder creates with+//! database-generated ids (`SharePermission` and its join tables) are found+//! through their join to a marked entity instead.++#[cfg(test)]+mod test;++/// Build the ordered list of delete statements for a marker prefix.+///+/// The marker must be `5eed` (all scenarios) or `5eed` + 4 hex chars (one+/// scenario); it is interpolated into `LIKE` patterns.+pub fn reset_statements(marker: &str) -> Vec<String> {+ let m = format!("{marker}%");++ vec![+ // SharePermission rows are DB-generated ids; collect them via their+ // join rows to marked entities, delete the joins, then the+ // permissions. Calls are excluded: a call_records delete trigger+ // removes its own SharePermission.+ format!(+ r#"WITH sp_ids AS (+ SELECT dp."sharePermissionId" AS id FROM "DocumentPermission" dp WHERE dp."documentId" LIKE '{m}'+ UNION SELECT cp."sharePermissionId" FROM "ChatPermission" cp WHERE cp."chatId" LIKE '{m}'+ UNION SELECT pp."sharePermissionId" FROM "ProjectPermission" pp WHERE pp."projectId" LIKE '{m}'+ UNION SELECT tp."sharePermissionId" FROM "EmailThreadPermission" tp WHERE tp."threadId" LIKE '{m}'+),+del_document_permissions AS (+ DELETE FROM "DocumentPermission" WHERE "documentId" LIKE '{m}'+),+del_chat_permissions AS (+ DELETE FROM "ChatPermission" WHERE "chatId" LIKE '{m}'+),+del_project_permissions AS (+ DELETE FROM "ProjectPermission" WHERE "projectId" LIKE '{m}'+),+del_email_thread_permissions AS (+ DELETE FROM "EmailThreadPermission" WHERE "threadId" LIKE '{m}'+),+del_channel_share_permissions AS (+ DELETE FROM "ChannelSharePermission"+ WHERE share_permission_id IN (SELECT id FROM sp_ids) OR channel_id LIKE '{m}'+)+DELETE FROM "SharePermission" WHERE id IN (SELECT id FROM sp_ids)"#+ ),+ format!(+ "DELETE FROM entity_access WHERE entity_id::text LIKE '{m}' OR source_id LIKE '{m}'"+ ),+ format!("DELETE FROM entity_properties WHERE entity_id LIKE '{m}'"),+ // Notifications point at seeded items (message notifications carry+ // the channel id); user_notification rows cascade.+ format!("DELETE FROM notification WHERE event_item_id LIKE '{m}'"),+ format!(+ "DELETE FROM comms_entity_mentions WHERE source_entity_id LIKE '{m}' OR entity_id LIKE '{m}'"+ ),+ format!("DELETE FROM comms_activity WHERE channel_id::text LIKE '{m}'"),+ // The call_records delete trigger removes each record's+ // SharePermission; participants and transcripts cascade.+ format!("DELETE FROM call_records WHERE id::text LIKE '{m}'"),+ format!("DELETE FROM calls WHERE id::text LIKE '{m}'"),+ // Participants, messages, attachments, and reactions cascade with+ // the channel.+ format!("DELETE FROM comms_channels WHERE id::text LIKE '{m}'"),+ // Threads, messages, labels, contacts, and macro_user_links cascade+ // with the link.+ format!("DELETE FROM email_links WHERE id::text LIKE '{m}'"),+ format!("DELETE FROM \"Document\" WHERE id LIKE '{m}'"),+ format!("DELETE FROM \"Chat\" WHERE id LIKE '{m}'"),+ format!("DELETE FROM \"Project\" WHERE id LIKE '{m}'"),+ format!("DELETE FROM team_invite WHERE team_id::text LIKE '{m}'"),+ format!("DELETE FROM team_user WHERE team_id::text LIKE '{m}'"),+ // team_crm_settings cascades with the team.+ format!("DELETE FROM team WHERE id::text LIKE '{m}'"),+ format!(+ r#"DELETE FROM "RolesOnUsers" WHERE "userId" IN (SELECT id FROM "User" WHERE "macro_user_id"::text LIKE '{m}')"#+ ),+ format!("DELETE FROM macro_user_email_verification WHERE macro_user_id::text LIKE '{m}'"),+ format!("DELETE FROM macro_user_info WHERE macro_user_id::text LIKE '{m}'"),+ format!(r#"DELETE FROM "User" WHERE "macro_user_id"::text LIKE '{m}'"#),+ format!("DELETE FROM macro_user WHERE id::text LIKE '{m}'"),+ ]+}++/// Statement deleting stale contacts-backfill outbox rows for marked+/// channels. Runs separately because the table only exists once its+/// migration has been applied.+pub fn reset_contacts_outbox_statement(marker: &str) -> String {+ format!("DELETE FROM contacts_backfill_outbox WHERE comms_channel_id::text LIKE '{marker}%'")+}++/// Delete scenario users by email. Needed on top of the marker deletes+/// because accounts created through the signup webhook (so they can log in)+/// carry database-generated ids, not marker-prefixed ones.+pub fn reset_user_statements(emails: &[String]) -> Vec<String> {+ if emails.is_empty() {+ return Vec::new();+ }+ let emails = emails+ .iter()+ .map(|email| format!("'{}'", email.replace('\'', "''")))+ .collect::<Vec<_>>()+ .join(", ");+ let user_ids = format!(r#"SELECT id FROM "User" WHERE email IN ({emails})"#);+ let macro_user_ids = format!("SELECT id FROM macro_user WHERE email IN ({emails})");++ vec![+ format!(r#"DELETE FROM "RolesOnUsers" WHERE "userId" IN ({user_ids})"#),+ format!(+ "DELETE FROM contacts_connections WHERE user1 IN ({user_ids}) OR user2 IN ({user_ids})"+ ),+ format!("DELETE FROM macro_user_email_verification WHERE email IN ({emails})"),+ format!("DELETE FROM macro_user_info WHERE macro_user_id IN ({macro_user_ids})"),+ format!(r#"DELETE FROM "User" WHERE email IN ({emails})"#),+ format!("DELETE FROM macro_user WHERE email IN ({emails})"),+ ]+}diff --git a/tooling/seed_cli/src/entity/scenario/reset/test.rs b/tooling/seed_cli/src/entity/scenario/reset/test.rsnew file mode 100644index 0000000000..068119eabf--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/reset/test.rs@@ -0,0 +1,52 @@+use super::*;++#[test]+fn statements_scope_to_the_marker() {+ let statements = reset_statements("5eedabcd");+ assert!(!statements.is_empty());+ for statement in &statements {+ assert!(+ statement.contains("5eedabcd%"),+ "statement must be marker-scoped: {statement}"+ );+ assert!(+ !statement.contains(';'),+ "statements must be standalone (no embedded semicolons): {statement}"+ );+ }+}++#[test]+fn covers_every_seeded_table() {+ let all = reset_statements("5eed").join("\n");+ for table in [+ "\"SharePermission\"",+ "\"ChannelSharePermission\"",+ "\"DocumentPermission\"",+ "\"ChatPermission\"",+ "\"ProjectPermission\"",+ "\"EmailThreadPermission\"",+ "entity_access",+ "entity_properties",+ "notification",+ "comms_entity_mentions",+ "comms_activity",+ "comms_channels",+ "call_records",+ "calls",+ "email_links",+ "\"Document\"",+ "\"Chat\"",+ "\"Project\"",+ "team_invite",+ "team_user",+ "team",+ "\"RolesOnUsers\"",+ "macro_user_email_verification",+ "macro_user_info",+ "\"User\"",+ "macro_user",+ ] {+ assert!(all.contains(table), "missing table {table}");+ }+}diff --git a/tooling/seed_cli/src/entity/scenario/spec.rs b/tooling/seed_cli/src/entity/scenario/spec.rsnew file mode 100644index 0000000000..c2bce7a47f--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/spec.rs@@ -0,0 +1,991 @@+//! Scenario config model: parsing, deterministic id derivation, and validation.+//!+//! A scenario file declares users, teams, channels, and entities with the+//! access edges between them, keyed by human-readable names. Every seeded row+//! id is derived from `(scenario, kind, key)` and carries the `5eed` marker+//! prefix so re-applying converges and resets can target exactly the seeded+//! rows.++#[cfg(test)]+mod test;++use std::collections::{BTreeMap, BTreeSet};+use std::fmt;++use serde::Deserialize;+use sha2::{Digest, Sha256};+use uuid::Uuid;++/// Marker prefix (hex) carried by every seeded uuid.+pub const SEED_MARKER: &str = "5eed";++/// Access level names accepted in scenario share/public declarations.+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ShareLevel {+ /// Read-only access.+ View,+ /// Read and comment access.+ Comment,+ /// Full edit access.+ Edit,+}++impl fmt::Display for ShareLevel {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ ShareLevel::View => f.write_str("view"),+ ShareLevel::Comment => f.write_str("comment"),+ ShareLevel::Edit => f.write_str("edit"),+ }+ }+}++/// Team role names accepted in scenario team member declarations.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum TeamMemberRole {+ /// Regular team member.+ Member,+ /// Team admin.+ Admin,+}++/// Channel types accepted in scenario channel declarations.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ChannelKind {+ /// Public channel: readable by everyone, joinable.+ Public,+ /// Private channel: participants only.+ Private,+ /// Two-person direct message.+ DirectMessage,+ /// Team channel: membership mirrors the team.+ Team,+}++/// A reference to another scenario object, written as `kind:key`.+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]+pub enum EntityRef {+ /// A user by key.+ User(String),+ /// A team by key.+ Team(String),+ /// A channel by key.+ Channel(String),+ /// A document by key.+ Document(String),+ /// A project by key.+ Project(String),+ /// An AI chat by key.+ Chat(String),+ /// A call record by key.+ Call(String),+}++impl EntityRef {+ /// Parse a `kind:key` reference string.+ pub fn parse(raw: &str) -> Result<Self, String> {+ let (kind, key) = raw+ .split_once(':')+ .ok_or_else(|| format!("reference `{raw}` must look like `kind:key`"))?;+ if key.is_empty() {+ return Err(format!("reference `{raw}` has an empty key"));+ }+ let key = key.to_string();+ match kind {+ "user" => Ok(EntityRef::User(key)),+ "team" => Ok(EntityRef::Team(key)),+ "channel" => Ok(EntityRef::Channel(key)),+ "document" => Ok(EntityRef::Document(key)),+ "project" => Ok(EntityRef::Project(key)),+ "chat" => Ok(EntityRef::Chat(key)),+ "call" => Ok(EntityRef::Call(key)),+ other => Err(format!("reference `{raw}` has unknown kind `{other}`")),+ }+ }+}++/// A single share edge: grant `level` to the principal in `with`.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ShareSpec {+ /// The principal receiving access: `user:x`, `team:x`, or `channel:x`.+ pub with: String,+ /// The level granted.+ pub level: ShareLevel,+}++/// A user in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct UserSpec {+ /// Login email. With `run_local`'s passwordless FusionAuth this account+ /// is immediately log-in-able.+ pub email: String,+ /// First name shown in the app. Defaults to the capitalized key.+ #[serde(default)]+ pub first_name: Option<String>,+ /// Last name shown in the app. Defaults to "Seed".+ #[serde(default)]+ pub last_name: Option<String>,+ /// Extra role rows on top of the default `self_serve`. These drive+ /// feature entitlements like `read:professional_features`, not entity+ /// access. `professional_subscriber` = individually paid;+ /// `team_subscriber` + `sub_opus` = what joining a paying team grants+ /// (production keeps these in lockstep with team membership — the+ /// seeder lets you diverge on purpose).+ #[serde(default)]+ pub roles: Vec<String>,+}++/// A team in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct TeamSpec {+ /// Display name. Defaults to the key.+ #[serde(default)]+ pub name: Option<String>,+ /// Team owner user key. Becomes `team_user` role `owner`.+ pub owner: String,+ /// Members and their roles (the owner is implicit).+ #[serde(default)]+ pub members: BTreeMap<String, TeamMemberRole>,+ /// Whether the team has CRM enabled.+ #[serde(default)]+ pub crm_enabled: bool,+}++/// A channel in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ChannelSpec {+ /// Channel type.+ #[serde(rename = "type")]+ pub kind: ChannelKind,+ /// Display name. Defaults to the key for public/private/team channels;+ /// direct messages are unnamed.+ #[serde(default)]+ pub name: Option<String>,+ /// Owner user key. Required for public/private; derived for team+ /// channels (team owner); for DMs the first member is the owner.+ #[serde(default)]+ pub owner: Option<String>,+ /// Participant user keys (the owner is implicit). For team channels+ /// membership mirrors the team and this must be empty.+ #[serde(default)]+ pub members: Vec<String>,+ /// Backing team key. Required iff `type` is `team`.+ #[serde(default)]+ pub team: Option<String>,+}++/// A project in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ProjectSpec {+ /// Owner user key.+ pub owner: String,+ /// Display name. Defaults to the key.+ #[serde(default)]+ pub name: Option<String>,+ /// Parent project key for nesting.+ #[serde(default)]+ pub parent: Option<String>,+ /// Access grants on the project (inherited by contained entities).+ #[serde(default)]+ pub share: Vec<ShareSpec>,+ /// Public link access level, if the project is public.+ #[serde(default)]+ pub public: Option<ShareLevel>,+}++/// A document in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct DocumentSpec {+ /// Owner user key.+ pub owner: String,+ /// Display name. Defaults to the key.+ #[serde(default)]+ pub name: Option<String>,+ /// File name under `seed/documents/files/` providing the content.+ /// `.md` files are initialized as native sync-service documents; other+ /// extensions upload to object storage. Omit (along with `content`) for+ /// a name-only document row.+ #[serde(default)]+ pub file: Option<String>,+ /// Inline markdown content for a native document. Mutually exclusive+ /// with `file`.+ #[serde(default)]+ pub content: Option<String>,+ /// Project key this document lives in.+ #[serde(default)]+ pub project: Option<String>,+ /// Access grants on the document.+ #[serde(default)]+ pub share: Vec<ShareSpec>,+ /// Public link access level, if the document is public.+ #[serde(default)]+ pub public: Option<ShareLevel>,+}++/// A task in the scenario: a markdown document with the task subtype plus+/// status/assignee properties.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct TaskSpec {+ /// Owner user key.+ pub owner: String,+ /// Display name. Defaults to the key.+ #[serde(default)]+ pub name: Option<String>,+ /// Inline markdown body. Defaults to an empty document.+ #[serde(default)]+ pub content: Option<String>,+ /// Project key this task lives in.+ #[serde(default)]+ pub project: Option<String>,+ /// Status option: `not_started` (default), `in_progress`, `in_review`,+ /// `completed`, or `canceled`.+ #[serde(default)]+ pub status: Option<String>,+ /// Assignee user keys. Defaults to the owner.+ #[serde(default)]+ pub assignees: Vec<String>,+ /// Grant the owner's team comment access, like the app's+ /// share-with-team toggle on tasks.+ #[serde(default)]+ pub share_with_team: bool,+ /// Access grants on the task.+ #[serde(default)]+ pub share: Vec<ShareSpec>,+}++/// An AI chat in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ChatSpec {+ /// Owner user key.+ pub owner: String,+ /// Display name. Defaults to the key.+ #[serde(default)]+ pub name: Option<String>,+ /// Access grants on the chat.+ #[serde(default)]+ pub share: Vec<ShareSpec>,+ /// Public link access level, if the chat is public.+ #[serde(default)]+ pub public: Option<ShareLevel>,+}++/// A transcript segment of a seeded call.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct TranscriptSpec {+ /// Speaking user key (must be a participant).+ pub speaker: String,+ /// What was said.+ pub text: String,+}++/// An archived call record in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct CallSpec {+ /// Channel key the call happened in.+ pub channel: String,+ /// Creator user key (must have access to the channel).+ pub created_by: String,+ /// Grant the creator's team view access (mirrors the app default).+ #[serde(default = "default_true")]+ pub share_with_team: bool,+ /// Participant user keys. Defaults to just the creator.+ #[serde(default)]+ pub participants: Vec<String>,+ /// Call length in minutes. Defaults to 15.+ #[serde(default)]+ pub duration_minutes: Option<u32>,+ /// How long ago the call ended, in minutes. Defaults to staggered+ /// recent times.+ #[serde(default)]+ pub ended_minutes_ago: Option<u32>,+ /// Custom display name for the call record.+ #[serde(default)]+ pub name: Option<String>,+ /// Transcript segments.+ #[serde(default)]+ pub transcript: Vec<TranscriptSpec>,+}++fn default_true() -> bool {+ true+}++/// An email thread in a seeded inbox.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct EmailThreadSpec {+ /// Subject line.+ pub subject: String,+ /// External sender email address.+ #[serde(default)]+ pub from: Option<String>,+ /// Plain-text body. Defaults to a short generated body.+ #[serde(default)]+ pub body: Option<String>,+ /// Whether the thread is unread.+ #[serde(default)]+ pub unread: bool,+ /// How long ago the message arrived, in minutes. Defaults to staggered+ /// recent times.+ #[serde(default)]+ pub sent_minutes_ago: Option<u32>,+ /// Access grants on the thread (beyond inbox ownership/delegation).+ #[serde(default)]+ pub share: Vec<ShareSpec>,+}++/// A connected inbox (email link) plus its threads.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct EmailAccountSpec {+ /// Owner user key.+ pub owner: String,+ /// Mailbox address. Defaults to the owner's email.+ #[serde(default)]+ pub address: Option<String>,+ /// User keys this inbox is delegated to (shared-inbox access).+ #[serde(default)]+ pub delegated_to: Vec<String>,+ /// Threads keyed by a scenario-local name.+ #[serde(default)]+ pub threads: BTreeMap<String, EmailThreadSpec>,+}++/// A channel message in the scenario.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct MessageSpec {+ /// Channel key the message is posted to.+ pub channel: String,+ /// Sender user key (must be a channel member).+ pub from: String,+ /// Message text.+ pub text: String,+ /// Entity references mentioned by the message (`document:x`,+ /// `project:x`, `chat:x`, `call:x`, `user:x`). Mentioning a shareable+ /// entity grants the channel view access, like the app does.+ #[serde(default)]+ pub mentions: Vec<String>,+}++/// A full scenario file.+#[derive(Debug, Clone, Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ScenarioSpec {+ /// Scenario name: lowercase alphanumerics and hyphens. Namespaces all+ /// derived ids.+ pub scenario: String,+ /// Free-form description of what the scenario exercises.+ #[serde(default)]+ pub description: Option<String>,+ /// Users keyed by a short name.+ #[serde(default)]+ pub users: BTreeMap<String, UserSpec>,+ /// Teams keyed by a short name.+ #[serde(default)]+ pub teams: BTreeMap<String, TeamSpec>,+ /// Channels keyed by a short name.+ #[serde(default)]+ pub channels: BTreeMap<String, ChannelSpec>,+ /// Projects keyed by a short name.+ #[serde(default)]+ pub projects: BTreeMap<String, ProjectSpec>,+ /// Documents keyed by a short name.+ #[serde(default)]+ pub documents: BTreeMap<String, DocumentSpec>,+ /// Tasks keyed by a short name.+ #[serde(default)]+ pub tasks: BTreeMap<String, TaskSpec>,+ /// AI chats keyed by a short name.+ #[serde(default)]+ pub chats: BTreeMap<String, ChatSpec>,+ /// Archived calls keyed by a short name.+ #[serde(default)]+ pub calls: BTreeMap<String, CallSpec>,+ /// Email inboxes keyed by a short name.+ #[serde(default)]+ pub emails: BTreeMap<String, EmailAccountSpec>,+ /// Channel messages, posted in order.+ #[serde(default)]+ pub messages: Vec<MessageSpec>,+}++/// Derive the deterministic uuid for `(scenario, kind, key)`.+///+/// Layout: bytes 0-1 are the `5eed` marker, bytes 2-3 hash the scenario+/// name, bytes 4-15 hash the full triple. Version/variant bits are set so+/// the result is a valid UUIDv8.+pub fn derive_id(scenario: &str, kind: &str, key: &str) -> Uuid {+ let mut bytes = [0u8; 16];+ bytes[0] = 0x5e;+ bytes[1] = 0xed;++ let scenario_hash = Sha256::digest(scenario.as_bytes());+ bytes[2..4].copy_from_slice(&scenario_hash[..2]);++ let mut hasher = Sha256::new();+ hasher.update(scenario.as_bytes());+ hasher.update([0]);+ hasher.update(kind.as_bytes());+ hasher.update([0]);+ hasher.update(key.as_bytes());+ let full_hash = hasher.finalize();+ bytes[4..16].copy_from_slice(&full_hash[..12]);++ bytes[6] = (bytes[6] & 0x0f) | 0x80;+ bytes[8] = (bytes[8] & 0x3f) | 0x80;++ Uuid::from_bytes(bytes)+}++/// The 8-hex-char id prefix shared by every row of a scenario.+pub fn scenario_marker(scenario: &str) -> String {+ let scenario_hash = Sha256::digest(scenario.as_bytes());+ format!(+ "{SEED_MARKER}{:02x}{:02x}",+ scenario_hash[0], scenario_hash[1]+ )+}++impl ScenarioSpec {+ /// Parse a scenario file and validate it.+ pub fn parse(content: &str) -> anyhow::Result<Self> {+ let spec: ScenarioSpec = serde_json::from_str(content)+ .map_err(|e| anyhow::anyhow!("invalid scenario json: {e}"))?;+ let errors = spec.validate();+ anyhow::ensure!(+ errors.is_empty(),+ "invalid scenario `{}`:\n - {}",+ spec.scenario,+ errors.join("\n - ")+ );+ Ok(spec)+ }++ /// The `macro|email` user id for a user key.+ pub fn user_id(&self, key: &str) -> String {+ format!("macro|{}", self.users[key].email)+ }++ /// The derived `macro_user` uuid for a user key.+ pub fn macro_user_uuid(&self, key: &str) -> Uuid {+ derive_id(&self.scenario, "macro_user", key)+ }++ /// The derived team uuid for a team key.+ pub fn team_id(&self, key: &str) -> Uuid {+ derive_id(&self.scenario, "team", key)+ }++ /// The derived channel uuid for a channel key.+ pub fn channel_id(&self, key: &str) -> Uuid {+ derive_id(&self.scenario, "channel", key)+ }++ /// The derived project id (text) for a project key.+ pub fn project_id(&self, key: &str) -> String {+ derive_id(&self.scenario, "project", key).to_string()+ }++ /// The derived document id (text) for a document key.+ pub fn document_id(&self, key: &str) -> String {+ derive_id(&self.scenario, "document", key).to_string()+ }++ /// The derived task document id (text) for a task key.+ pub fn task_id(&self, key: &str) -> String {+ derive_id(&self.scenario, "task", key).to_string()+ }++ /// The derived chat id (text) for a chat key.+ pub fn chat_id(&self, key: &str) -> String {+ derive_id(&self.scenario, "chat", key).to_string()+ }++ /// The derived call uuid for a call key.+ pub fn call_id(&self, key: &str) -> Uuid {+ derive_id(&self.scenario, "call", key)+ }++ /// The derived email link uuid for an inbox key.+ pub fn email_link_id(&self, key: &str) -> Uuid {+ derive_id(&self.scenario, "email_link", key)+ }++ /// The derived email thread uuid for `(inbox key, thread key)`.+ pub fn email_thread_id(&self, account: &str, thread: &str) -> Uuid {+ derive_id(+ &self.scenario,+ "email_thread",+ &format!("{account}/{thread}"),+ )+ }++ /// The derived email message uuid for `(inbox key, thread key)`.+ pub fn email_message_id(&self, account: &str, thread: &str) -> Uuid {+ derive_id(+ &self.scenario,+ "email_message",+ &format!("{account}/{thread}"),+ )+ }++ /// The derived channel message uuid for a message index.+ pub fn message_id(&self, index: usize) -> Uuid {+ derive_id(&self.scenario, "channel_message", &index.to_string())+ }++ /// The team a user key belongs to (owner or member), if any.+ pub fn team_of(&self, user_key: &str) -> Option<&str> {+ self.teams+ .iter()+ .find(|(_, team)| team.owner == user_key || team.members.contains_key(user_key))+ .map(|(key, _)| key.as_str())+ }++ /// All member user keys of a channel, owner included.+ pub fn channel_members(&self, channel_key: &str) -> Vec<String> {+ let channel = &self.channels[channel_key];+ let mut members: Vec<String> = Vec::new();+ match channel.kind {+ ChannelKind::Team => {+ let team = &self.teams[channel.team.as_deref().expect("validated")];+ members.push(team.owner.clone());+ members.extend(team.members.keys().cloned());+ }+ ChannelKind::DirectMessage => {+ members.extend(channel.members.iter().cloned());+ }+ ChannelKind::Public | ChannelKind::Private => {+ let owner = channel.owner.as_deref().expect("validated");+ members.push(owner.to_string());+ members.extend(channel.members.iter().filter(|m| *m != owner).cloned());+ }+ }+ let mut seen = BTreeSet::new();+ members.retain(|m| seen.insert(m.clone()));+ members+ }++ /// The owner user key of a channel.+ pub fn channel_owner(&self, channel_key: &str) -> String {+ let channel = &self.channels[channel_key];+ match channel.kind {+ ChannelKind::Team => self.teams[channel.team.as_deref().expect("validated")]+ .owner+ .clone(),+ ChannelKind::DirectMessage => channel.members[0].clone(),+ ChannelKind::Public | ChannelKind::Private => channel.owner.clone().expect("validated"),+ }+ }++ /// The chain of project keys from `project_key` up through its ancestors,+ /// starting with the project itself. Stops at unknown parents or cycles.+ pub fn project_chain(&self, project_key: &str) -> Vec<String> {+ let mut chain = vec![project_key.to_string()];+ let mut current = project_key;+ while let Some(parent) = self.projects[current].parent.as_deref() {+ if !self.projects.contains_key(parent) || chain.iter().any(|c| c == parent) {+ break;+ }+ chain.push(parent.to_string());+ current = parent;+ }+ chain+ }++ /// Validate the scenario, returning every problem found.+ pub fn validate(&self) -> Vec<String> {+ let mut errors = Vec::new();++ if self.scenario.is_empty()+ || !self+ .scenario+ .chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')+ {+ errors.push(format!(+ "scenario name `{}` must be non-empty lowercase alphanumerics/hyphens",+ self.scenario+ ));+ }++ let mut emails = BTreeSet::new();+ for (key, user) in &self.users {+ if !user.email.contains('@') || user.email != user.email.to_lowercase() {+ errors.push(format!(+ "user `{key}` email `{}` must be a lowercase email address",+ user.email+ ));+ }+ if !emails.insert(user.email.clone()) {+ errors.push(format!("user `{key}` reuses email `{}`", user.email));+ }+ for role in &user.roles {+ if role+ .parse::<roles_and_permissions::domain::model::RoleId>()+ .is_err()+ {+ errors.push(format!("user `{key}` has unknown role `{role}`"));+ }+ }+ }++ let user_exists = |errors: &mut Vec<String>, context: &str, key: &str| {+ if !self.users.contains_key(key) {+ errors.push(format!("{context} references unknown user `{key}`"));+ }+ };++ let mut team_membership: BTreeMap<&str, &str> = BTreeMap::new();+ for (key, team) in &self.teams {+ user_exists(&mut errors, &format!("team `{key}` owner"), &team.owner);+ if team.members.contains_key(&team.owner) {+ errors.push(format!(+ "team `{key}` lists its owner `{}` as a member; the owner is implicit",+ team.owner+ ));+ }+ for member in team.members.keys() {+ user_exists(&mut errors, &format!("team `{key}` member"), member);+ }+ for user in std::iter::once(&team.owner).chain(team.members.keys()) {+ if let Some(previous) = team_membership.insert(user, key) {+ errors.push(format!(+ "user `{user}` is on both team `{previous}` and team `{key}`; users can only belong to one team"+ ));+ }+ }+ }++ for (key, channel) in &self.channels {+ match channel.kind {+ ChannelKind::Team => {+ match channel.team.as_deref() {+ Some(team) if self.teams.contains_key(team) => {}+ Some(team) => {+ errors.push(format!("channel `{key}` references unknown team `{team}`"))+ }+ None => errors.push(format!("team channel `{key}` must set `team`")),+ }+ if channel.owner.is_some() || !channel.members.is_empty() {+ errors.push(format!(+ "team channel `{key}` derives owner/members from the team; leave them unset"+ ));+ }+ }+ ChannelKind::DirectMessage => {+ if channel.members.len() != 2 || channel.members[0] == channel.members[1] {+ errors.push(format!(+ "direct message channel `{key}` must have exactly two distinct members"+ ));+ }+ for member in &channel.members {+ user_exists(&mut errors, &format!("channel `{key}` member"), member);+ }+ if channel.owner.is_some() || channel.name.is_some() {+ errors.push(format!(+ "direct message channel `{key}` cannot set owner or name"+ ));+ }+ if channel.team.is_some() {+ errors.push(format!(+ "channel `{key}` sets `team` but is not a team channel"+ ));+ }+ }+ ChannelKind::Public | ChannelKind::Private => {+ match channel.owner.as_deref() {+ Some(owner) => {+ user_exists(&mut errors, &format!("channel `{key}` owner"), owner)+ }+ None => errors.push(format!("channel `{key}` must set `owner`")),+ }+ for member in &channel.members {+ user_exists(&mut errors, &format!("channel `{key}` member"), member);+ }+ if channel.team.is_some() {+ errors.push(format!(+ "channel `{key}` sets `team` but is not a team channel"+ ));+ }+ }+ }+ }++ let check_shares = |errors: &mut Vec<String>, context: &str, shares: &[ShareSpec]| {+ for share in shares {+ match EntityRef::parse(&share.with) {+ Ok(EntityRef::User(user)) => {+ user_exists(errors, &format!("{context} share"), &user)+ }+ Ok(EntityRef::Team(team)) => {+ if !self.teams.contains_key(&team) {+ errors+ .push(format!("{context} share references unknown team `{team}`"));+ }+ }+ Ok(EntityRef::Channel(channel)) => {+ if !self.channels.contains_key(&channel) {+ errors.push(format!(+ "{context} share references unknown channel `{channel}`"+ ));+ }+ }+ Ok(other) => errors.push(format!(+ "{context} share target must be a user, team, or channel (got {other:?})"+ )),+ Err(e) => errors.push(format!("{context} share: {e}")),+ }+ }+ };++ for (key, project) in &self.projects {+ user_exists(+ &mut errors,+ &format!("project `{key}` owner"),+ &project.owner,+ );+ if let Some(parent) = project.parent.as_deref()+ && !self.projects.contains_key(parent)+ {+ errors.push(format!(+ "project `{key}` references unknown parent `{parent}`"+ ));+ }+ check_shares(&mut errors, &format!("project `{key}`"), &project.share);+ }++ for key in self.projects.keys() {+ let chain = self.project_chain(key);+ if let Some(last) = chain.last()+ && let Some(parent) = self.projects[last].parent.as_deref()+ && chain.iter().any(|c| c == parent)+ {+ errors.push(format!("project `{key}` is part of a parent cycle"));+ }+ }++ for (key, document) in &self.documents {+ user_exists(+ &mut errors,+ &format!("document `{key}` owner"),+ &document.owner,+ );+ if let Some(project) = document.project.as_deref()+ && !self.projects.contains_key(project)+ {+ errors.push(format!(+ "document `{key}` references unknown project `{project}`"+ ));+ }+ if document.file.is_some() && document.content.is_some() {+ errors.push(format!(+ "document `{key}` sets both `file` and `content`; pick one"+ ));+ }+ check_shares(&mut errors, &format!("document `{key}`"), &document.share);+ }++ for (key, task) in &self.tasks {+ user_exists(&mut errors, &format!("task `{key}` owner"), &task.owner);+ for assignee in &task.assignees {+ user_exists(&mut errors, &format!("task `{key}` assignee"), assignee);+ }+ if let Some(project) = task.project.as_deref()+ && !self.projects.contains_key(project)+ {+ errors.push(format!(+ "task `{key}` references unknown project `{project}`"+ ));+ }+ if let Some(status) = task.status.as_deref()+ && system_properties::StatusOption::try_from(status).is_err()+ {+ errors.push(format!(+ "task `{key}` has unknown status `{status}` (expected not_started, in_progress, in_review, completed, or canceled)"+ ));+ }+ if task.share_with_team+ && self.users.contains_key(&task.owner)+ && self.team_of(&task.owner).is_none()+ {+ errors.push(format!(+ "task `{key}` sets share_with_team but owner `{}` is not on a team",+ task.owner+ ));+ }+ check_shares(&mut errors, &format!("task `{key}`"), &task.share);+ }++ for (key, chat) in &self.chats {+ user_exists(&mut errors, &format!("chat `{key}` owner"), &chat.owner);+ check_shares(&mut errors, &format!("chat `{key}`"), &chat.share);+ }++ for (key, call) in &self.calls {+ let members = if self.channels.contains_key(&call.channel) {+ self.channel_members(&call.channel)+ } else {+ errors.push(format!(+ "call `{key}` references unknown channel `{}`",+ call.channel+ ));+ Vec::new()+ };+ user_exists(+ &mut errors,+ &format!("call `{key}` created_by"),+ &call.created_by,+ );+ if self.users.contains_key(&call.created_by)+ && !members.is_empty()+ && !members.contains(&call.created_by)+ {+ errors.push(format!(+ "call `{key}` created_by `{}` is not a member of channel `{}`",+ call.created_by, call.channel+ ));+ }+ for participant in &call.participants {+ user_exists(+ &mut errors,+ &format!("call `{key}` participant"),+ participant,+ );+ if self.users.contains_key(participant)+ && !members.is_empty()+ && !members.contains(participant)+ {+ errors.push(format!(+ "call `{key}` participant `{participant}` is not a member of channel `{}`",+ call.channel+ ));+ }+ }+ let participants = self.call_participants(key);+ for segment in &call.transcript {+ if !participants.contains(&segment.speaker) {+ errors.push(format!(+ "call `{key}` transcript speaker `{}` is not a participant",+ segment.speaker+ ));+ }+ }+ if call.duration_minutes == Some(0) {+ errors.push(format!("call `{key}` duration_minutes must be positive"));+ }+ }++ for (key, account) in &self.emails {+ user_exists(&mut errors, &format!("inbox `{key}` owner"), &account.owner);+ for delegate in &account.delegated_to {+ user_exists(&mut errors, &format!("inbox `{key}` delegate"), delegate);+ if delegate == &account.owner {+ errors.push(format!("inbox `{key}` cannot be delegated to its owner"));+ }+ }+ for (thread_key, thread) in &account.threads {+ if let Some(from) = thread.from.as_deref()+ && !from.contains('@')+ {+ errors.push(format!(+ "inbox `{key}` thread `{thread_key}` sender `{from}` must be an email address"+ ));+ }+ check_shares(+ &mut errors,+ &format!("inbox `{key}` thread `{thread_key}`"),+ &thread.share,+ );+ }+ }++ for (index, message) in self.messages.iter().enumerate() {+ let context = format!("message #{index}");+ if !self.channels.contains_key(&message.channel) {+ errors.push(format!(+ "{context} references unknown channel `{}`",+ message.channel+ ));+ }+ user_exists(&mut errors, &format!("{context} sender"), &message.from);+ if self.channels.contains_key(&message.channel)+ && self.users.contains_key(&message.from)+ && !self+ .channel_members(&message.channel)+ .contains(&message.from)+ {+ errors.push(format!(+ "{context} sender `{}` is not a member of channel `{}`",+ message.from, message.channel+ ));+ }+ for mention in &message.mentions {+ match EntityRef::parse(mention) {+ Ok(EntityRef::User(user)) => {+ user_exists(&mut errors, &format!("{context} mention"), &user)+ }+ Ok(EntityRef::Document(doc)) => {+ if !self.documents.contains_key(&doc) {+ errors.push(format!(+ "{context} mention references unknown document `{doc}`"+ ));+ }+ }+ Ok(EntityRef::Project(project)) => {+ if !self.projects.contains_key(&project) {+ errors.push(format!(+ "{context} mention references unknown project `{project}`"+ ));+ }+ }+ Ok(EntityRef::Chat(chat)) => {+ if !self.chats.contains_key(&chat) {+ errors.push(format!("{context} mention references unknown chat `{chat}`"));+ }+ }+ Ok(EntityRef::Call(call)) => {+ if !self.calls.contains_key(&call) {+ errors.push(format!("{context} mention references unknown call `{call}`"));+ }+ }+ Ok(other) => errors.push(format!(+ "{context} mention must be a user, document, project, chat, or call (got {other:?})"+ )),+ Err(e) => errors.push(format!("{context} mention: {e}")),+ }+ }+ }++ errors+ }++ /// The effective participant user keys of a call (creator included).+ pub fn call_participants(&self, call_key: &str) -> Vec<String> {+ let call = &self.calls[call_key];+ let mut participants = vec![call.created_by.clone()];+ participants.extend(+ call.participants+ .iter()+ .filter(|p| **p != call.created_by)+ .cloned(),+ );+ let mut seen = BTreeSet::new();+ participants.retain(|p| seen.insert(p.clone()));+ participants+ }+}diff --git a/tooling/seed_cli/src/entity/scenario/spec/test.rs b/tooling/seed_cli/src/entity/scenario/spec/test.rsnew file mode 100644index 0000000000..079bdb827a--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/spec/test.rs@@ -0,0 +1,235 @@+use super::*;++fn example_json() -> String {+ let path =+ std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("seed/scenarios/team-perms.json");+ std::fs::read_to_string(path).expect("example scenario file exists")+}++fn example() -> ScenarioSpec {+ ScenarioSpec::parse(&example_json()).expect("example scenario is valid")+}++fn minimal(json: serde_json::Value) -> Result<ScenarioSpec, anyhow::Error> {+ ScenarioSpec::parse(&json.to_string())+}++#[test]+fn derive_id_is_deterministic_and_marked() {+ let a = derive_id("team-perms", "document", "q3-plan");+ let b = derive_id("team-perms", "document", "q3-plan");+ assert_eq!(a, b);++ let other_key = derive_id("team-perms", "document", "handbook");+ let other_kind = derive_id("team-perms", "chat", "q3-plan");+ let other_scenario = derive_id("other", "document", "q3-plan");+ assert_ne!(a, other_key);+ assert_ne!(a, other_kind);+ assert_ne!(a, other_scenario);++ let text = a.to_string();+ assert!(+ text.starts_with(SEED_MARKER),+ "id {text} carries the marker"+ );+ assert!(+ text.starts_with(&scenario_marker("team-perms")),+ "id {text} carries the scenario marker {}",+ scenario_marker("team-perms")+ );+ assert_eq!(a.get_version_num(), 8);+}++#[test]+fn scenario_marker_shape() {+ let marker = scenario_marker("team-perms");+ assert_eq!(marker.len(), 8);+ assert!(marker.starts_with(SEED_MARKER));+ assert_ne!(marker, scenario_marker("other-scenario"));+}++#[test]+fn example_scenario_parses() {+ let spec = example();+ assert_eq!(spec.scenario, "team-perms");+ assert_eq!(spec.users.len(), 5);+ assert_eq!(spec.user_id("alice"), "macro|[email protected]");+}++#[test]+fn team_and_channel_derivations() {+ let spec = example();++ assert_eq!(spec.team_of("alice"), Some("acme"));+ assert_eq!(spec.team_of("bob"), Some("acme"));+ assert_eq!(spec.team_of("dave"), None);++ let mut hq_members = spec.channel_members("acme-hq");+ hq_members.sort();+ assert_eq!(hq_members, vec!["alice", "bob", "carol"]);+ assert_eq!(spec.channel_owner("acme-hq"), "alice");++ assert_eq!(spec.channel_owner("dm-alice-dave"), "alice");+ let mut eng_members = spec.channel_members("eng");+ eng_members.sort();+ assert_eq!(eng_members, vec!["alice", "bob", "dave"]);+}++#[test]+fn call_participants_include_creator_once() {+ let spec = example();+ assert_eq!(spec.call_participants("eng-standup"), vec!["alice", "bob"]);+ assert_eq!(spec.call_participants("dm-huddle"), vec!["dave", "alice"]);+}++#[test]+fn rejects_unknown_references() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": { "alice": { "email": "[email protected]" } },+ "documents": {+ "doc": {+ "owner": "ghost",+ "share": [ { "with": "team:none", "level": "view" } ]+ }+ }+ }));+ let error = result.unwrap_err().to_string();+ assert!(error.contains("unknown user `ghost`"), "{error}");+ assert!(error.contains("unknown team `none`"), "{error}");+}++#[test]+fn rejects_second_team_membership() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": {+ "alice": { "email": "[email protected]" },+ "bob": { "email": "[email protected]" },+ "carol": { "email": "[email protected]" }+ },+ "teams": {+ "one": { "owner": "alice", "members": { "bob": "member" } },+ "two": { "owner": "carol", "members": { "bob": "admin" } }+ }+ }));+ let error = result.unwrap_err().to_string();+ assert!(error.contains("one team"), "{error}");+}++#[test]+fn rejects_bad_channels() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": {+ "alice": { "email": "[email protected]" },+ "bob": { "email": "[email protected]" }+ },+ "teams": { "acme": { "owner": "alice" } },+ "channels": {+ "dm": { "type": "direct_message", "members": ["alice"] },+ "hq": { "type": "team", "team": "acme", "members": ["bob"] },+ "orphan": { "type": "private" }+ }+ }));+ let error = result.unwrap_err().to_string();+ assert!(error.contains("exactly two distinct members"), "{error}");+ assert!(+ error.contains("derives owner/members from the team"),+ "{error}"+ );+ assert!(error.contains("must set `owner`"), "{error}");+}++#[test]+fn rejects_call_and_message_membership_violations() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": {+ "alice": { "email": "[email protected]" },+ "eve": { "email": "[email protected]" }+ },+ "channels": {+ "eng": { "type": "private", "owner": "alice" }+ },+ "calls": {+ "call": { "channel": "eng", "created_by": "eve" }+ },+ "messages": [+ { "channel": "eng", "from": "eve", "text": "hi" }+ ]+ }));+ let error = result.unwrap_err().to_string();+ assert!(+ error.contains("created_by `eve` is not a member"),+ "{error}"+ );+ assert!(error.contains("sender `eve` is not a member"), "{error}");+}++#[test]+fn rejects_project_cycles() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": { "alice": { "email": "[email protected]" } },+ "projects": {+ "a": { "owner": "alice", "parent": "b" },+ "b": { "owner": "alice", "parent": "a" }+ }+ }));+ let error = result.unwrap_err().to_string();+ assert!(error.contains("parent cycle"), "{error}");+}++#[test]+fn rejects_unknown_roles() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": {+ "alice": { "email": "[email protected]", "roles": ["professional_subscriber", "royalty"] }+ }+ }));+ let error = result.unwrap_err().to_string();+ assert!(error.contains("unknown role `royalty`"), "{error}");+ assert!(!error.contains("professional_subscriber"), "{error}");+}++#[test]+fn rejects_unknown_fields() {+ let result = minimal(serde_json::json!({+ "scenario": "bad",+ "users": { "alice": { "email": "[email protected]", "surprise": true } }+ }));+ assert!(result.unwrap_err().to_string().contains("unknown field"));+}++#[test]+fn entity_ref_parsing() {+ assert_eq!(+ EntityRef::parse("user:alice").unwrap(),+ EntityRef::User("alice".to_string())+ );+ assert_eq!(+ EntityRef::parse("document:q3-plan").unwrap(),+ EntityRef::Document("q3-plan".to_string())+ );+ assert!(EntityRef::parse("nope").is_err());+ assert!(EntityRef::parse("user:").is_err());+ assert!(EntityRef::parse("widget:x").is_err());+}++#[test]+fn project_chain_walks_parents() {+ let spec = minimal(serde_json::json!({+ "scenario": "chain",+ "users": { "alice": { "email": "[email protected]" } },+ "projects": {+ "root": { "owner": "alice" },+ "mid": { "owner": "alice", "parent": "root" },+ "leaf": { "owner": "alice", "parent": "mid" }+ }+ }))+ .unwrap();+ assert_eq!(spec.project_chain("leaf"), vec!["leaf", "mid", "root"]);+ assert_eq!(spec.project_chain("root"), vec!["root"]);+}diff --git a/tooling/seed_cli/src/entity/scenario/status.rs b/tooling/seed_cli/src/entity/scenario/status.rsnew file mode 100644index 0000000000..e0847458b9--- /dev/null+++ b/tooling/seed_cli/src/entity/scenario/status.rs@@ -0,0 +1,368 @@+//! Status: report which of a scenario's rows are actually present — per-kind+//! counts, FusionAuth accounts, sync-service content — and re-print the+//! persona login links. Read-only.+//!+//! Without `--file` it discovers applied scenarios instead: seeded ids carry+//! `5eed` + a 4-hex-char hash of the scenario name, so grouping marked rows+//! by their first 8 uuid chars yields one bucket per applied scenario, which+//! is then matched against the names declared in `seed/scenarios/*.json`.++use std::collections::{BTreeMap, HashSet};+use std::path::Path;++use anyhow::Context;+use sqlx::PgPool;++use crate::config::SeedCliContext;++use super::spec::{SEED_MARKER, ScenarioSpec, scenario_marker};++/// The tables holding marker-prefixed container rows, as (kind, table, id+/// column). Documents and tasks share the `"Document"` table.+const MARKED_TABLES: &[(&str, &str, &str)] = &[+ ("teams", "team", "id"),+ ("channels", "comms_channels", "id"),+ ("projects", "\"Project\"", "id"),+ ("documents", "\"Document\"", "id"),+ ("chats", "\"Chat\"", "id"),+ ("calls", "call_records", "id"),+ ("inboxes", "email_links", "id"),+ ("messages", "comms_messages", "id"),+];++/// One kind's presence check: the expected `(spec key, id)` pairs and where+/// their rows live.+struct KindCheck {+ label: &'static str,+ table: &'static str,+ id_column: &'static str,+ expected: Vec<(String, String)>,+}++fn kind_checks(spec: &ScenarioSpec) -> Vec<KindCheck> {+ let pairs = |keys: Vec<(&String, String)>| {+ keys.into_iter()+ .map(|(key, id)| (key.clone(), id))+ .collect::<Vec<_>>()+ };+ vec![+ KindCheck {+ label: "teams",+ table: "team",+ id_column: "id",+ expected: pairs(+ spec.teams+ .keys()+ .map(|k| (k, spec.team_id(k).to_string()))+ .collect(),+ ),+ },+ KindCheck {+ label: "channels",+ table: "comms_channels",+ id_column: "id",+ expected: pairs(+ spec.channels+ .keys()+ .map(|k| (k, spec.channel_id(k).to_string()))+ .collect(),+ ),+ },+ KindCheck {+ label: "projects",+ table: "\"Project\"",+ id_column: "id",+ expected: pairs(+ spec.projects+ .keys()+ .map(|k| (k, spec.project_id(k)))+ .collect(),+ ),+ },+ KindCheck {+ label: "documents",+ table: "\"Document\"",+ id_column: "id",+ expected: pairs(+ spec.documents+ .keys()+ .map(|k| (k, spec.document_id(k)))+ .collect(),+ ),+ },+ KindCheck {+ label: "tasks",+ table: "\"Document\"",+ id_column: "id",+ expected: pairs(spec.tasks.keys().map(|k| (k, spec.task_id(k))).collect()),+ },+ KindCheck {+ label: "chats",+ table: "\"Chat\"",+ id_column: "id",+ expected: pairs(spec.chats.keys().map(|k| (k, spec.chat_id(k))).collect()),+ },+ KindCheck {+ label: "calls",+ table: "call_records",+ id_column: "id",+ expected: pairs(+ spec.calls+ .keys()+ .map(|k| (k, spec.call_id(k).to_string()))+ .collect(),+ ),+ },+ KindCheck {+ label: "inboxes",+ table: "email_links",+ id_column: "id",+ expected: pairs(+ spec.emails+ .keys()+ .map(|k| (k, spec.email_link_id(k).to_string()))+ .collect(),+ ),+ },+ KindCheck {+ label: "messages",+ table: "comms_messages",+ id_column: "id",+ expected: spec+ .messages+ .iter()+ .enumerate()+ .map(|(index, message)| {+ (+ format!("#{index} in `{}`", message.channel),+ spec.message_id(index).to_string(),+ )+ })+ .collect(),+ },+ ]+}++/// The ids of every expected `SELECT` hit in `table.column`, as text.+#[allow(clippy::disallowed_methods, reason = "seed-only dynamic SQL")]+async fn existing_ids(+ pool: &PgPool,+ table: &str,+ column: &str,+ ids: &[String],+) -> anyhow::Result<HashSet<String>> {+ let sql = format!("SELECT {column}::text FROM {table} WHERE {column}::text = ANY($1)");+ let found: Vec<String> = sqlx::query_scalar(&sql)+ .bind(ids)+ .fetch_all(pool)+ .await+ .with_context(|| format!("querying {table}"))?;+ Ok(found.into_iter().collect())+}++fn print_check_line(label: &str, found: usize, expected: usize, missing: &[String], extra: &str) {+ let mut line = format!(" {label:<13} {found}/{expected}{extra}");+ if !missing.is_empty() {+ line.push_str(&format!(" (missing: {})", missing.join(", ")));+ }+ println!("{line}");+}++/// Report presence for one scenario file's spec.+pub async fn report(ctx: &SeedCliContext, spec: &ScenarioSpec) -> anyhow::Result<()> {+ let pool = ctx.db.pool();+ println!(+ "Scenario `{}` (marker {})",+ spec.scenario,+ scenario_marker(&spec.scenario)+ );++ let mut expected_total = 0usize;+ let mut found_total = 0usize;++ // Users carry no marker (their rows come from the signup webhook), so+ // presence is keyed by email; FusionAuth is checked alongside.+ if !spec.users.is_empty() {+ let emails: Vec<String> = spec.users.values().map(|u| u.email.clone()).collect();+ let found = existing_ids(&pool, "\"User\"", "email", &emails).await?;+ let missing: Vec<String> = spec+ .users+ .iter()+ .filter(|(_, user)| !found.contains(&user.email))+ .map(|(key, _)| key.clone())+ .collect();++ let mut fa_found = 0usize;+ for email in &emails {+ if ctx+ .fusionauth_client+ .user_exists(email)+ .await+ .unwrap_or(false)+ {+ fa_found += 1;+ }+ }+ let fa_hint = if fa_found == 0 {+ " (accounts missing, or FusionAuth is unreachable)"+ } else {+ ""+ };+ print_check_line(+ "users",+ found.len(),+ emails.len(),+ &missing,+ &format!(" fusionauth {fa_found}/{}{fa_hint}", emails.len()),+ );+ expected_total += emails.len();+ found_total += found.len();+ }++ for check in kind_checks(spec) {+ if check.expected.is_empty() {+ continue;+ }+ let ids: Vec<String> = check.expected.iter().map(|(_, id)| id.clone()).collect();+ let found = existing_ids(&pool, check.table, check.id_column, &ids).await?;+ let missing: Vec<String> = check+ .expected+ .iter()+ .filter(|(_, id)| !found.contains(id))+ .map(|(key, _)| key.clone())+ .collect();+ print_check_line(check.label, found.len(), ids.len(), &missing, "");+ expected_total += ids.len();+ found_total += found.len();+ }++ report_sync_content(ctx, spec).await;++ if found_total == 0 {+ println!("\nNot applied — run `just seed-scenario apply --file <scenario.json>`.");+ } else if found_total < expected_total {+ println!("\nPartially applied — re-run apply to converge. Log in as:");+ super::apply::print_login_links(spec);+ } else {+ println!("\nFully applied. Log in as:");+ super::apply::print_login_links(spec);+ }+ Ok(())+}++/// Probe sync-service for the entities whose content lives there: every+/// task, plus documents with inline content or a `.md` file.+async fn report_sync_content(ctx: &SeedCliContext, spec: &ScenarioSpec) {+ let mut targets: Vec<(String, String)> = spec+ .documents+ .iter()+ .filter(|(_, doc)| {+ doc.content.is_some() || doc.file.as_deref().is_some_and(|f| f.ends_with(".md"))+ })+ .map(|(key, _)| (key.clone(), spec.document_id(key)))+ .collect();+ targets.extend(+ spec.tasks+ .keys()+ .map(|key| (key.clone(), spec.task_id(key))),+ );+ if targets.is_empty() {+ return;+ }++ let Some(clients) = ctx.doc_content.as_ref() else {+ println!(" sync content skipped (SYNC_SERVICE_URL/LEXICAL_SERVICE_URL unset)");+ return;+ };+ let mut missing = Vec::new();+ for (key, id) in &targets {+ if clients.sync.get_raw(id).await.is_err() {+ missing.push(key.clone());+ }+ }+ print_check_line(+ "sync content",+ targets.len() - missing.len(),+ targets.len(),+ &missing,+ "",+ );+}++/// No `--file`: find every applied scenario by scanning for marked ids, then+/// report fully on the ones whose name matches a file in `scenarios_dir`.+#[allow(clippy::disallowed_methods, reason = "seed-only dynamic SQL")]+pub async fn discover(ctx: &SeedCliContext, scenarios_dir: &Path) -> anyhow::Result<()> {+ let pool = ctx.db.pool();++ let mut counts: BTreeMap<String, Vec<(&'static str, i64)>> = BTreeMap::new();+ for (label, table, column) in MARKED_TABLES {+ let sql = format!(+ "SELECT substring({column}::text, 1, 8), count(*) FROM {table} \+ WHERE {column}::text LIKE '{SEED_MARKER}%' GROUP BY 1"+ );+ let rows: Vec<(String, i64)> = sqlx::query_as(&sql)+ .fetch_all(&pool)+ .await+ .with_context(|| format!("scanning {table}"))?;+ for (marker, count) in rows {+ counts.entry(marker).or_default().push((label, count));+ }+ }++ if counts.is_empty() {+ println!("No seeded rows found (no ids starting `{SEED_MARKER}`).");+ return Ok(());+ }++ let known = known_scenarios(scenarios_dir);+ let mut first = true;+ for (marker, tables) in &counts {+ if !first {+ println!();+ }+ first = false;+ match known.get(marker) {+ Some((file, spec)) => {+ println!("{}:", file.display());+ report(ctx, spec).await?;+ }+ None => {+ let breakdown = tables+ .iter()+ .map(|(label, count)| format!("{count} {label}"))+ .collect::<Vec<_>>()+ .join(", ");+ println!(+ "Unknown scenario (marker {marker}): {breakdown} — no file in {} declares a matching name; `reset --all` removes it",+ scenarios_dir.display()+ );+ }+ }+ }+ Ok(())+}++/// Parse every readable scenario file in `dir` into a marker -> (path, spec)+/// map. Unreadable or invalid files are skipped: discovery should still+/// report the database's state.+fn known_scenarios(dir: &Path) -> BTreeMap<String, (std::path::PathBuf, ScenarioSpec)> {+ let mut known = BTreeMap::new();+ let Ok(entries) = std::fs::read_dir(dir) else {+ return known;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().is_none_or(|ext| ext != "json") {+ continue;+ }+ let Ok(content) = std::fs::read_to_string(&path) else {+ continue;+ };+ let Ok(spec) = ScenarioSpec::parse(&content) else {+ continue;+ };+ known.insert(scenario_marker(&spec.scenario), (path, spec));+ }+ known+}diff --git a/tooling/seed_cli/src/entity/user/test.rs b/tooling/seed_cli/src/entity/user/test.rsindex 83b30e1be9..be398d7e11 100644--- a/tooling/seed_cli/src/entity/user/test.rs+++ b/tooling/seed_cli/src/entity/user/test.rs@@ -66,6 +66,7 @@ fn mock_ctx(auth: Auth) -> SeedCliContext {db: Db::default(),fusionauth_client: auth,s3: S3::default(),+ doc_content: None,}}diff --git a/tooling/seed_cli/src/main.rs b/tooling/seed_cli/src/main.rsindex cb6c4255d8..3d68b8adc4 100644--- a/tooling/seed_cli/src/main.rs+++ b/tooling/seed_cli/src/main.rs@@ -38,14 +38,15 @@ pub async fn main() -> anyhow::Result<()> {cli.command.validate_environment(&env_vars)?;tracing::trace!("initializing");+ let database_url = env_vars+ .database_url+ .replace("postgres:5432", "localhost:5432");+ cli.command.pre_connect(&database_url).await?;+let db = PgPoolOptions::new().min_connections(1).max_connections(95)- .connect(- &env_vars- .database_url- .replace("postgres:5432", "localhost:5432"),- )+ .connect(&database_url).await.context("could not connect to db")?;tracing::trace!("initialized db");@@ -69,6 +70,7 @@ pub async fn main() -> anyhow::Result<()> {&env_vars.document_storage_bucket,macro_aws_config::s3_client().await,),+ doc_content: crate::config::DocContentClients::from_env(),};cli.command.execute(context).awaitdiff --git a/tooling/seed_cli/src/service/auth/mod.rs b/tooling/seed_cli/src/service/auth/mod.rsindex f6ae5b25be..8d60c7de76 100644--- a/tooling/seed_cli/src/service/auth/mod.rs+++ b/tooling/seed_cli/src/service/auth/mod.rs@@ -42,4 +42,38 @@ impl SeedAuth {Ok(result)}++ /// Whether a FusionAuth account exists for `email`. Read-only; also+ /// returns false when FusionAuth is unreachable.+ pub async fn user_exists(&self, email: &str) -> anyhow::Result<bool> {+ Ok(self.inner.get_user_id_by_email(email).await.is_ok())+ }++ /// Ensure a FusionAuth user exists and is registered to the application,+ /// so the account can log in through the real passwordless flow.+ /// Returns whether the user was created (false = already existed).+ ///+ /// Creating the user fires the `user.create` webhook, which writes the+ /// base macrodb rows — call this BEFORE seeding user rows directly.+ #[tracing::instrument(skip(self), err)]+ pub async fn ensure_user(&self, email: String) -> anyhow::Result<bool> {+ if self.inner.get_user_id_by_email(&email).await.is_ok() {+ return Ok(false);+ }++ self.create_user(fusionauth::user::create::User {+ email: std::borrow::Cow::Owned(email.clone()),+ username: None,+ password: "hardcodeLocalPassword123!".into(),+ })+ .await?;++ self.inner+ .register_user_from_email(&email)+ .await+ .inspect_err(|e| tracing::warn!(error=?e, "user registration failed, continuing"))+ .ok();++ Ok(true)+ }}diff --git a/tooling/seed_cli/src/service/db/mod.rs b/tooling/seed_cli/src/service/db/mod.rsindex 015a642e5d..5a7667d3dc 100644--- a/tooling/seed_cli/src/service/db/mod.rs+++ b/tooling/seed_cli/src/service/db/mod.rs@@ -10,6 +10,7 @@ pub use SeedDb as Db;#[allow(unused_imports)]use mockall::automock;+use chrono::{DateTime, Utc};use comms_db_client::channels::create_channel::CreateChannelOptions;use comms_db_client::channels::seed_channel::SeedChannelOptions;use comms_db_client::messages::create_message::CreateMessageOptions;@@ -18,7 +19,57 @@ use comms_db_client::messages::seed_message::SeedMessageOptions;use comms_db_client::model::SimpleMention;use model::document::DocumentMetadata;use models_email::email::service;+use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;+use uuid::Uuid;++/// Everything needed to seed one scenario user.+#[derive(Debug)]+pub struct AdoptOrSeedUserArgs {+ /// Login email.+ pub email: String,+ /// The `macro|email` user id.+ pub user_id: String,+ /// Derived uuid used when no `macro_user` row exists for the email.+ pub derived_macro_user_id: Uuid,+ /// First name for `macro_user_info`.+ pub first_name: String,+ /// Last name for `macro_user_info`.+ pub last_name: String,+ /// Fabricated stripe customer id used on fresh inserts.+ pub stripe_customer_id: String,+ /// Role rows written on top of the default `self_serve`.+ pub extra_roles: Vec<String>,+}++/// Everything needed to seed an archived call record.+#[derive(Debug)]+pub struct InsertCallRecordArgs {+ /// Call record id (same id the live call would have had).+ pub call_id: Uuid,+ /// Channel the call happened in.+ pub channel_id: Uuid,+ /// LiveKit-style room name.+ pub room_name: String,+ /// Creator user id.+ pub created_by: String,+ /// Call start time.+ pub started_at: DateTime<Utc>,+ /// Call end time.+ pub ended_at: DateTime<Utc>,+ /// Pre-derived share permission id.+ pub share_permission_id: String,+ /// Whether the creator's team gets view access.+ pub share_with_team: bool,+ /// Optional custom display name.+ pub custom_name: Option<String>,+ /// The creator's team, when `share_with_team` applies.+ pub team_id: Option<Uuid>,+ /// Participants as (user id, joined_at, left_at).+ pub participants: Vec<(String, DateTime<Utc>, DateTime<Utc>)>,+ /// Transcript segments as (speaker id, content, started_at, ended_at).+ pub transcripts: Vec<(String, String, DateTime<Utc>, DateTime<Utc>)>,+}/// Wrapper around the database connection pool.#[cfg_attr(test, allow(dead_code))]@@ -223,4 +274,475 @@ impl SeedDb {.await?;Ok(id)}++ /// Execute a list of standalone SQL statements inside one transaction.+ ///+ /// Unlike [`Self::execute_sql_script`] the statements are not split on+ /// semicolons, so they may contain CTEs with embedded semicolons-free+ /// bodies of arbitrary complexity.+ #[tracing::instrument(skip(self, statements), err)]+ #[allow(clippy::disallowed_methods, reason = "seed-only dynamic SQL")]+ pub async fn execute_statements(&self, statements: &[String]) -> anyhow::Result<()> {+ let mut transaction = self.inner.begin().await?;+ for statement in statements {+ sqlx::query(statement).execute(&mut *transaction).await?;+ }+ transaction.commit().await?;+ Ok(())+ }++ /// Upsert an `entity_access` row, replacing the level on conflict.+ #[tracing::instrument(skip(self), err)]+ #[allow(clippy::disallowed_methods, reason = "seed-only dynamic SQL")]+ pub async fn upsert_entity_access(+ &self,+ entity_id: &str,+ entity_type: entity_access_db_utils::EntityType,+ source_id: &str,+ source_type: entity_access_db_utils::EntityAccessSourceType,+ access_level: AccessLevel,+ granted_from_project_id: Option<String>,+ ) -> anyhow::Result<()> {+ let entity_uuid = macro_uuid::string_to_uuid(entity_id)+ .map_err(|e| anyhow::anyhow!("entity id {entity_id} is not a uuid: {e:?}"))?;+ let conflict = if granted_from_project_id.is_some() {+ r#"(entity_id, entity_type, source_id, source_type, granted_from_project_id)+ WHERE granted_from_project_id IS NOT NULL"#+ } else {+ r#"(entity_id, entity_type, source_id, source_type)+ WHERE granted_from_project_id IS NULL"#+ };+ let query = format!(+ r#"INSERT INTO entity_access+ (entity_id, entity_type, source_id, source_type, access_level, granted_from_project_id)+ VALUES ($1, $2, $3, $4, $5, $6)+ ON CONFLICT {conflict}+ DO UPDATE SET access_level = EXCLUDED.access_level"#+ );+ sqlx::query(&query)+ .bind(entity_uuid)+ .bind(entity_type.as_ref())+ .bind(source_id)+ .bind(source_type)+ .bind(access_level)+ .bind(granted_from_project_id.as_deref())+ .execute(&self.inner)+ .await?;+ Ok(())+ }++ /// Grant a channel access to a shareable item: writes the+ /// `ChannelSharePermission` row (when the item has a share permission)+ /// and the `entity_access` row, like mention-sharing does.+ #[tracing::instrument(skip(self), err)]+ pub async fn upsert_channel_share_permission(+ &self,+ item_id: &str,+ item_type: &str,+ channel_id: &str,+ access_level: AccessLevel,+ ) -> anyhow::Result<()> {+ match macro_db_client::share_permission::get::get_share_permission_id(+ &self.inner,+ item_id,+ item_type,+ )+ .await+ {+ Ok(share_permission_id) => {+ if let Err(e) =+ macro_db_client::share_permission::channel_permission::create::insert_channel_share_permission(+ &self.inner,+ &share_permission_id,+ channel_id,+ &access_level,+ )+ .await+ {+ tracing::warn!(error=?e, "channel share permission may already exist, continuing");+ }+ }+ Err(e) => {+ tracing::debug!(error=?e, item_type, "no share permission for item, skipping channel share row");+ }+ }++ self.upsert_entity_access(+ item_id,+ entity_access_db_utils::EntityType::from_str(item_type)+ .map_err(|e| anyhow::anyhow!("invalid entity type {item_type}: {e:?}"))?,+ channel_id,+ entity_access_db_utils::EntityAccessSourceType::Channel,+ access_level,+ None,+ )+ .await+ }++ /// Insert a project row with a pre-defined id.+ #[tracing::instrument(skip(self), err)]+ pub async fn insert_project(+ &self,+ project_id: &str,+ name: &str,+ owner_id: &str,+ parent_id: Option<String>,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO "Project" (id, name, "userId", "parentId", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, NOW(), NOW())"#,+ project_id,+ name,+ owner_id,+ parent_id.as_deref(),+ )+ .execute(&self.inner)+ .await?;+ Ok(())+ }++ /// Insert an AI chat row with a pre-defined id.+ #[tracing::instrument(skip(self), err)]+ pub async fn insert_chat(+ &self,+ chat_id: &str,+ owner_id: &str,+ name: &str,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO "Chat" (id, "userId", name, "isPersistent") VALUES ($1, $2, $3, true)"#,+ chat_id,+ owner_id,+ name,+ )+ .execute(&self.inner)+ .await?;+ Ok(())+ }++ /// Create a public share permission attached to a project.+ #[tracing::instrument(skip(self, share_permission), err)]+ pub async fn create_project_public_permission(+ &self,+ project_id: &str,+ share_permission: &SharePermissionV2,+ ) -> anyhow::Result<()> {+ let mut transaction = self.inner.begin().await?;+ macro_db_client::share_permission::create::create_project_permission(+ &mut transaction,+ project_id,+ share_permission,+ )+ .await?;+ transaction.commit().await?;+ Ok(())+ }++ /// Create a public share permission attached to a chat.+ #[tracing::instrument(skip(self, share_permission), err)]+ pub async fn create_chat_public_permission(+ &self,+ chat_id: &str,+ share_permission: &SharePermissionV2,+ ) -> anyhow::Result<()> {+ let mut transaction = self.inner.begin().await?;+ macro_db_client::share_permission::create::create_chat_permission(+ &mut transaction,+ chat_id,+ share_permission,+ )+ .await?;+ transaction.commit().await?;+ Ok(())+ }++ /// Insert an archived call record with its share permission, access+ /// rows, participants, and transcripts — the same rows `create_call` ++ /// `archive_call` leave behind.+ #[tracing::instrument(skip(self, args), fields(call_id = %args.call_id), err)]+ pub async fn insert_call_record(&self, args: InsertCallRecordArgs) -> anyhow::Result<()> {+ let mut transaction = self.inner.begin().await?;++ sqlx::query!(+ r#"INSERT INTO "SharePermission" (id, "isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ VALUES ($1, false, NULL, NOW(), NOW())"#,+ args.share_permission_id,+ )+ .execute(transaction.as_mut())+ .await?;++ macro_db_client::share_permission::channel_permission::create::create_channel_share_permissions(+ &mut transaction,+ &args.share_permission_id,+ &vec![models_permissions::share_permission::channel_share_permission::ChannelSharePermission {+ channel_id: args.channel_id.to_string(),+ access_level: AccessLevel::Edit,+ }],+ )+ .await?;++ entity_access_db_utils::insert_entity_access_row(+ &mut transaction,+ &args.call_id,+ entity_access_db_utils::EntityType::Call,+ &args.created_by,+ entity_access_db_utils::EntityAccessSourceType::User,+ entity_access_db_utils::AccessLevel::Owner,+ )+ .await?;+ entity_access_db_utils::insert_entity_access_row(+ &mut transaction,+ &args.call_id,+ entity_access_db_utils::EntityType::Call,+ &args.channel_id.to_string(),+ entity_access_db_utils::EntityAccessSourceType::Channel,+ entity_access_db_utils::AccessLevel::Edit,+ )+ .await?;+ if let Some(team_id) = args.team_id {+ entity_access_db_utils::insert_entity_access_row(+ &mut transaction,+ &args.call_id,+ entity_access_db_utils::EntityType::Call,+ &team_id.to_string(),+ entity_access_db_utils::EntityAccessSourceType::Team,+ entity_access_db_utils::AccessLevel::View,+ )+ .await?;+ }++ let duration_ms = (args.ended_at - args.started_at).num_milliseconds().max(0);+ sqlx::query!(+ r#"INSERT INTO call_records+ (id, channel_id, room_name, created_by, started_at, ended_at, duration_ms,+ share_permission_id, share_with_team, custom_name)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)"#,+ args.call_id,+ args.channel_id,+ args.room_name,+ args.created_by,+ args.started_at,+ args.ended_at,+ duration_ms,+ args.share_permission_id,+ args.share_with_team,+ args.custom_name.as_deref(),+ )+ .execute(transaction.as_mut())+ .await?;++ for (user_id, joined_at, left_at) in &args.participants {+ sqlx::query!(+ r#"INSERT INTO call_record_participants (call_record_id, user_id, joined_at, left_at)+ VALUES ($1, $2, $3, $4)"#,+ args.call_id,+ user_id,+ joined_at,+ left_at as _,+ )+ .execute(transaction.as_mut())+ .await?;+ }++ for (index, (speaker_id, content, started_at, ended_at)) in+ args.transcripts.iter().enumerate()+ {+ sqlx::query!(+ r#"INSERT INTO call_record_transcripts+ (call_record_id, segment_id, speaker_id, content, started_at, ended_at, sequence_num)+ VALUES ($1, $2, $3, $4, $5, $6, $7)"#,+ args.call_id,+ format!("seed-seg-{index}"),+ speaker_id,+ content,+ started_at,+ ended_at as _,+ index as i32,+ )+ .execute(transaction.as_mut())+ .await?;+ }++ transaction.commit().await?;+ Ok(())+ }++ /// Delegate an email link from its owner to another user.+ #[tracing::instrument(skip(self), err)]+ pub async fn insert_macro_user_link(+ &self,+ primary_macro_id: &str,+ child_macro_id: &str,+ link_id: uuid::Uuid,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"INSERT INTO macro_user_links (primary_macro_id, child_macro_id, link_id)+ VALUES ($1, $2, $3)+ ON CONFLICT DO NOTHING"#,+ primary_macro_id,+ child_macro_id,+ link_id,+ )+ .execute(&self.inner)+ .await?;+ Ok(())+ }++ /// Seed one user, adopting rows the signup webhook may already have+ /// created for the email (their `macro_user` id wins over the derived+ /// one so login-created accounts stay intact).+ #[tracing::instrument(skip(self), err)]+ pub async fn adopt_or_seed_user(&self, args: AdoptOrSeedUserArgs) -> anyhow::Result<()> {+ let AdoptOrSeedUserArgs {+ email,+ user_id,+ derived_macro_user_id,+ first_name,+ last_name,+ stripe_customer_id,+ extra_roles,+ } = args;+ let (email, user_id) = (email.as_str(), user_id.as_str());+ let (first_name, last_name) = (first_name.as_str(), last_name.as_str());+ let stripe_customer_id = stripe_customer_id.as_str();+ let mut transaction = self.inner.begin().await?;++ let existing: Option<Uuid> =+ sqlx::query_scalar!("SELECT id FROM macro_user WHERE email = $1 LIMIT 1", email)+ .fetch_optional(transaction.as_mut())+ .await?;++ let macro_user_id = match existing {+ Some(id) => id,+ None => {+ sqlx::query!(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id, has_trialed)+ VALUES ($1, $2, $3, $4, false)"#,+ derived_macro_user_id,+ email,+ email,+ stripe_customer_id,+ )+ .execute(transaction.as_mut())+ .await?;+ derived_macro_user_id+ }+ };++ sqlx::query!(+ r#"INSERT INTO "User" (id, email, "stripeCustomerId", macro_user_id, "tutorialComplete", "hasOnboardingDocuments")+ VALUES ($1, $2, $3, $4, true, true)+ ON CONFLICT (id) DO UPDATE SET+ macro_user_id = EXCLUDED.macro_user_id,+ "tutorialComplete" = true,+ "hasOnboardingDocuments" = true"#,+ user_id,+ email,+ stripe_customer_id,+ macro_user_id,+ )+ .execute(transaction.as_mut())+ .await?;++ sqlx::query!(+ r#"INSERT INTO macro_user_email_verification (macro_user_id, email, is_verified)+ VALUES ($1, $2, true)+ ON CONFLICT (email) DO UPDATE SET+ macro_user_id = EXCLUDED.macro_user_id,+ is_verified = true"#,+ macro_user_id,+ email,+ )+ .execute(transaction.as_mut())+ .await?;++ sqlx::query!(+ r#"INSERT INTO macro_user_info (macro_user_id, first_name, last_name)+ VALUES ($1, $2, $3)+ ON CONFLICT (macro_user_id) DO UPDATE SET+ first_name = EXCLUDED.first_name,+ last_name = EXCLUDED.last_name"#,+ macro_user_id,+ first_name,+ last_name,+ )+ .execute(transaction.as_mut())+ .await?;++ // Converge on exactly self_serve + the configured roles, dropping+ // whatever a previous apply granted.+ sqlx::query!(r#"DELETE FROM "RolesOnUsers" WHERE "userId" = $1"#, user_id)+ .execute(transaction.as_mut())+ .await?;+ sqlx::query!(+ r#"INSERT INTO "RolesOnUsers" ("userId", "roleId") VALUES ($1, 'self_serve')+ ON CONFLICT DO NOTHING"#,+ user_id,+ )+ .execute(transaction.as_mut())+ .await?;++ for role in &extra_roles {+ sqlx::query!(+ r#"INSERT INTO "RolesOnUsers" ("userId", "roleId") VALUES ($1, $2)+ ON CONFLICT DO NOTHING"#,+ user_id,+ role,+ )+ .execute(transaction.as_mut())+ .await?;+ }++ transaction.commit().await?;+ Ok(())+ }++ /// Mark a document's content as ready at the given location+ /// (`sync_service` for native markdown, `object_storage` for uploads).+ #[tracing::instrument(skip(self), err)]+ pub async fn set_document_content_ready(+ &self,+ document_id: &str,+ location: &str,+ ) -> anyhow::Result<()> {+ sqlx::query!(+ r#"UPDATE "Document"+ SET uploaded = true, "contentState" = 'ready', "contentLocation" = $2, "updatedAt" = NOW()+ WHERE id = $1"#,+ document_id,+ location,+ )+ .execute(&self.inner)+ .await?;+ Ok(())+ }++ /// Upsert pairwise contact connections, the rows the contacts worker+ /// derives from channel/team membership messages. Pairs must already be+ /// normalized (`user1 <= user2`, no self-pairs).+ #[tracing::instrument(skip(self, pairs), err)]+ pub async fn insert_contact_connections(+ &self,+ pairs: Vec<(String, String)>,+ ) -> anyhow::Result<()> {+ if pairs.is_empty() {+ return Ok(());+ }+ let (users1, users2): (Vec<String>, Vec<String>) = pairs.into_iter().unzip();+ sqlx::query!(+ "INSERT INTO contacts_connections(user1, user2)+ SELECT * FROM unnest($1::text[], $2::text[])+ ON CONFLICT(user1, user2) DO UPDATE SET updated_at = now()",+ &users1,+ &users2,+ )+ .execute(&self.inner)+ .await?;+ Ok(())+ }++ /// Read-only handle to the underlying pool (for the matrix verifier).+ pub fn pool(&self) -> sqlx::PgPool {+ self.inner.clone()+ }}diff --git a/tooling/xtask/crates/xtask_local/src/local/cli.rs b/tooling/xtask/crates/xtask_local/src/local/cli.rsindex 37ab9f4a39..d8c400e97c 100644--- a/tooling/xtask/crates/xtask_local/src/local/cli.rs+++ b/tooling/xtask/crates/xtask_local/src/local/cli.rs@@ -36,6 +36,8 @@ enum Cmd {KafkaProvision(InstanceArgs),/// Preflight checks (docker, toolchain, ports, env sources, images).DoctorLocal(InstanceArgs),+ /// Show an instance's endpoints and container states without starting anything.+ StatusLocal(InstanceArgs),/// Stop an instance's containers (keep volumes).StopLocal(InstanceArgs),/// Drop, recreate, and migrate the instance database.@@ -176,6 +178,10 @@ fn run(cli: Cli) -> Result<()> {super::kafka::provision(&instance)}Cmd::DoctorLocal(a) => super::doctor::run(&a),+ Cmd::StatusLocal(a) => {+ let instance = super::instance::Instance::derive(a.instance.as_deref(), a.port_base)?;+ super::status::run(&instance)+ }Cmd::StopLocal(a) => super::stop(&a),Cmd::ResetLocal(a) => super::reset(&a),Cmd::DestroyLocal(a) => super::destroy(&a),diff --git a/tooling/xtask/crates/xtask_local/src/local/docker.rs b/tooling/xtask/crates/xtask_local/src/local/docker.rsindex 0e27d69c66..4baaefc0ab 100644--- a/tooling/xtask/crates/xtask_local/src/local/docker.rs+++ b/tooling/xtask/crates/xtask_local/src/local/docker.rs@@ -81,3 +81,64 @@ fn already_exists(e: &bollard::errors::Error) -> bool {let s = e.to_string();s.contains("already exists") || s.contains("409")}++/// A container belonging to a compose project, as `status-local` reports it.+pub struct ProjectContainer {+ /// Container name (without the leading slash).+ pub name: String,+ /// Whether the container is currently running.+ pub running: bool,+ /// Human-readable status, e.g. `Up 3 hours (healthy)`.+ pub status: String,+ /// Published host ports, sorted and deduplicated.+ pub host_ports: Vec<u16>,+}++/// List every container (running or not) labeled with the compose `project`.+pub fn project_containers(project: &str) -> Result<Vec<ProjectContainer>> {+ use bollard::models::ContainerSummaryStateEnum;+ use bollard::query_parameters::ListContainersOptionsBuilder;++ block_on(async {+ let docker = connect()?;+ let filters = std::collections::HashMap::from([(+ "label",+ vec![format!("com.docker.compose.project={project}")],+ )]);+ let options = ListContainersOptionsBuilder::new()+ .all(true)+ .filters(&filters)+ .build();+ let mut containers: Vec<ProjectContainer> = docker+ .list_containers(Some(options))+ .await+ .context("listing containers")?+ .into_iter()+ .map(|c| {+ let name = c+ .names+ .unwrap_or_default()+ .first()+ .map(|n| n.trim_start_matches('/').to_string())+ .or(c.id)+ .unwrap_or_default();+ let mut host_ports: Vec<u16> = c+ .ports+ .unwrap_or_default()+ .iter()+ .filter_map(|p| p.public_port)+ .collect();+ host_ports.sort_unstable();+ host_ports.dedup();+ ProjectContainer {+ name,+ running: c.state == Some(ContainerSummaryStateEnum::RUNNING),+ status: c.status.unwrap_or_default(),+ host_ports,+ }+ })+ .collect();+ containers.sort_by(|a, b| a.name.cmp(&b.name));+ Ok(containers)+ })+}diff --git a/tooling/xtask/crates/xtask_local/src/local/inventory.rs b/tooling/xtask/crates/xtask_local/src/local/inventory.rsindex e567ac0ecc..d97d4f9add 100644--- a/tooling/xtask/crates/xtask_local/src/local/inventory.rs+++ b/tooling/xtask/crates/xtask_local/src/local/inventory.rs@@ -62,10 +62,13 @@ impl RustService {/// Cargo features to re-enable alongside `--no-default-features` for this/// service's local build (empty = none). Only `search_processing_service`- /// needs this: dropping default features removes the amd64-only `pdf`- /// feature, but its bin still requires `processing`/`service`.+ /// needs this: `authentication_service` opts into local passwordless code+ /// responses, and dropping `search_processing_service` default features+ /// removes the amd64-only `pdf` feature, but its bin still requires+ /// `processing`/`service`.pub fn build_features(&self) -> &'static [&'static str] {match self.cargo_bin {+ "authentication_service" => &["return_passwordless_code"],"search_processing_service" => &["processing", "service"],_ => &[],}diff --git a/tooling/xtask/crates/xtask_local/src/local/local_env.rs b/tooling/xtask/crates/xtask_local/src/local/local_env.rsindex 221d724c45..f50fa0be1d 100644--- a/tooling/xtask/crates/xtask_local/src/local/local_env.rs+++ b/tooling/xtask/crates/xtask_local/src/local/local_env.rs@@ -98,6 +98,14 @@ impl InfraEnv {env.insert("OPENSEARCH_URL".into(), self.opensearch_url.clone());env.insert("LOCAL_AWS_URL".into(), self.local_aws_url.clone());env.insert("KAFKA_BROKERS".into(), self.kafka_brokers.clone());+ // In-network services resolve the gateway through the OVERRIDE_ var;+ // without it the resolver's Environment::Local default+ // (http://localhost:8082) points at the calling container itself and+ // every realtime push silently fails.+ env.insert(+ "OVERRIDE_CONNECTION_GATEWAY_URL".into(),+ "http://connection-gateway:8080".into(),+ );// Dummy creds: the SDK talks to LocalStack, never real AWS.env.insert("AWS_ACCESS_KEY_ID".into(), "test".into());env.insert("AWS_SECRET_ACCESS_KEY".into(), "test".into());diff --git a/tooling/xtask/crates/xtask_local/src/local/mod.rs b/tooling/xtask/crates/xtask_local/src/local/mod.rsindex 43f091808c..09823f0fc9 100644--- a/tooling/xtask/crates/xtask_local/src/local/mod.rs+++ b/tooling/xtask/crates/xtask_local/src/local/mod.rs@@ -1,7 +1,7 @@//! xtask-owned local & dev orchestration.//!//! `just run_local`, `just run_dev`, and the supporting-//! `doctor`/`validate`/`stop`/`reset`/`destroy` recipes all delegate here.+//! `doctor`/`validate`/`status`/`stop`/`reset`/`destroy` recipes all delegate here.//! This module owns: building Linux service binaries on the host (zigbuild),//! the minimal runtime image, the typed service inventory, per-instance//! isolation, environment layering, generated docker-compose overrides, local@@ -38,6 +38,7 @@ pub mod resources;pub mod snapshot;pub mod stack;pub mod stage;+pub mod status;pub mod summary;pub mod validate;diff --git a/tooling/xtask/crates/xtask_local/src/local/status.rs b/tooling/xtask/crates/xtask_local/src/local/status.rsnew file mode 100644index 0000000000..7920426d1e--- /dev/null+++ b/tooling/xtask/crates/xtask_local/src/local/status.rs@@ -0,0 +1,103 @@+//! `status-local`: an on-demand view of an instance's stack — the endpoint+//! list with live TCP probes plus per-container states. Read-only: nothing is+//! built, started, or regenerated.++use std::net::{SocketAddr, TcpStream};+use std::time::Duration;++use anyhow::Result;+use console::Style;++use super::instance::Instance;+use super::{docker, summary};++/// Whether something on the host is accepting connections on `port`.+fn listening(port: u16) -> bool {+ let addr = SocketAddr::from(([127, 0, 0, 1], port));+ TcpStream::connect_timeout(&addr, Duration::from_millis(250)).is_ok()+}++/// Print endpoints (with reachability) and container states for `instance`.+pub fn run(instance: &Instance) -> Result<()> {+ let dim = Style::new().dim();+ let link = Style::new().cyan();+ let up = Style::new().green().apply_to("●").to_string();+ let down = dim.apply_to("○").to_string();++ println!();+ println!(+ "{}",+ Style::new().bold().apply_to(format!(+ "macro local stack — instance {} (project {})",+ instance.name(),+ instance.project_name()+ ))+ );+ println!();++ println!(+ " {}",+ dim.apply_to("endpoints (● listening / ○ not answering)")+ );+ for (label, url, port) in summary::endpoint_rows(instance) {+ let dot = if listening(port) { &up } else { &down };+ println!(+ " {dot} {}{}",+ dim.apply_to(format!("{label:<14}")),+ link.apply_to(url)+ );+ }+ println!();++ match docker::project_containers(instance.project_name()) {+ Ok(containers) if containers.is_empty() => {+ println!(+ " {}",+ dim.apply_to(format!(+ "no containers for project {} — start the stack with `just run_local`",+ instance.project_name()+ ))+ );+ }+ Ok(containers) => {+ println!(" {}", dim.apply_to("containers"));+ let name_width = containers.iter().map(|c| c.name.len()).max().unwrap_or(0);+ for c in &containers {+ let dot = if c.running { &up } else { &down };+ let ports = c+ .host_ports+ .iter()+ .map(|p| p.to_string())+ .collect::<Vec<_>>()+ .join(",");+ println!(+ " {dot} {:<name_width$} {:<12} {}",+ c.name,+ ports,+ dim.apply_to(&c.status)+ );+ }+ }+ Err(e) => println!(+ " {}",+ dim.apply_to(format!("containers unavailable: {e:#}"))+ ),+ }+ println!();++ let generated_env = instance.artifact_dir().join("local.generated.env");+ if generated_env.exists() {+ println!(+ " {}{}",+ dim.apply_to(format!("{:<16}", "logs")),+ summary::logs_command(instance, &generated_env)+ );+ }+ println!(+ " {}{}",+ dim.apply_to(format!("{:<16}", "stop")),+ summary::stop_command(instance)+ );+ println!();+ Ok(())+}diff --git a/tooling/xtask/crates/xtask_local/src/local/summary.rs b/tooling/xtask/crates/xtask_local/src/local/summary.rsindex 9751f21c94..bd35529afe 100644--- a/tooling/xtask/crates/xtask_local/src/local/summary.rs+++ b/tooling/xtask/crates/xtask_local/src/local/summary.rs@@ -1,10 +1,83 @@//! The final startup summary (the spec's Output Contract).+use std::path::Path;+use console::Style;use super::env_layer::ResolvedEnv;use super::instance::{Instance, Port};-use super::{Mode, proxy};+use super::{Mode, frontend, mailpit, proxy};++/// The host-facing endpoints of an instance: (label, url, host port).+/// Shared by the startup summary and `status-local`.+pub fn endpoint_rows(instance: &Instance) -> Vec<(&'static str, String, u16)> {+ vec![+ (+ "frontend",+ frontend::url(instance),+ instance.port(Port::Frontend),+ ),+ ("proxy", proxy::url(instance), instance.port(Port::Proxy)),+ (+ "fusionauth",+ format!("http://localhost:{}", instance.port(Port::FusionAuth)),+ instance.port(Port::FusionAuth),+ ),+ (+ "mailpit",+ mailpit::direct_ui_url(instance),+ instance.port(Port::MailpitUi),+ ),+ (+ "localstack",+ format!("http://localhost:{}", instance.port(Port::LocalStack)),+ instance.port(Port::LocalStack),+ ),+ (+ "postgres",+ format!(+ "postgres://user:password@localhost:{}/macrodb",+ instance.port(Port::Postgres)+ ),+ instance.port(Port::Postgres),+ ),+ (+ "redis",+ format!("redis://localhost:{}", instance.port(Port::Redis)),+ instance.port(Port::Redis),+ ),+ (+ "kafka",+ format!("localhost:{}", instance.port(Port::Kafka)),+ instance.port(Port::Kafka),+ ),+ ]+}++/// The `docker compose logs -f` invocation for the instance.+pub fn logs_command(instance: &Instance, generated_env: &Path) -> String {+ let repo_root = super::repo_root();+ let base_compose = repo_root.join("docker/docker-compose.yml");+ let override_compose = instance.artifact_dir().join("docker-compose.override.yml");+ format!(+ "MACRO_ENV_FILE={:?} docker compose --project-directory {:?} -p {} -f {:?} -f {:?} --env-file {:?} logs -f",+ generated_env,+ repo_root,+ instance.project_name(),+ base_compose,+ override_compose,+ generated_env,+ )+}++/// The `just stop_local` invocation for the instance.+pub fn stop_command(instance: &Instance) -> String {+ if instance.is_default() {+ "just stop_local".to_string()+ } else {+ format!("just stop_local --instance {}", instance.name())+ }+}/// Print the mode/instance/endpoints block after a successful startup./// `frontend_url` differs by flow: the dev-server origin for `run_local`, the@@ -60,53 +133,20 @@ pub fn print(.unwrap_or_else(|| "(none)".into()),);row("generated env", env.generated_path.display().to_string());- row("frontend", frontend_url.to_string());-- if mode.spec().show_infra_in_summary {- row("proxy", proxy::url(instance));- row(- "fusionauth",- format!("http://localhost:{}", instance.port(Port::FusionAuth)),- );- row("mailpit", mailpit_url.to_string());- row(- "localstack",- format!("http://localhost:{}", instance.port(Port::LocalStack)),- );- row(- "postgres",- format!(- "postgres://user:password@localhost:{}/macrodb",- instance.port(Port::Postgres)- ),- );- row(- "redis",- format!("redis://localhost:{}", instance.port(Port::Redis)),- );- row("kafka", format!("localhost:{}", instance.port(Port::Kafka)));+ // The frontend and mailpit rows come from the caller (they differ by+ // flow); the rest of the endpoint list is shared with `status-local`.+ for (label, url, _port) in endpoint_rows(instance) {+ if label != "frontend" && !mode.spec().show_infra_in_summary {+ continue;+ }+ let value = match label {+ "frontend" => frontend_url.to_string(),+ "mailpit" => mailpit_url.to_string(),+ _ => url,+ };+ row(label, value);}-- let repo_root = super::repo_root();- let base_compose = repo_root.join("docker/docker-compose.yml");- let override_compose = instance.artifact_dir().join("docker-compose.override.yml");- row(- "logs",- format!(- "MACRO_ENV_FILE={:?} docker compose --project-directory {:?} -p {} -f {:?} -f {:?} --env-file {:?} logs -f",- env.generated_path,- repo_root,- instance.project_name(),- base_compose,- override_compose,- env.generated_path,- ),- );- let stop = if instance.is_default() {- "just stop_local".to_string()- } else {- format!("just stop_local --instance {}", instance.name())- };- row("stop", stop);+ row("logs", logs_command(instance, &env.generated_path));+ row("stop", stop_command(instance));println!();}