The open-source app everyone uses to manage agents at work
TypeScript acpxagent-orchestrationagent-skillsagentic-aiai-agentsai-engineeringai-governanceai-toolsautonomous-agentsclaudeclaude-codeclaude-skillscodexhermesllmmcpmulti-agentopenclawproject-managementworkflow-automation
fix(server): permit verified question-delivery history to sleep (#15851)
Devin Foleyb36960b75871
diff --git a/doc/DATABASE.md b/doc/DATABASE.mdindex c6e9c5474d..2177689e1b 100644--- a/doc/DATABASE.md+++ b/doc/DATABASE.md@@ -433,6 +433,14 @@ run/turn ids, payload digest, attempt/acknowledgement state, and one of `steered`issue_thread_interactions.result`. Deleting the interaction cascades its receipt,while deleting a referenced run clears that run pointer without deleting history.+The question-history index covers `(company_id, idempotency_key)` for every+`question-response:` wake state, including failed, cancelled, and skipped+receipts excluded from the delivery-idempotency fence. Migration `0332` creates+this nonunique index concurrently through the standard migration executor.+Apply it with `pnpm db:migrate` on a direct connection before enabling the new+sleep guard. The executor retries interrupted invalid builds and records history+only after the index is valid. It does not delete delivery or wake records.+## Plugin database namespacesThe plugin runtime tracks plugin-owned database namespaces and migrations in `plugin_database_namespaces` and `plugin_migrations`. Hosted deployments that separate runtime and migration connections should set `DATABASE_MIGRATION_URL`; plugin namespace migration work uses the migration connection when present.diff --git a/doc/idle-sleep-safety.md b/doc/idle-sleep-safety.mdindex 30622581e2..b4bf960ce5 100644--- a/doc/idle-sleep-safety.md+++ b/doc/idle-sleep-safety.md@@ -129,6 +129,16 @@ company/agent's linked run has finished without retry or accounting debt.Image-setup history still blocks: promotion can succeed before teardown isconfirmed, so a terminal label does not prove that its provider resource is gone.+Completed question-answer deliveries permit sleep only after acknowledgement+and completion of their exact target run in the same company, without retry or+accounting debt. A fallback without a target run requires its exact question's+finished durable wake receipt in the same company. A coalesced fallback also+requires its exact company/agent's linked run to finish without retry or+accounting debt. The question-history index covers every wake status.+Pending deliveries, missing+completion evidence, and unfinished handoffs still block. Failed deliveries+without a pending target are history; other work checks still apply.+Every enabled plugin blocks sleep. A version label does not prove that arbitraryworker code has no background activity. No plugin approval or configurationbypass is supported. Scheduled and externally triggered work needs a durablediff --git a/packages/db/src/client.ts b/packages/db/src/client.tsindex 3f6061deaa..199a28ebe4 100644--- a/packages/db/src/client.ts+++ b/packages/db/src/client.ts@@ -467,12 +467,12 @@ async function recordMigrationHistoryEntry();}-// These idempotent privacy migrations commit keyset batches inside their DO-// blocks. Execute each statement at top level so DDL locks and completed batches-// are released before the next batch. History is recorded only after completion.-const MIGRATIONS_WITH_BATCH_COMMITS = new Set([+// These idempotent migrations require top-level statements for batch commits+// or concurrent index builds. History is recorded only after completion.+const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set(["0313_private_task_access.sql","0314_private_task_draft_assets.sql",+ "0332_little_night_nurse.sql",]);async function applyPendingMigrationsManually(@@ -493,7 +493,13 @@ async function applyPendingMigrationsManually(try {// A session lock survives each batch COMMIT. Reserve the connection so// pool rotation cannot release it while another migrator is waiting.- await sql`SELECT pg_advisory_lock(hashtextextended('paperclip:migrations', 0))`;+ // A blocking lock SELECT retains its statement snapshot while waiting.+ // A partial concurrent index build can wait for that snapshot, forming a+ // deadlock with this lock. Each failed try ends its snapshot before sleep.+ while (!(await sql<{ locked: boolean }[]>`+ SELECT pg_try_advisory_lock(hashtextextended('paperclip:migrations', 0)) AS locked`)[0]?.locked) {+ await new Promise((resolve) => setTimeout(resolve, 100));+ }const { migrationTableSchema, columnNames } = await ensureMigrationJournalTable(sql);const qualifiedTable = `${quoteIdentifier(migrationTableSchema)}.${quoteIdentifier(DRIZZLE_MIGRATIONS_TABLE)}`;@@ -511,7 +517,7 @@ async function applyPendingMigrationsManually(const applyMigration = async () => {for (const statement of splitMigrationStatements(migrationContent)) {- if (MIGRATIONS_WITH_BATCH_COMMITS.has(migrationFile)) {+ if (MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS.has(migrationFile)) {// A cancelled concurrent build leaves an invalid index. IF NOT// EXISTS alone would skip it on retry and journal an incomplete index.const index = statement.replace(/^\s*--.*$/gm, "").trim()@@ -545,7 +551,7 @@ async function applyPendingMigrationsManually(folderMillisByFileName.get(migrationFile) ?? Date.now(),);};- if (MIGRATIONS_WITH_BATCH_COMMITS.has(migrationFile)) {+ if (MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS.has(migrationFile)) {await applyMigration();} else {await runInTransaction(sql, applyMigration);diff --git a/packages/db/src/heartbeat-run-issue-privacy-migration.test.ts b/packages/db/src/heartbeat-run-issue-privacy-migration.test.tsindex bb01e215a2..6883c0c799 100644--- a/packages/db/src/heartbeat-run-issue-privacy-migration.test.ts+++ b/packages/db/src/heartbeat-run-issue-privacy-migration.test.ts@@ -229,7 +229,8 @@ describeEmbeddedPostgres("heartbeat run issue privacy migration", () => {contender = applyPendingMigrations(database.connectionString).then(() => null, error => error);await expect.poll(async () => {const [row] = await sql`SELECT count(*)::int AS n FROM pg_stat_activity- WHERE datname = current_database() AND wait_event = 'advisory'+ WHERE datname = current_database() AND query LIKE '%SELECT pg_try_advisory_lock%'+ AND query NOT LIKE '%FROM pg_stat_activity%'AND strpos(query, 'paperclip:migrations') > 0`;return row.n;}, { timeout: 10_000 }).toBe(1);diff --git a/packages/db/src/migrations/0332_little_night_nurse.sql b/packages/db/src/migrations/0332_little_night_nurse.sqlnew file mode 100644index 0000000000..dd23f331cb--- /dev/null+++ b/packages/db/src/migrations/0332_little_night_nurse.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS "agent_wakeup_requests_question_response_history_idx" ON "agent_wakeup_requests" USING btree ("company_id","idempotency_key") WHERE "agent_wakeup_requests"."idempotency_key" LIKE 'question-response:%';\ No newline at end of filediff --git a/packages/db/src/migrations/meta/0321_snapshot.json b/packages/db/src/migrations/meta/0332_snapshot.jsonsimilarity index 96%rename from packages/db/src/migrations/meta/0321_snapshot.jsonrename to packages/db/src/migrations/meta/0332_snapshot.jsonindex f6a27b20ed..80f174738d 100644--- a/packages/db/src/migrations/meta/0321_snapshot.json+++ b/packages/db/src/migrations/meta/0332_snapshot.json@@ -1,6 +1,6 @@{- "id": "3a76c99a-51c4-41d7-b7e2-12b55d8c7d08",- "prevId": "d6277736-9c05-4304-8d16-52dc0d2fbaef",+ "id": "8dadd21e-8c02-4ada-b99a-55ba133e7f70",+ "prevId": "5c09a14d-e323-49b1-b855-dcd12b974bcc","version": "7","dialect": "postgresql","tables": {@@ -416,6 +416,12 @@"primaryKey": false,"notNull": false},+ "fast_response_request_id": {+ "name": "fast_response_request_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },"agent_id": {"name": "agent_id","type": "uuid",@@ -462,6 +468,27 @@}},"indexes": {+ "budget_reservations_fast_response_idx": {+ "name": "budget_reservations_fast_response_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "fast_response_request_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"budget_reservations_decision_idx": {"name": "budget_reservations_decision_idx","columns": [@@ -580,7 +607,7 @@"checkConstraints": {"budget_reservations_source_check": {"name": "budget_reservations_source_check",- "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int = 1"+ "value": "(\"budget_reservations\".\"run_id\" is not null)::int + (\"budget_reservations\".\"decision_invocation_id\" is not null)::int + (\"budget_reservations\".\"fast_response_request_id\" is not null)::int = 1"},"budget_reservations_state_check": {"name": "budget_reservations_state_check",@@ -3737,6 +3764,28 @@"method": "btree","with": {}},+ "agent_wakeup_requests_question_response_history_idx": {+ "name": "agent_wakeup_requests_question_response_history_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"agent_wakeup_requests\".\"idempotency_key\" LIKE 'question-response:%'",+ "concurrently": true,+ "method": "btree",+ "with": {}+ },"agent_wakeup_requests_connection_intent_delivery_idempotency_uq": {"name": "agent_wakeup_requests_connection_intent_delivery_idempotency_uq","columns": [@@ -4810,67 +4859,8 @@},"isRLSEnabled": false},- "public.announcement_dismissals": {- "name": "announcement_dismissals",- "schema": "",- "columns": {- "user_id": {- "name": "user_id",- "type": "text",- "primaryKey": false,- "notNull": true- },- "announcement_id": {- "name": "announcement_id",- "type": "text",- "primaryKey": false,- "notNull": true- },- "dismissed_at": {- "name": "dismissed_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {- "announcement_dismissals_user_id_announcement_id_pk": {- "name": "announcement_dismissals_user_id_announcement_id_pk",- "columns": [- "user_id",- "announcement_id"- ]- }- },- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.announcement_publications": {- "name": "announcement_publications",- "schema": "",- "columns": {- "announcement_id": {- "name": "announcement_id",- "type": "text",- "primaryKey": true,- "notNull": true- }- },- "indexes": {},- "foreignKeys": {},- "compositePrimaryKeys": {},- "uniqueConstraints": {},- "policies": {},- "checkConstraints": {},- "isRLSEnabled": false- },- "public.approval_comments": {- "name": "approval_comments",+ "public.ai_subscription_connections": {+ "name": "ai_subscription_connections","schema": "","columns": {"id": {@@ -4886,66 +4876,64 @@"primaryKey": false,"notNull": true},- "approval_id": {- "name": "approval_id",+ "connection_id": {+ "name": "connection_id","type": "uuid","primaryKey": false,"notNull": true},- "author_agent_id": {- "name": "author_agent_id",+ "grant_id": {+ "name": "grant_id","type": "uuid","primaryKey": false,- "notNull": false- },- "author_user_id": {- "name": "author_user_id",- "type": "text",- "primaryKey": false,- "notNull": false+ "notNull": true},- "body": {- "name": "body",+ "credential_key": {+ "name": "credential_key","type": "text","primaryKey": false,"notNull": true},- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "updated_at": {- "name": "updated_at",- "type": "timestamp with time zone",+ "subscription_id": {+ "name": "subscription_id",+ "type": "uuid","primaryKey": false,- "notNull": true,- "default": "now()"+ "notNull": true}},"indexes": {- "approval_comments_company_idx": {- "name": "approval_comments_company_idx",+ "ai_subscription_connections_grant_idx": {+ "name": "ai_subscription_connections_grant_idx","columns": [{"expression": "company_id","isExpression": false,"asc": true,"nulls": "last"+ },+ {+ "expression": "grant_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"}],- "isUnique": false,+ "isUnique": true,"concurrently": false,"method": "btree","with": {}},- "approval_comments_approval_idx": {- "name": "approval_comments_approval_idx",+ "ai_subscription_connections_credential_idx": {+ "name": "ai_subscription_connections_credential_idx","columns": [{- "expression": "approval_id",+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "credential_key","isExpression": false,"asc": true,"nulls": "last"@@ -4956,17 +4944,17 @@"method": "btree","with": {}},- "approval_comments_approval_created_idx": {- "name": "approval_comments_approval_created_idx",+ "ai_subscription_connections_account_idx": {+ "name": "ai_subscription_connections_account_idx","columns": [{- "expression": "approval_id",+ "expression": "company_id","isExpression": false,"asc": true,"nulls": "last"},{- "expression": "created_at",+ "expression": "subscription_id","isExpression": false,"asc": true,"nulls": "last"@@ -4979,9 +4967,9 @@}},"foreignKeys": {- "approval_comments_company_id_companies_id_fk": {- "name": "approval_comments_company_id_companies_id_fk",- "tableFrom": "approval_comments",+ "ai_subscription_connections_company_id_companies_id_fk": {+ "name": "ai_subscription_connections_company_id_companies_id_fk",+ "tableFrom": "ai_subscription_connections","tableTo": "companies","columnsFrom": ["company_id"@@ -4989,33 +4977,46 @@"columnsTo": ["id"],- "onDelete": "no action",+ "onDelete": "cascade","onUpdate": "no action"},- "approval_comments_approval_id_approvals_id_fk": {- "name": "approval_comments_approval_id_approvals_id_fk",- "tableFrom": "approval_comments",- "tableTo": "approvals",+ "ai_subscription_connections_connection_id_tool_connections_id_fk": {+ "name": "ai_subscription_connections_connection_id_tool_connections_id_fk",+ "tableFrom": "ai_subscription_connections",+ "tableTo": "tool_connections","columnsFrom": [- "approval_id"+ "connection_id"],"columnsTo": ["id"],- "onDelete": "no action",+ "onDelete": "cascade","onUpdate": "no action"},- "approval_comments_author_agent_id_agents_id_fk": {- "name": "approval_comments_author_agent_id_agents_id_fk",- "tableFrom": "approval_comments",- "tableTo": "agents",+ "ai_subscription_connections_grant_id_connection_grants_id_fk": {+ "name": "ai_subscription_connections_grant_id_connection_grants_id_fk",+ "tableFrom": "ai_subscription_connections",+ "tableTo": "connection_grants","columnsFrom": [- "author_agent_id"+ "grant_id"],"columnsTo": ["id"],- "onDelete": "no action",+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_subscription_connections_subscription_id_ai_subscriptions_id_fk": {+ "name": "ai_subscription_connections_subscription_id_ai_subscriptions_id_fk",+ "tableFrom": "ai_subscription_connections",+ "tableTo": "ai_subscriptions",+ "columnsFrom": [+ "subscription_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade","onUpdate": "no action"}},@@ -5025,8 +5026,8 @@"checkConstraints": {},"isRLSEnabled": false},- "public.approvals": {- "name": "approvals",+ "public.ai_subscription_prices": {+ "name": "ai_subscription_prices","schema": "","columns": {"id": {@@ -5042,64 +5043,65 @@"primaryKey": false,"notNull": true},- "type": {- "name": "type",- "type": "text",+ "subscription_id": {+ "name": "subscription_id",+ "type": "uuid","primaryKey": false,"notNull": true},- "requested_by_agent_id": {- "name": "requested_by_agent_id",- "type": "uuid",+ "revision": {+ "name": "revision",+ "type": "integer","primaryKey": false,- "notNull": false+ "notNull": true},- "requested_by_user_id": {- "name": "requested_by_user_id",+ "plan": {+ "name": "plan","type": "text","primaryKey": false,+ "notNull": true+ },+ "amount_cents": {+ "name": "amount_cents",+ "type": "numeric(24, 7)",+ "primaryKey": false,"notNull": false},- "status": {- "name": "status",+ "currency": {+ "name": "currency","type": "text","primaryKey": false,"notNull": true,- "default": "'pending'"+ "default": "'USD'"},- "payload": {- "name": "payload",- "type": "jsonb",+ "cadence": {+ "name": "cadence",+ "type": "text","primaryKey": false,- "notNull": true+ "notNull": true,+ "default": "'month'"},- "decision_note": {- "name": "decision_note",+ "status": {+ "name": "status","type": "text","primaryKey": false,- "notNull": false+ "notNull": true,+ "default": "'active'"},- "decided_by_user_id": {- "name": "decided_by_user_id",+ "source": {+ "name": "source","type": "text","primaryKey": false,- "notNull": false+ "notNull": true},- "decided_at": {- "name": "decided_at",- "type": "timestamp with time zone",+ "source_url": {+ "name": "source_url",+ "type": "text","primaryKey": false,"notNull": false},- "created_at": {- "name": "created_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": true,- "default": "now()"- },- "updated_at": {- "name": "updated_at",+ "effective_at": {+ "name": "effective_at","type": "timestamp with time zone","primaryKey": false,"notNull": true,@@ -5107,23 +5109,32 @@}},"indexes": {- "approvals_company_status_type_idx": {- "name": "approvals_company_status_type_idx",+ "ai_subscription_prices_revision_idx": {+ "name": "ai_subscription_prices_revision_idx","columns": [{- "expression": "company_id",+ "expression": "subscription_id","isExpression": false,"asc": true,"nulls": "last"},{- "expression": "status",+ "expression": "revision","isExpression": false,"asc": true,"nulls": "last"- },+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_subscription_prices_company_idx": {+ "name": "ai_subscription_prices_company_idx",+ "columns": [{- "expression": "type",+ "expression": "company_id","isExpression": false,"asc": true,"nulls": "last"@@ -5136,9 +5147,9 @@}},"foreignKeys": {- "approvals_company_id_companies_id_fk": {- "name": "approvals_company_id_companies_id_fk",- "tableFrom": "approvals",+ "ai_subscription_prices_company_id_companies_id_fk": {+ "name": "ai_subscription_prices_company_id_companies_id_fk",+ "tableFrom": "ai_subscription_prices","tableTo": "companies","columnsFrom": ["company_id"@@ -5146,31 +5157,579 @@"columnsTo": ["id"],- "onDelete": "no action",+ "onDelete": "cascade","onUpdate": "no action"},- "approvals_requested_by_agent_id_agents_id_fk": {- "name": "approvals_requested_by_agent_id_agents_id_fk",- "tableFrom": "approvals",- "tableTo": "agents",+ "ai_subscription_prices_subscription_id_ai_subscriptions_id_fk": {+ "name": "ai_subscription_prices_subscription_id_ai_subscriptions_id_fk",+ "tableFrom": "ai_subscription_prices",+ "tableTo": "ai_subscriptions","columnsFrom": [- "requested_by_agent_id"+ "subscription_id"],"columnsTo": ["id"],- "onDelete": "no action",+ "onDelete": "cascade","onUpdate": "no action"}},"compositePrimaryKeys": {},"uniqueConstraints": {},"policies": {},- "checkConstraints": {},+ "checkConstraints": {+ "ai_subscription_prices_valid": {+ "name": "ai_subscription_prices_valid",+ "value": "(\"ai_subscription_prices\".\"amount_cents\" is null or \"ai_subscription_prices\".\"amount_cents\" >= 0) and \"ai_subscription_prices\".\"cadence\" in ('month','year') and \"ai_subscription_prices\".\"status\" in ('active','ended','excluded') and \"ai_subscription_prices\".\"source\" in ('catalog','user','unknown')"+ }+ },"isRLSEnabled": false},- "public.assets": {- "name": "assets",+ "public.ai_subscriptions": {+ "name": "ai_subscriptions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "account_key": {+ "name": "account_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "identity_verified": {+ "name": "identity_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "owner_user_ids": {+ "name": "owner_user_ids",+ "type": "text[]",+ "primaryKey": false,+ "notNull": true,+ "default": "'{}'::text[]"+ },+ "shared": {+ "name": "shared",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "detected_plan": {+ "name": "detected_plan",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "observed_at": {+ "name": "observed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_status": {+ "name": "refresh_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "merged_into_id": {+ "name": "merged_into_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "revision": {+ "name": "revision",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "ai_subscriptions_identity_idx": {+ "name": "ai_subscriptions_identity_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "account_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "ai_subscriptions_company_idx": {+ "name": "ai_subscriptions_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "ai_subscriptions_company_id_companies_id_fk": {+ "name": "ai_subscriptions_company_id_companies_id_fk",+ "tableFrom": "ai_subscriptions",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "ai_subscriptions_merged_into_id_ai_subscriptions_id_fk": {+ "name": "ai_subscriptions_merged_into_id_ai_subscriptions_id_fk",+ "tableFrom": "ai_subscriptions",+ "tableTo": "ai_subscriptions",+ "columnsFrom": [+ "merged_into_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "ai_subscriptions_no_self_merge": {+ "name": "ai_subscriptions_no_self_merge",+ "value": "\"ai_subscriptions\".\"merged_into_id\" is null or \"ai_subscriptions\".\"merged_into_id\" <> \"ai_subscriptions\".\"id\""+ }+ },+ "isRLSEnabled": false+ },+ "public.announcement_dismissals": {+ "name": "announcement_dismissals",+ "schema": "",+ "columns": {+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "announcement_id": {+ "name": "announcement_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "dismissed_at": {+ "name": "dismissed_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {+ "announcement_dismissals_user_id_announcement_id_pk": {+ "name": "announcement_dismissals_user_id_announcement_id_pk",+ "columns": [+ "user_id",+ "announcement_id"+ ]+ }+ },+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.announcement_publications": {+ "name": "announcement_publications",+ "schema": "",+ "columns": {+ "announcement_id": {+ "name": "announcement_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.approval_comments": {+ "name": "approval_comments",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "approval_id": {+ "name": "approval_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "author_agent_id": {+ "name": "author_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "author_user_id": {+ "name": "author_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "body": {+ "name": "body",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "approval_comments_company_idx": {+ "name": "approval_comments_company_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "approval_comments_approval_idx": {+ "name": "approval_comments_approval_idx",+ "columns": [+ {+ "expression": "approval_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "approval_comments_approval_created_idx": {+ "name": "approval_comments_approval_created_idx",+ "columns": [+ {+ "expression": "approval_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "created_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "approval_comments_company_id_companies_id_fk": {+ "name": "approval_comments_company_id_companies_id_fk",+ "tableFrom": "approval_comments",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "approval_comments_approval_id_approvals_id_fk": {+ "name": "approval_comments_approval_id_approvals_id_fk",+ "tableFrom": "approval_comments",+ "tableTo": "approvals",+ "columnsFrom": [+ "approval_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "approval_comments_author_agent_id_agents_id_fk": {+ "name": "approval_comments_author_agent_id_agents_id_fk",+ "tableFrom": "approval_comments",+ "tableTo": "agents",+ "columnsFrom": [+ "author_agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.approvals": {+ "name": "approvals",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "requested_by_agent_id": {+ "name": "requested_by_agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requested_by_user_id": {+ "name": "requested_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "payload": {+ "name": "payload",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "decision_note": {+ "name": "decision_note",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_by_user_id": {+ "name": "decided_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "decided_at": {+ "name": "decided_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "approvals_company_status_type_idx": {+ "name": "approvals_company_status_type_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "approvals_company_id_companies_id_fk": {+ "name": "approvals_company_id_companies_id_fk",+ "tableFrom": "approvals",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "approvals_requested_by_agent_id_agents_id_fk": {+ "name": "approvals_requested_by_agent_id_agents_id_fk",+ "tableFrom": "approvals",+ "tableTo": "agents",+ "columnsFrom": [+ "requested_by_agent_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.assets": {+ "name": "assets","schema": "","columns": {"id": {@@ -9945,7 +10504,7 @@},"chat_endpoints_provider_check": {"name": "chat_endpoints_provider_check",- "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"+ "value": "\"chat_endpoints\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'speko', 'agentmail', 'imessage-photon')"},"chat_endpoints_status_check": {"name": "chat_endpoints_status_check",@@ -10130,7 +10689,7 @@"checkConstraints": {"chat_external_principals_provider_check": {"name": "chat_external_principals_provider_check",- "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"+ "value": "\"chat_external_principals\".\"provider\" in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'speko', 'agentmail', 'imessage-photon')"},"chat_external_principals_kind_check": {"name": "chat_external_principals_kind_check",@@ -11456,6 +12015,31 @@"primaryKey": false,"notNull": true},+ "owner_type": {+ "name": "owner_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'personal'"+ },+ "owner_login": {+ "name": "owner_login",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "app_name": {+ "name": "app_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "handoff": {+ "name": "handoff",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": false+ },"status": {"name": "status","type": "text",@@ -12011,184 +12595,1246 @@"primaryKey": false,"notNull": true},- "publication_id": {- "name": "publication_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },+ "publication_id": {+ "name": "publication_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "comment_id": {+ "name": "comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "attachment_id": {+ "name": "attachment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "principal_id": {+ "name": "principal_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "authorized_user_id": {+ "name": "authorized_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "runtime_generation": {+ "name": "runtime_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "credential_fingerprint": {+ "name": "credential_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_generation": {+ "name": "conversation_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "source_digest": {+ "name": "source_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "authority_digest": {+ "name": "authority_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tenant_id": {+ "name": "tenant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "bot_app_id": {+ "name": "bot_app_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "aad_object_id": {+ "name": "aad_object_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_conversation_id": {+ "name": "provider_conversation_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_user_id": {+ "name": "provider_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "sha256": {+ "name": "sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "byte_size": {+ "name": "byte_size",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "filename": {+ "name": "filename",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "token_sha256": {+ "name": "token_sha256",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "phase": {+ "name": "phase",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'consent_pending'"+ },+ "version": {+ "name": "version",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 1+ },+ "attempt_id": {+ "name": "attempt_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "attempt_expires_at": {+ "name": "attempt_expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "consent_message_id": {+ "name": "consent_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "file_info_message_id": {+ "name": "file_info_message_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_activity_id": {+ "name": "response_activity_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "response_digest": {+ "name": "response_digest",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "private_state": {+ "name": "private_state",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "reason": {+ "name": "reason",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_teams_file_transfers_publication_uq": {+ "name": "chat_teams_file_transfers_publication_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "publication_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_teams_file_transfers_token_uq": {+ "name": "chat_teams_file_transfers_token_uq",+ "columns": [+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "token_sha256",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_teams_file_transfers_work_idx": {+ "name": "chat_teams_file_transfers_work_idx",+ "columns": [+ {+ "expression": "phase",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "attempt_expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_teams_file_transfers_company_id_companies_id_fk": {+ "name": "chat_teams_file_transfers_company_id_companies_id_fk",+ "tableFrom": "chat_teams_file_transfers",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_teams_file_transfers_issue_id_issues_id_fk": {+ "name": "chat_teams_file_transfers_issue_id_issues_id_fk",+ "tableFrom": "chat_teams_file_transfers",+ "tableTo": "issues",+ "columnsFrom": [+ "issue_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "restrict",+ "onUpdate": "no action"+ },+ "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {+ "name": "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk",+ "tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_endpoints",+ "columnsFrom": [+ "company_id",+ "endpoint_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk": {+ "name": "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk",+ "tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_publications",+ "columnsFrom": [+ "company_id",+ "publication_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk": {+ "name": "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk",+ "tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_conversations",+ "columnsFrom": [+ "company_id",+ "conversation_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk": {+ "name": "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk",+ "tableFrom": "chat_teams_file_transfers",+ "tableTo": "chat_external_principals",+ "columnsFrom": [+ "company_id",+ "principal_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_teams_file_transfers_phase_check": {+ "name": "chat_teams_file_transfers_phase_check",+ "value": "\"chat_teams_file_transfers\".\"phase\" in ('consent_pending','consent_sending','consent_unknown','awaiting_consent','upload_pending','uploading','upload_unknown','file_info_pending','file_info_sending','file_info_unknown','delivered','declined','expired','cancelled','conflict')"+ },+ "chat_teams_file_transfers_bounds_check": {+ "name": "chat_teams_file_transfers_bounds_check",+ "value": "\"chat_teams_file_transfers\".\"version\" > 0 and \"chat_teams_file_transfers\".\"runtime_generation\" >= 0 and \"chat_teams_file_transfers\".\"conversation_generation\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" < 62914560"+ },+ "chat_teams_file_transfers_hash_check": {+ "name": "chat_teams_file_transfers_hash_check",+ "value": "\"chat_teams_file_transfers\".\"source_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"authority_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"sha256\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"token_sha256\" ~ '^[a-f0-9]{64}$'"+ },+ "chat_teams_file_transfers_attempt_check": {+ "name": "chat_teams_file_transfers_attempt_check",+ "value": "(\"chat_teams_file_transfers\".\"attempt_id\" is null) = (\"chat_teams_file_transfers\".\"attempt_expires_at\" is null)"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_callbacks": {+ "name": "chat_voice_callbacks",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "phone_number": {+ "name": "phone_number",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_voice_callbacks_owner_uq": {+ "name": "chat_voice_callbacks_owner_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "endpoint_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_voice_callbacks_endpoint_fk": {+ "name": "chat_voice_callbacks_endpoint_fk",+ "tableFrom": "chat_voice_callbacks",+ "tableTo": "chat_endpoints",+ "columnsFrom": [+ "company_id",+ "endpoint_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_voice_callbacks_phone_check": {+ "name": "chat_voice_callbacks_phone_check",+ "value": "\"chat_voice_callbacks\".\"phone_number\" ~ '^\\+[1-9][0-9]{6,14}$'"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_inbound_calls": {+ "name": "chat_voice_inbound_calls",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_session_id": {+ "name": "provider_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "state": {+ "name": "state",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'awaiting_approval'"+ },+ "approval_code": {+ "name": "approval_code",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "generation": {+ "name": "generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "credential_fingerprint": {+ "name": "credential_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tool_token_hash": {+ "name": "tool_token_hash",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "request_fingerprint": {+ "name": "request_fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "approved_by_user_id": {+ "name": "approved_by_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "caller_authority": {+ "name": "caller_authority",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "intake_issue_id": {+ "name": "intake_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "requested_issue_id": {+ "name": "requested_issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_voice_inbound_expiry_idx": {+ "name": "chat_voice_inbound_expiry_idx",+ "columns": [+ {+ "expression": "state",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_voice_inbound_endpoint_fk": {+ "name": "chat_voice_inbound_endpoint_fk",+ "tableFrom": "chat_voice_inbound_calls",+ "tableTo": "chat_endpoints",+ "columnsFrom": [+ "company_id",+ "endpoint_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_voice_inbound_session_fk": {+ "name": "chat_voice_inbound_session_fk",+ "tableFrom": "chat_voice_inbound_calls",+ "tableTo": "chat_voice_sessions",+ "columnsFrom": [+ "company_id",+ "session_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "chat_voice_inbound_intake_fk": {+ "name": "chat_voice_inbound_intake_fk",+ "tableFrom": "chat_voice_inbound_calls",+ "tableTo": "issues",+ "columnsFrom": [+ "company_id",+ "intake_issue_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "chat_voice_inbound_requested_issue_fk": {+ "name": "chat_voice_inbound_requested_issue_fk",+ "tableFrom": "chat_voice_inbound_calls",+ "tableTo": "issues",+ "columnsFrom": [+ "company_id",+ "requested_issue_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_voice_inbound_provider_uq": {+ "name": "chat_voice_inbound_provider_uq",+ "nullsNotDistinct": false,+ "columns": [+ "provider_session_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_voice_inbound_state_check": {+ "name": "chat_voice_inbound_state_check",+ "value": "\"chat_voice_inbound_calls\".\"state\" in ('guest_intake', 'awaiting_approval', 'approving', 'approved', 'denied', 'expired', 'ended')"+ },+ "chat_voice_inbound_token_check": {+ "name": "chat_voice_inbound_token_check",+ "value": "\"chat_voice_inbound_calls\".\"tool_token_hash\" ~ '^[a-f0-9]{64}$'"+ },+ "chat_voice_inbound_code_check": {+ "name": "chat_voice_inbound_code_check",+ "value": "\"chat_voice_inbound_calls\".\"approval_code\" ~ '^[0-9]{6}$'"+ },+ "chat_voice_inbound_generation_check": {+ "name": "chat_voice_inbound_generation_check",+ "value": "\"chat_voice_inbound_calls\".\"generation\" > 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_phone_lines": {+ "name": "chat_voice_phone_lines",+ "schema": "",+ "columns": {+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_number_id": {+ "name": "provider_number_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "phone_number": {+ "name": "phone_number",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "guest_intake": {+ "name": "guest_intake",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "low_trust_environment_id": {+ "name": "low_trust_environment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk": {+ "name": "chat_voice_phone_lines_low_trust_environment_id_environments_id_fk",+ "tableFrom": "chat_voice_phone_lines",+ "tableTo": "environments",+ "columnsFrom": [+ "low_trust_environment_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "chat_voice_phone_lines_endpoint_fk": {+ "name": "chat_voice_phone_lines_endpoint_fk",+ "tableFrom": "chat_voice_phone_lines",+ "tableTo": "chat_endpoints",+ "columnsFrom": [+ "company_id",+ "endpoint_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_voice_phone_lines_number_uq": {+ "name": "chat_voice_phone_lines_number_uq",+ "nullsNotDistinct": false,+ "columns": [+ "provider_number_id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_voice_phone_lines_number_check": {+ "name": "chat_voice_phone_lines_number_check",+ "value": "\"chat_voice_phone_lines\".\"phone_number\" ~ '^\\+[1-9][0-9]{6,14}$'"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_reports": {+ "name": "chat_voice_reports",+ "schema": "",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "transcript": {+ "name": "transcript",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true,+ "default": "'[]'::jsonb"+ },+ "cost_micro_usd": {+ "name": "cost_micro_usd",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "duration_seconds": {+ "name": "duration_seconds",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "provider_updated_at": {+ "name": "provider_updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "next_check_at": {+ "name": "next_check_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "attempts": {+ "name": "attempts",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_voice_reports_pending_idx": {+ "name": "chat_voice_reports_pending_idx",+ "columns": [+ {+ "expression": "status",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "next_check_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_voice_reports_session_fk": {+ "name": "chat_voice_reports_session_fk",+ "tableFrom": "chat_voice_reports",+ "tableTo": "chat_voice_sessions",+ "columnsFrom": [+ "company_id",+ "session_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_voice_reports_status_check": {+ "name": "chat_voice_reports_status_check",+ "value": "\"chat_voice_reports\".\"status\" in ('pending', 'available', 'unavailable')"+ },+ "chat_voice_reports_cost_check": {+ "name": "chat_voice_reports_cost_check",+ "value": "\"chat_voice_reports\".\"cost_micro_usd\" is null or \"chat_voice_reports\".\"cost_micro_usd\" ~ '^[0-9]{1,30}$'"+ },+ "chat_voice_reports_duration_check": {+ "name": "chat_voice_reports_duration_check",+ "value": "\"chat_voice_reports\".\"duration_seconds\" is null or \"chat_voice_reports\".\"duration_seconds\" >= 0"+ },+ "chat_voice_reports_attempts_check": {+ "name": "chat_voice_reports_attempts_check",+ "value": "\"chat_voice_reports\".\"attempts\" >= 0"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_replies": {+ "name": "chat_voice_replies",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "publication_id": {+ "name": "publication_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "cursor": {+ "name": "cursor",+ "type": "integer",+ "primaryKey": false,+ "notNull": true+ },+ "delivered_at": {+ "name": "delivered_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "spoken_at": {+ "name": "spoken_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_voice_replies_publication_uq": {+ "name": "chat_voice_replies_publication_uq",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "publication_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_voice_replies_cursor_uq": {+ "name": "chat_voice_replies_cursor_uq",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "cursor",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_voice_replies_company_id_companies_id_fk": {+ "name": "chat_voice_replies_company_id_companies_id_fk",+ "tableFrom": "chat_voice_replies",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "chat_voice_replies_session_fk": {+ "name": "chat_voice_replies_session_fk",+ "tableFrom": "chat_voice_replies",+ "tableTo": "chat_voice_sessions",+ "columnsFrom": [+ "company_id",+ "session_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "chat_voice_replies_publication_fk": {+ "name": "chat_voice_replies_publication_fk",+ "tableFrom": "chat_voice_replies",+ "tableTo": "chat_publications",+ "columnsFrom": [+ "company_id",+ "publication_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "chat_voice_replies_cursor_check": {+ "name": "chat_voice_replies_cursor_check",+ "value": "\"chat_voice_replies\".\"cursor\" > 0"+ },+ "chat_voice_replies_spoken_check": {+ "name": "chat_voice_replies_spoken_check",+ "value": "\"chat_voice_replies\".\"spoken_at\" is null or \"chat_voice_replies\".\"delivered_at\" is not null"+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_sessions": {+ "name": "chat_voice_sessions",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },"issue_id": {"name": "issue_id","type": "uuid","primaryKey": false,"notNull": true},- "comment_id": {- "name": "comment_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "attachment_id": {- "name": "attachment_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "principal_id": {- "name": "principal_id",+ "assigned_agent_id": {+ "name": "assigned_agent_id","type": "uuid","primaryKey": false,"notNull": true},- "authorized_user_id": {- "name": "authorized_user_id",+ "caller_id": {+ "name": "caller_id","type": "text","primaryKey": false,- "notNull": false- },- "runtime_generation": {- "name": "runtime_generation",- "type": "integer",- "primaryKey": false,"notNull": true},- "credential_fingerprint": {- "name": "credential_fingerprint",+ "caller_authority": {+ "name": "caller_authority","type": "text","primaryKey": false,"notNull": true},- "conversation_generation": {- "name": "conversation_generation",- "type": "integer",- "primaryKey": false,- "notNull": true- },- "source_digest": {- "name": "source_digest",+ "approved_by_user_id": {+ "name": "approved_by_user_id","type": "text","primaryKey": false,- "notNull": true+ "notNull": false},- "authority_digest": {- "name": "authority_digest",+ "mode": {+ "name": "mode","type": "text","primaryKey": false,"notNull": true},- "tenant_id": {- "name": "tenant_id",- "type": "uuid",- "primaryKey": false,- "notNull": true- },- "bot_app_id": {- "name": "bot_app_id",- "type": "uuid",+ "state": {+ "name": "state",+ "type": "text","primaryKey": false,- "notNull": true+ "notNull": true,+ "default": "'reserved'"},- "aad_object_id": {- "name": "aad_object_id",- "type": "uuid",+ "generation": {+ "name": "generation",+ "type": "integer","primaryKey": false,"notNull": true},- "provider_conversation_id": {- "name": "provider_conversation_id",+ "credential_fingerprint": {+ "name": "credential_fingerprint","type": "text","primaryKey": false,"notNull": true},- "provider_user_id": {- "name": "provider_user_id",+ "provider_session_id": {+ "name": "provider_session_id","type": "text","primaryKey": false,- "notNull": true+ "notNull": false},- "sha256": {- "name": "sha256",+ "tool_token_hash": {+ "name": "tool_token_hash","type": "text","primaryKey": false,"notNull": true},- "byte_size": {- "name": "byte_size",- "type": "integer",- "primaryKey": false,- "notNull": true- },- "filename": {- "name": "filename",+ "idempotency_key": {+ "name": "idempotency_key","type": "text","primaryKey": false,"notNull": true},- "token_sha256": {- "name": "token_sha256",+ "request_fingerprint": {+ "name": "request_fingerprint","type": "text","primaryKey": false,"notNull": true},- "phase": {- "name": "phase",- "type": "text",- "primaryKey": false,- "notNull": true,- "default": "'consent_pending'"- },- "version": {- "name": "version",+ "reply_cursor": {+ "name": "reply_cursor","type": "integer","primaryKey": false,"notNull": true,- "default": 1- },- "attempt_id": {- "name": "attempt_id",- "type": "uuid",- "primaryKey": false,- "notNull": false- },- "attempt_expires_at": {- "name": "attempt_expires_at",- "type": "timestamp with time zone",- "primaryKey": false,- "notNull": false- },- "consent_message_id": {- "name": "consent_message_id",- "type": "text",- "primaryKey": false,- "notNull": false- },- "file_info_message_id": {- "name": "file_info_message_id",- "type": "text",- "primaryKey": false,- "notNull": false- },- "response_activity_id": {- "name": "response_activity_id",- "type": "text",- "primaryKey": false,- "notNull": false- },- "response_digest": {- "name": "response_digest",- "type": "text",- "primaryKey": false,- "notNull": false- },- "private_state": {- "name": "private_state",- "type": "jsonb",- "primaryKey": false,- "notNull": true+ "default": 0},- "reason": {- "name": "reason",+ "error_code": {+ "name": "error_code","type": "text","primaryKey": false,"notNull": false@@ -12199,6 +13845,12 @@"primaryKey": false,"notNull": true},+ "ended_at": {+ "name": "ended_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },"created_at": {"name": "created_at","type": "timestamp with time zone",@@ -12215,8 +13867,23 @@}},"indexes": {- "chat_teams_file_transfers_publication_uq": {- "name": "chat_teams_file_transfers_publication_uq",+ "chat_voice_sessions_provider_uq": {+ "name": "chat_voice_sessions_provider_uq",+ "columns": [+ {+ "expression": "provider_session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_voice_sessions_request_uq": {+ "name": "chat_voice_sessions_request_uq","columns": [{"expression": "company_id",@@ -12225,7 +13892,13 @@"nulls": "last"},{- "expression": "publication_id",+ "expression": "caller_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "idempotency_key","isExpression": false,"asc": true,"nulls": "last"@@ -12236,38 +13909,39 @@"method": "btree","with": {}},- "chat_teams_file_transfers_token_uq": {- "name": "chat_teams_file_transfers_token_uq",+ "chat_voice_sessions_live_caller_task_uq": {+ "name": "chat_voice_sessions_live_caller_task_uq","columns": [{- "expression": "endpoint_id",+ "expression": "company_id","isExpression": false,"asc": true,"nulls": "last"},{- "expression": "token_sha256",+ "expression": "caller_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "issue_id","isExpression": false,"asc": true,"nulls": "last"}],"isUnique": true,+ "where": "\"chat_voice_sessions\".\"state\" not in ('ended', 'failed', 'expired')","concurrently": false,"method": "btree","with": {}},- "chat_teams_file_transfers_work_idx": {- "name": "chat_teams_file_transfers_work_idx",+ "chat_voice_sessions_expiry_idx": {+ "name": "chat_voice_sessions_expiry_idx","columns": [{- "expression": "phase",- "isExpression": false,- "asc": true,- "nulls": "last"- },- {- "expression": "attempt_expires_at",+ "expression": "state","isExpression": false,"asc": true,"nulls": "last"@@ -12286,9 +13960,9 @@}},"foreignKeys": {- "chat_teams_file_transfers_company_id_companies_id_fk": {- "name": "chat_teams_file_transfers_company_id_companies_id_fk",- "tableFrom": "chat_teams_file_transfers",+ "chat_voice_sessions_company_id_companies_id_fk": {+ "name": "chat_voice_sessions_company_id_companies_id_fk",+ "tableFrom": "chat_voice_sessions","tableTo": "companies","columnsFrom": ["company_id"@@ -12299,71 +13973,254 @@"onDelete": "cascade","onUpdate": "no action"},- "chat_teams_file_transfers_issue_id_issues_id_fk": {- "name": "chat_teams_file_transfers_issue_id_issues_id_fk",- "tableFrom": "chat_teams_file_transfers",- "tableTo": "issues",+ "chat_voice_sessions_endpoint_fk": {+ "name": "chat_voice_sessions_endpoint_fk",+ "tableFrom": "chat_voice_sessions",+ "tableTo": "chat_endpoints","columnsFrom": [- "issue_id"+ "company_id",+ "endpoint_id"],"columnsTo": [+ "company_id","id"],- "onDelete": "restrict",+ "onDelete": "no action","onUpdate": "no action"},- "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk": {- "name": "chat_teams_file_transfers_company_id_endpoint_id_chat_endpoints_company_id_id_fk",- "tableFrom": "chat_teams_file_transfers",- "tableTo": "chat_endpoints",+ "chat_voice_sessions_conversation_fk": {+ "name": "chat_voice_sessions_conversation_fk",+ "tableFrom": "chat_voice_sessions",+ "tableTo": "chat_conversations","columnsFrom": ["company_id",- "endpoint_id"+ "conversation_id"],"columnsTo": ["company_id","id"],- "onDelete": "cascade",+ "onDelete": "no action","onUpdate": "no action"},- "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk": {- "name": "chat_teams_file_transfers_company_id_publication_id_chat_publications_company_id_id_fk",- "tableFrom": "chat_teams_file_transfers",- "tableTo": "chat_publications",+ "chat_voice_sessions_issue_fk": {+ "name": "chat_voice_sessions_issue_fk",+ "tableFrom": "chat_voice_sessions",+ "tableTo": "issues","columnsFrom": ["company_id",- "publication_id"+ "issue_id"],"columnsTo": ["company_id","id"],- "onDelete": "cascade",+ "onDelete": "no action","onUpdate": "no action"},- "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk": {- "name": "chat_teams_file_transfers_company_id_conversation_id_chat_conversations_company_id_id_fk",- "tableFrom": "chat_teams_file_transfers",- "tableTo": "chat_conversations",+ "chat_voice_sessions_agent_fk": {+ "name": "chat_voice_sessions_agent_fk",+ "tableFrom": "chat_voice_sessions",+ "tableTo": "agents","columnsFrom": ["company_id",- "conversation_id"+ "assigned_agent_id"],"columnsTo": ["company_id","id"],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "chat_voice_sessions_company_id_uq": {+ "name": "chat_voice_sessions_company_id_uq",+ "nullsNotDistinct": false,+ "columns": [+ "company_id",+ "id"+ ]+ }+ },+ "policies": {},+ "checkConstraints": {+ "chat_voice_sessions_state_check": {+ "name": "chat_voice_sessions_state_check",+ "value": "\"chat_voice_sessions\".\"state\" in ('reserved', 'creating', 'creation_unknown', 'connecting', 'active', 'awaiting_approval', 'ending', 'ended', 'failed', 'expired')"+ },+ "chat_voice_sessions_mode_check": {+ "name": "chat_voice_sessions_mode_check",+ "value": "\"chat_voice_sessions\".\"mode\" in ('browser', 'inbound_phone', 'outbound_phone')"+ },+ "chat_voice_sessions_authority_check": {+ "name": "chat_voice_sessions_authority_check",+ "value": "\"chat_voice_sessions\".\"caller_authority\" in ('member', 'instance_admin', 'local_board', 'guest_intake', 'pending_approval')"+ },+ "chat_voice_sessions_counters_check": {+ "name": "chat_voice_sessions_counters_check",+ "value": "\"chat_voice_sessions\".\"generation\" >= 1 and \"chat_voice_sessions\".\"reply_cursor\" >= 0"+ },+ "chat_voice_sessions_token_check": {+ "name": "chat_voice_sessions_token_check",+ "value": "\"chat_voice_sessions\".\"tool_token_hash\" ~ '^[a-f0-9]{64}$'"+ },+ "chat_voice_sessions_expiry_check": {+ "name": "chat_voice_sessions_expiry_check",+ "value": "\"chat_voice_sessions\".\"expires_at\" > \"chat_voice_sessions\".\"created_at\""+ }+ },+ "isRLSEnabled": false+ },+ "public.chat_voice_tool_calls": {+ "name": "chat_voice_tool_calls",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "session_id": {+ "name": "session_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "provider_tool_call_id": {+ "name": "provider_tool_call_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "webhook_id": {+ "name": "webhook_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "fingerprint": {+ "name": "fingerprint",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "tool": {+ "name": "tool",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "delivery_id": {+ "name": "delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "response": {+ "name": "response",+ "type": "jsonb",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "chat_voice_tool_calls_tool_uq": {+ "name": "chat_voice_tool_calls_tool_uq",+ "columns": [+ {+ "expression": "session_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "provider_tool_call_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "chat_voice_tool_calls_webhook_uq": {+ "name": "chat_voice_tool_calls_webhook_uq",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "webhook_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "chat_voice_tool_calls_company_id_companies_id_fk": {+ "name": "chat_voice_tool_calls_company_id_companies_id_fk",+ "tableFrom": "chat_voice_tool_calls",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],"onDelete": "cascade","onUpdate": "no action"},- "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk": {- "name": "chat_teams_file_transfers_company_id_principal_id_chat_external_principals_company_id_id_fk",- "tableFrom": "chat_teams_file_transfers",- "tableTo": "chat_external_principals",+ "chat_voice_tool_calls_session_fk": {+ "name": "chat_voice_tool_calls_session_fk",+ "tableFrom": "chat_voice_tool_calls",+ "tableTo": "chat_voice_sessions","columnsFrom": ["company_id",- "principal_id"+ "session_id"+ ],+ "columnsTo": [+ "company_id",+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ },+ "chat_voice_tool_calls_delivery_fk": {+ "name": "chat_voice_tool_calls_delivery_fk",+ "tableFrom": "chat_voice_tool_calls",+ "tableTo": "chat_deliveries",+ "columnsFrom": [+ "company_id",+ "delivery_id"],"columnsTo": ["company_id",@@ -12377,21 +14234,9 @@"uniqueConstraints": {},"policies": {},"checkConstraints": {- "chat_teams_file_transfers_phase_check": {- "name": "chat_teams_file_transfers_phase_check",- "value": "\"chat_teams_file_transfers\".\"phase\" in ('consent_pending','consent_sending','consent_unknown','awaiting_consent','upload_pending','uploading','upload_unknown','file_info_pending','file_info_sending','file_info_unknown','delivered','declined','expired','cancelled','conflict')"- },- "chat_teams_file_transfers_bounds_check": {- "name": "chat_teams_file_transfers_bounds_check",- "value": "\"chat_teams_file_transfers\".\"version\" > 0 and \"chat_teams_file_transfers\".\"runtime_generation\" >= 0 and \"chat_teams_file_transfers\".\"conversation_generation\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" > 0 and \"chat_teams_file_transfers\".\"byte_size\" < 62914560"- },- "chat_teams_file_transfers_hash_check": {- "name": "chat_teams_file_transfers_hash_check",- "value": "\"chat_teams_file_transfers\".\"source_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"authority_digest\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"sha256\" ~ '^[a-f0-9]{64}$' and \"chat_teams_file_transfers\".\"token_sha256\" ~ '^[a-f0-9]{64}$'"- },- "chat_teams_file_transfers_attempt_check": {- "name": "chat_teams_file_transfers_attempt_check",- "value": "(\"chat_teams_file_transfers\".\"attempt_id\" is null) = (\"chat_teams_file_transfers\".\"attempt_expires_at\" is null)"+ "chat_voice_tool_calls_tool_check": {+ "name": "chat_voice_tool_calls_tool_check",+ "value": "\"chat_voice_tool_calls\".\"tool\" in ('submit_request', 'get_updates', 'answer_question')"}},"isRLSEnabled": false@@ -17560,6 +19405,12 @@"primaryKey": false,"notNull": false},+ "subscription_id": {+ "name": "subscription_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },"billing_code": {"name": "billing_code","type": "text",@@ -17795,6 +19646,33 @@"method": "btree","with": {}},+ "cost_events_company_subscription_occurred_idx": {+ "name": "cost_events_company_subscription_occurred_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "subscription_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "occurred_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },"cost_events_company_agent_occurred_idx": {"name": "cost_events_company_agent_occurred_idx","columns": [@@ -17976,6 +19854,19 @@],"onDelete": "no action","onUpdate": "no action"+ },+ "cost_events_subscription_id_ai_subscriptions_id_fk": {+ "name": "cost_events_subscription_id_ai_subscriptions_id_fk",+ "tableFrom": "cost_events",+ "tableTo": "ai_subscriptions",+ "columnsFrom": [+ "subscription_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"}},"compositePrimaryKeys": {},@@ -17984,7 +19875,7 @@"checkConstraints": {"cost_events_usage_kind_check": {"name": "cost_events_usage_kind_check",- "value": "\"cost_events\".\"usage_kind\" = 'decision' or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)"+ "value": "\"cost_events\".\"usage_kind\" in ('decision', 'fast_response') or (\"cost_events\".\"usage_kind\" = 'agent' and \"cost_events\".\"agent_id\" is not null)"},"cost_events_nonnegative_amounts": {"name": "cost_events_nonnegative_amounts",@@ -25649,6 +27540,378 @@"checkConstraints": {},"isRLSEnabled": false},+ "public.company_fast_responses": {+ "name": "company_fast_responses",+ "schema": "",+ "columns": {+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "allow_sponsored": {+ "name": "allow_sponsored",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "company_fast_responses_company_id_companies_id_fk": {+ "name": "company_fast_responses_company_id_companies_id_fk",+ "tableFrom": "company_fast_responses",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "company_fast_responses_configured": {+ "name": "company_fast_responses_configured",+ "value": "(\"company_fast_responses\".\"connection_id\" is null) = (\"company_fast_responses\".\"grant_id\" is null) and (not \"company_fast_responses\".\"enabled\" or (\"company_fast_responses\".\"connection_id\" is not null and \"company_fast_responses\".\"model\" is not null))"+ }+ },+ "isRLSEnabled": false+ },+ "public.fast_response_requests": {+ "name": "fast_response_requests",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "uuid",+ "primaryKey": true,+ "notNull": true,+ "default": "gen_random_uuid()"+ },+ "company_id": {+ "name": "company_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": true+ },+ "source_key": {+ "name": "source_key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "source_comment_id": {+ "name": "source_comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "issue_id": {+ "name": "issue_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "project_id": {+ "name": "project_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "responsible_user_id": {+ "name": "responsible_user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "sponsored": {+ "name": "sponsored",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true,+ "default": false+ },+ "endpoint_id": {+ "name": "endpoint_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "conversation_id": {+ "name": "conversation_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "delivery_id": {+ "name": "delivery_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "session_generation": {+ "name": "session_generation",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "publication_status": {+ "name": "publication_status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "connection_id": {+ "name": "connection_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "grant_id": {+ "name": "grant_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "provider": {+ "name": "provider",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "model": {+ "name": "model",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "provider_request_id": {+ "name": "provider_request_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "cost_event_id": {+ "name": "cost_event_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "error_code": {+ "name": "error_code",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "comment_id": {+ "name": "comment_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },+ "accepted_at": {+ "name": "accepted_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true+ },+ "started_at": {+ "name": "started_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "finished_at": {+ "name": "finished_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": false+ },+ "duration_ms": {+ "name": "duration_ms",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "input_tokens": {+ "name": "input_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "output_tokens": {+ "name": "output_tokens",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "fast_response_requests_source_idx": {+ "name": "fast_response_requests_source_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "source_key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": true,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "fast_response_requests_history_idx": {+ "name": "fast_response_requests_history_idx",+ "columns": [+ {+ "expression": "company_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ },+ {+ "expression": "accepted_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "fast_response_requests_work_idx": {+ "name": "fast_response_requests_work_idx",+ "columns": [+ {+ "expression": "expires_at",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "where": "\"fast_response_requests\".\"status\" in ('pending', 'running')",+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "fast_response_requests_company_id_companies_id_fk": {+ "name": "fast_response_requests_company_id_companies_id_fk",+ "tableFrom": "fast_response_requests",+ "tableTo": "companies",+ "columnsFrom": [+ "company_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "fast_response_requests_cost_event_id_cost_events_id_fk": {+ "name": "fast_response_requests_cost_event_id_cost_events_id_fk",+ "tableFrom": "fast_response_requests",+ "tableTo": "cost_events",+ "columnsFrom": [+ "cost_event_id"+ ],+ "columnsTo": [+ "id"+ ],+ "onDelete": "no action",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {+ "fast_response_requests_status_check": {+ "name": "fast_response_requests_status_check",+ "value": "\"fast_response_requests\".\"status\" in ('pending', 'running', 'succeeded', 'failed', 'unknown', 'skipped')"+ }+ },+ "isRLSEnabled": false+ },"public.feedback_exports": {"name": "feedback_exports","schema": "",@@ -30550,6 +32813,19 @@"primaryKey": false,"notNull": false},+ "origin": {+ "name": "origin",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'comment'"+ },+ "fast_response_request_id": {+ "name": "fast_response_request_id",+ "type": "uuid",+ "primaryKey": false,+ "notNull": false+ },"body": {"name": "body","type": "text",@@ -49371,7 +51647,7 @@},"tool_connections_transport_check": {"name": "tool_connections_transport_check",- "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'runtime_auth')"+ "value": "\"tool_connections\".\"transport\" in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'voice', 'runtime_auth')"},"tool_connections_purpose_check": {"name": "tool_connections_purpose_check",@@ -49379,7 +51655,7 @@},"tool_connections_channel_transport_check": {"name": "tool_connections_channel_transport_check",- "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" = 'chat_sdk' or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )"+ "value": "(\n (\"tool_connections\".\"connection_purpose\" = 'tool' and \"tool_connections\".\"transport\" not in ('chat_sdk', 'voice', 'runtime_auth'))\n or\n (\"tool_connections\".\"connection_purpose\" = 'channel' and (\"tool_connections\".\"transport\" in ('chat_sdk', 'voice') or (\"tool_connections\".\"transport\" = 'rest_api' and \"tool_connections\".\"config\"->>'provider' = 'agentmail')))\n or\n (\"tool_connections\".\"connection_purpose\" = 'ai' and \"tool_connections\".\"transport\" = 'runtime_auth')\n )"},"tool_connections_auth_kind_check": {"name": "tool_connections_auth_kind_check",diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.jsonindex fa45fd59eb..412ba94d17 100644--- a/packages/db/src/migrations/meta/_journal.json+++ b/packages/db/src/migrations/meta/_journal.json@@ -2311,6 +2311,13 @@"when": 1791642049733,"tag": "0331_panoramic_spyke","breakpoints": true+ },+ {+ "idx": 332,+ "version": "7",+ "when": 1791693159075,+ "tag": "0332_little_night_nurse",+ "breakpoints": true}]}\ No newline at end of filediff --git a/packages/db/src/question-response-history-migration.test.ts b/packages/db/src/question-response-history-migration.test.tsnew file mode 100644index 0000000000..f09fbe03ac--- /dev/null+++ b/packages/db/src/question-response-history-migration.test.ts@@ -0,0 +1,53 @@+import { createHash, randomUUID } from "node:crypto";+import { readFile } from "node:fs/promises";+import postgres from "postgres";+import { describe, expect, it } from "vitest";+import { applyPendingMigrations } from "./client.js";+import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js";++const support = await getEmbeddedPostgresTestSupport();+const indexName = "agent_wakeup_requests_question_response_history_idx";+const migrationFile = "0332_little_night_nurse.sql";++(support.supported ? describe : describe.skip)("question-response history migration", () => {+ it("repairs an interrupted concurrent index build and serializes replay without deleting wakes", async () => {+ const database = await startEmbeddedPostgresTestDatabase("question-history-migration-");+ const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} });+ try {+ const companyId = randomUUID();+ const agentId = randomUUID();+ await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Migration fixture', 'QHM')`;+ await sql`INSERT INTO agents (id, company_id, name, role, adapter_type)+ VALUES (${agentId}, ${companyId}, 'Fixture', 'engineer', 'process')`;+ await sql`INSERT INTO agent_wakeup_requests (company_id, agent_id, source, idempotency_key, status)+ SELECT ${companyId}::uuid, ${agentId}::uuid, 'automation', 'question-response:' || n::text, 'failed'+ FROM generate_series(1, 3) n`;+ const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8");+ const hash = createHash("sha256").update(content).digest("hex");+ await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;+ await sql.unsafe(`DROP INDEX ${indexName}`);+ // A failed concurrent UNIQUE build leaves the same invalid-index state+ // as an interrupted nonunique build, without relying on timing a cancel.+ await expect(sql.unsafe(`CREATE UNIQUE INDEX CONCURRENTLY ${indexName} ON agent_wakeup_requests (company_id)`))+ .rejects.toThrow();+ const [invalid] = await sql`SELECT i.indisvalid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid+ WHERE c.relname = ${indexName}`;+ expect(invalid?.indisvalid).toBe(false);+ await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]);+ const [rebuilt] = await sql`SELECT i.indisvalid, i.indisunique, pg_get_indexdef(i.indexrelid) AS definition+ FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid WHERE c.relname = ${indexName}`;+ expect(rebuilt?.indisvalid).toBe(true);+ expect(rebuilt?.indisunique).toBe(false);+ expect(rebuilt?.definition).toContain("company_id, idempotency_key");+ expect(rebuilt?.definition).toContain("question-response:%");+ const [wakes] = await sql`SELECT count(*)::int AS n FROM agent_wakeup_requests WHERE company_id = ${companyId}`;+ expect(wakes?.n).toBe(3);+ const [history] = await sql`SELECT count(*)::int AS n FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`;+ expect(history?.n).toBe(1);+ await applyPendingMigrations(database.connectionString);+ } finally {+ await sql.end();+ await database.cleanup();+ }+ }, 60_000);+});diff --git a/packages/db/src/schema/agent_wakeup_requests.ts b/packages/db/src/schema/agent_wakeup_requests.tsindex 0537bf6ee2..ee84a39520 100644--- a/packages/db/src/schema/agent_wakeup_requests.ts+++ b/packages/db/src/schema/agent_wakeup_requests.ts@@ -75,6 +75,12 @@ export const agentWakeupRequests = pgTable().on(table.companyId, table.idempotencyKey).where(sql`(${table.idempotencyKey} LIKE 'question-response:%' OR ${table.idempotencyKey} LIKE 'interaction:%') AND ${table.status} NOT IN ('skipped', 'failed', 'cancelled')`),+ // Sleep checks also need failed/cancelled/skipped receipts, which the+ // delivery idempotency fence deliberately excludes.+ questionResponseHistoryIdx: index("agent_wakeup_requests_question_response_history_idx")+ .on(table.companyId, table.idempotencyKey)+ .concurrently()+ .where(sql`${table.idempotencyKey} LIKE 'question-response:%'`),connectionIntentDeliveryIdempotencyUq: uniqueIndex("agent_wakeup_requests_connection_intent_delivery_idempotency_uq").on(table.companyId, table.idempotencyKey).where(sql`${table.idempotencyKey} LIKE 'connection-intent:%' AND ${table.status} NOT IN ('skipped', 'failed', 'cancelled')`),diff --git a/server/src/__tests__/idle-sleep-safety.test.ts b/server/src/__tests__/idle-sleep-safety.test.tsindex 718d33ce53..f8e1524107 100644--- a/server/src/__tests__/idle-sleep-safety.test.ts+++ b/server/src/__tests__/idle-sleep-safety.test.ts@@ -5,7 +5,8 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitestimport {agentInstructionWorkingCopies, agents, agentApiKeys, agentWakeupRequests, companies, companySecretProposals, createDb,adapterAuthSessions, environments, environmentLeases, executionWorkspaces,- heartbeatRuns, issues, issueWatchdogs, projects, routines, type Db,+ heartbeatRuns, issues, issueWatchdogs, issueThreadInteractions, issueQuestionResponseDeliveries,+ projects, routines, type Db,} from "@paperclipai/db";import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";import { readIdleSleepSafety, type IdleSleepDrainStatus } from "../services/idle-sleep-safety.js";@@ -184,6 +185,152 @@ if (!support.supported) console.warn(`Skipping idle sleep Postgres tests: ${suppreturn { companyId, agentId, runId };}+ async function seedQuestionDelivery(change: Partial<typeof issueQuestionResponseDeliveries.$inferInsert> = {}) {+ const seeded = await seed();+ await db.update(heartbeatRuns).set({ finishedAt: new Date(now) }).where(eq(heartbeatRuns.id, seeded.runId));+ const issueId = randomUUID();+ const interactionId = randomUUID();+ await db.insert(issues).values({ id: issueId, companyId: seeded.companyId, title: "Finished question", status: "done" });+ await db.insert(issueThreadInteractions).values({+ id: interactionId, companyId: seeded.companyId, issueId,+ kind: "ask_user_questions", status: "answered", payload: {},+ });+ await db.insert(issueQuestionResponseDeliveries).values({+ companyId: seeded.companyId, issueId, interactionId, sourceRunId: seeded.runId,+ targetRunId: seeded.runId, correlationId: randomUUID(), payloadSha256: "fixture",+ status: "fallback_queued", deliveryMode: "wake_fallback", acknowledgedAt: new Date(now), ...change,+ });+ return { ...seeded, issueId, interactionId };+ }++ async function seedQuestionWake(+ delivery: Awaited<ReturnType<typeof seedQuestionDelivery>>,+ change: Partial<typeof agentWakeupRequests.$inferInsert> = {},+ ) {+ await db.insert(agentWakeupRequests).values({+ companyId: delivery.companyId, agentId: delivery.agentId, source: "automation",+ idempotencyKey: `question-response:${delivery.interactionId}`,+ status: "completed", finishedAt: new Date(now), ...change,+ });+ }++ it.each(["pending", "delivering"])("keeps a %s question delivery awake", async status => {+ await seedQuestionDelivery({ status, acknowledgedAt: null });+ expect(await read()).toEqual(present);+ });++ it.each(["delivered", "fallback_queued"])("permits acknowledged %s history after its target run finishes", async status => {+ await seedQuestionDelivery({ status });+ expect(await read()).toEqual(none);+ });++ it.each(["delivered", "fallback_queued"])("keeps an unacknowledged %s question delivery awake", async status => {+ await seedQuestionDelivery({ status, acknowledgedAt: null });+ expect(await read()).toEqual(present);+ });++ it.each([+ ["queued", { status: "queued", finishedAt: null }],+ ["running", { status: "running", finishedAt: null }],+ ["unfinished", { finishedAt: null }],+ ["retry", { scheduledRetryAt: new Date(now + 1000) }],+ ["accounting", { costAccountingPending: true }],+ ] as const)("keeps an acknowledged question delivery awake with %s target evidence", async (_name, change) => {+ const { runId } = await seedQuestionDelivery();+ await db.update(heartbeatRuns).set(change).where(eq(heartbeatRuns.id, runId));+ expect(await read()).toEqual(present);+ });++ it("does not accept a foreign company's finished question target", async () => {+ const foreign = await seedQuestionDelivery({ status: "failed", targetRunId: null });+ await seedQuestionDelivery({ targetRunId: foreign.runId });+ expect(await read()).toEqual(present);+ });++ it("keeps delivered history with a missing target awake", async () => {+ await seedQuestionDelivery({ status: "delivered", targetRunId: null });+ expect(await read()).toEqual(present);+ });++ it("keeps fallback history without a durable wake receipt awake", async () => {+ await seedQuestionDelivery({ targetRunId: null });+ expect(await read()).toEqual(present);+ });++ it.each(["completed", "failed", "cancelled", "skipped", "timed_out"])(+ "permits fallback history after its exact durable wake is %s and finished", async status => {+ const delivery = await seedQuestionDelivery({ targetRunId: null });+ await seedQuestionWake(delivery, { status });+ expect(await read()).toEqual(none);+ },+ );++ it.each(["queued", "deferred_issue_execution", "coalesced"])("keeps an unresolved %s question wake awake", async status => {+ const delivery = await seedQuestionDelivery({ targetRunId: null });+ await seedQuestionWake(delivery, { status, finishedAt: null });+ expect(await read()).toEqual(present);+ });++ it("keeps a terminal question wake without completion evidence awake", async () => {+ const delivery = await seedQuestionDelivery({ targetRunId: null });+ await seedQuestionWake(delivery, { finishedAt: null });+ expect(await read()).toEqual(present);+ });++ it("permits a deferred question fallback after its coalesced continuation finishes", async () => {+ const delivery = await seedQuestionDelivery({ targetRunId: null });+ await seedQuestionWake(delivery, { status: "deferred_issue_execution", finishedAt: null });+ expect(await read()).toEqual(present);+ await db.update(agentWakeupRequests).set({+ status: "coalesced", runId: delivery.runId, finishedAt: new Date(now),+ }).where(eq(agentWakeupRequests.companyId, delivery.companyId));+ expect(await read()).toEqual(none);+ });++ it.each(["missing_run", "wrong_company", "wrong_agent", "unfinished", "retry", "accounting"])(+ "keeps a coalesced question fallback awake with %s linked-run evidence", async kind => {+ const delivery = await seedQuestionDelivery({ targetRunId: null });+ let runId = delivery.runId;+ if (kind === "missing_run") runId = randomUUID();+ if (kind === "wrong_company") runId = (await seedQuestionDelivery({ status: "failed", targetRunId: null })).runId;+ if (kind === "wrong_agent") {+ const otherAgent = randomUUID();+ await db.insert(agents).values({ id: otherAgent, companyId: delivery.companyId, name: "Other", role: "engineer", status: "idle", adapterType: "process" });+ await db.update(heartbeatRuns).set({ agentId: otherAgent }).where(eq(heartbeatRuns.id, runId));+ }+ if (kind === "unfinished") await db.update(heartbeatRuns).set({ finishedAt: null }).where(eq(heartbeatRuns.id, runId));+ if (kind === "retry") await db.update(heartbeatRuns).set({ scheduledRetryAt: new Date(now + 1000) }).where(eq(heartbeatRuns.id, runId));+ if (kind === "accounting") await db.update(heartbeatRuns).set({ costAccountingPending: true }).where(eq(heartbeatRuns.id, runId));+ await seedQuestionWake(delivery, { status: "coalesced", runId });+ expect(await read()).toEqual(present);+ },+ );++ it("does not accept another interaction's or company's question wake receipt", async () => {+ const delivery = await seedQuestionDelivery({ targetRunId: null });+ await seedQuestionWake(delivery, { idempotencyKey: `question-response:${randomUUID()}` });+ const foreign = await seedQuestionDelivery({ status: "failed", targetRunId: null });+ await seedQuestionWake(delivery, { companyId: foreign.companyId, agentId: foreign.agentId });+ expect(await read()).toEqual(present);+ });++ it("permits failed question-delivery history without a pending target", async () => {+ await seedQuestionDelivery({ status: "failed", targetRunId: null, acknowledgedAt: null });+ expect(await read()).toEqual(none);+ });++ it("still blocks other work after a question handoff finishes", async () => {+ const { issueId } = await seedQuestionDelivery();+ await db.update(issues).set({ status: "todo" }).where(eq(issues.id, issueId));+ expect(await read()).toEqual(present);+ });++ it("requires a current quiet owner even with completed question history", async () => {+ await seedQuestionDelivery();+ expect(await readIdleSleepSafety(db, owned, () => now, "stale-owner", emptyLocal)).toEqual(unknown);+ expect(await readIdleSleepSafety(db, owned, () => now + 60_001, ownerId, emptyLocal)).toEqual(unknown);+ });+it("keeps saved agent files awake until deferred cleanup completes", async () => {const { companyId, agentId, runId } = await seed();await db.insert(agentInstructionWorkingCopies).values({diff --git a/server/src/services/idle-sleep-safety.ts b/server/src/services/idle-sleep-safety.tsindex 4f2059f3bb..3e637a8c0a 100644--- a/server/src/services/idle-sleep-safety.ts+++ b/server/src/services/idle-sleep-safety.ts@@ -93,13 +93,38 @@ const WORK_CHECKS = [THEN s.provider_lease_id::uuid END)AND (l.status IN ('released', 'expired') AND l.cleanup_status = 'success'AND l.released_at IS NOT NULL) IS NOT TRUE))`,+ // Answer delivery history is not work once its acknowledged handoff has+ // finished. Keep pending deliveries, unfinished target runs, and missing or+ // unfinished fallback wake receipts awake. Other work checks still apply.+ `SELECT 1 FROM issue_question_response_deliveries d WHERE+ d.status NOT IN ('delivered', 'fallback_queued', 'failed')+ OR (d.status IN ('delivered', 'fallback_queued') AND d.acknowledged_at IS NULL)+ OR (d.status = 'delivered' AND d.target_run_id IS NULL)+ OR (d.target_run_id IS NOT NULL AND NOT EXISTS (+ SELECT 1 FROM heartbeat_runs r WHERE r.id = d.target_run_id+ AND r.company_id = d.company_id+ AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')+ AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL+ AND r.cost_accounting_pending = false))+ OR (d.status = 'fallback_queued' AND d.target_run_id IS NULL AND NOT EXISTS (+ SELECT 1 FROM agent_wakeup_requests w WHERE w.company_id = d.company_id+ AND w.idempotency_key = 'question-response:' || d.interaction_id::text+ AND w.idempotency_key LIKE 'question-response:%'+ AND w.finished_at IS NOT NULL+ AND (w.status IN ('completed', 'failed', 'cancelled', 'skipped', 'timed_out')+ OR (w.status = 'coalesced' AND EXISTS (+ SELECT 1 FROM heartbeat_runs r WHERE r.id = w.run_id+ AND r.company_id = w.company_id AND r.agent_id = w.agent_id+ AND r.status IN ('succeeded', 'failed', 'cancelled', 'timed_out', 'interrupted')+ AND r.finished_at IS NOT NULL AND r.scheduled_retry_at IS NULL+ AND r.cost_accounting_pending = false)))))`,// These less common work sources fail closed on any retained state. Their// terminal-state exceptions can be added with tests for the owning service....["chat_endpoints", "chat_deliveries", "chat_publications", "chat_actions","chat_completion_deliveries", "connection_event_deliveries","connection_intent_deliveries", "tool_action_requests", "tool_action_deliveries",- "issue_question_response_deliveries", "workspace_runtime_services",+ "workspace_runtime_services","execution_workspace_runtime_leases", "pipeline_automation_executions","native_run_finalizations", "company_transfer_runs", "decisions", "decision_effect_executions","decision_archive_notification_outbox", "browser_use_sessions", "browser_use_runs",