diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 2045df0fa86..9a368fabe0f 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -951,6 +951,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0511_simple_the_hunter.sql", "0512_stormy_the_hood.sql", "0513_closed_wither.sql", + "0516_exotic_spectrum.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0516_exotic_spectrum.sql b/packages/db/src/migrations/0516_exotic_spectrum.sql new file mode 100644 index 00000000000..5ce07f6b8bd --- /dev/null +++ b/packages/db/src/migrations/0516_exotic_spectrum.sql @@ -0,0 +1,2 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_github_run_publications_idx" ON "chat_actions" USING btree ("company_id","endpoint_id",("payload"->'session'->>'issueId'),("payload"->'session'->>'runId')) WHERE "chat_actions"."kind" = 'github_review_publication';--> statement-breakpoint +CREATE INDEX CONCURRENTLY IF NOT EXISTS "chat_actions_pending_work_idx" ON "chat_actions" USING btree ("kind","created_at","id") WHERE "chat_actions"."status" IN ('received', 'processing', 'queued', 'provider_confirmed', 'admitting', 'resolving', 'validating', 'dispatching') OR ("chat_actions"."kind" = 'failed_run_retry' AND "chat_actions"."status" IN ('issued', 'processing')) OR ("chat_actions"."status" = 'failed' AND "chat_actions"."result"->>'retryable' = 'true'); diff --git a/packages/db/src/migrations/meta/0511_snapshot.json b/packages/db/src/migrations/meta/0516_snapshot.json similarity index 97% rename from packages/db/src/migrations/meta/0511_snapshot.json rename to packages/db/src/migrations/meta/0516_snapshot.json index 967a79d74b3..308b61872c3 100644 --- a/packages/db/src/migrations/meta/0511_snapshot.json +++ b/packages/db/src/migrations/meta/0516_snapshot.json @@ -1,6 +1,6 @@ { - "id": "081cc14c-5504-4a93-8b4c-e5945f3936c3", - "prevId": "bd7706ab-f548-43f0-9dbb-4f1d52d9c135", + "id": "b87b425a-7bcf-46df-b784-bae302302953", + "prevId": "3a2aed10-7ad5-43cc-bb02-2dbc2e8066aa", "version": "7", "dialect": "postgresql", "tables": { @@ -1842,6 +1842,12 @@ "primaryKey": false, "notNull": false }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, "last_used_at": { "name": "last_used_at", "type": "timestamp with time zone", @@ -6878,6 +6884,24 @@ "primaryKey": false, "notNull": true }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "locked_profile": { + "name": "locked_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scopes": { + "name": "scopes", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, "name": { "name": "name", "type": "text", @@ -6946,6 +6970,21 @@ "concurrently": false, "method": "btree", "with": {} + }, + "board_api_keys_company_idx": { + "name": "board_api_keys_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -6961,6 +7000,19 @@ ], "onDelete": "cascade", "onUpdate": "no action" + }, + "board_api_keys_company_id_companies_id_fk": { + "name": "board_api_keys_company_id_companies_id_fk", + "tableFrom": "board_api_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -10363,6 +10415,345 @@ }, "isRLSEnabled": false }, + "public.channel_access_members": { + "name": "channel_access_members", + "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 + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "subject_type": { + "name": "subject_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_id": { + "name": "subject_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "channel_access_members_channel_subject_uq": { + "name": "channel_access_members_channel_subject_uq", + "columns": [ + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "channel_access_members_subject_lookup_idx": { + "name": "channel_access_members_subject_lookup_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "channel_access_members_company_id_companies_id_fk": { + "name": "channel_access_members_company_id_companies_id_fk", + "tableFrom": "channel_access_members", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "channel_access_members_channel_id_channels_id_fk": { + "name": "channel_access_members_channel_id_channels_id_fk", + "tableFrom": "channel_access_members", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "channel_access_members_subject_type_check": { + "name": "channel_access_members_subject_type_check", + "value": "\"channel_access_members\".\"subject_type\" in ('user', 'agent')" + } + }, + "isRLSEnabled": false + }, + "public.channels": { + "name": "channels", + "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 + }, + "path": { + "name": "path", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "visibility": { + "name": "visibility", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "default_project_id": { + "name": "default_project_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "queue_config": { + "name": "queue_config", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_activity_at": { + "name": "last_activity_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "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": { + "channels_company_path_uq": { + "name": "channels_company_path_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "path", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "channels_company_activity_idx": { + "name": "channels_company_activity_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "last_activity_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "channels_company_id_companies_id_fk": { + "name": "channels_company_id_companies_id_fk", + "tableFrom": "channels", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "channels_default_project_id_projects_id_fk": { + "name": "channels_default_project_id_projects_id_fk", + "tableFrom": "channels", + "tableTo": "projects", + "columnsFrom": [ + "default_project_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "channels_created_by_agent_id_agents_id_fk": { + "name": "channels_created_by_agent_id_agents_id_fk", + "tableFrom": "channels", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "channels_visibility_check": { + "name": "channels_visibility_check", + "value": "\"channels\".\"visibility\" in ('open', 'private')" + }, + "channels_path_check": { + "name": "channels_path_check", + "value": "\"channels\".\"path\" ~ '^[a-z0-9][a-z0-9_-]*(/[a-z0-9][a-z0-9_-]*)*$'" + } + }, + "isRLSEnabled": false + }, "public.chat_actions": { "name": "chat_actions", "schema": "", @@ -10629,6 +11020,68 @@ "method": "btree", "with": {} }, + "chat_actions_github_run_publications_idx": { + "name": "chat_actions_github_run_publications_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "endpoint_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "(\"payload\"->'session'->>'issueId')", + "asc": true, + "isExpression": true, + "nulls": "last" + }, + { + "expression": "(\"payload\"->'session'->>'runId')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_actions\".\"kind\" = 'github_review_publication'", + "concurrently": true, + "method": "btree", + "with": {} + }, + "chat_actions_pending_work_idx": { + "name": "chat_actions_pending_work_idx", + "columns": [ + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"chat_actions\".\"status\" IN ('received', 'processing', 'queued', 'provider_confirmed', 'admitting', 'resolving', 'validating', 'dispatching') OR (\"chat_actions\".\"kind\" = 'failed_run_retry' AND \"chat_actions\".\"status\" IN ('issued', 'processing')) OR (\"chat_actions\".\"status\" = 'failed' AND \"chat_actions\".\"result\"->>'retryable' = 'true')", + "concurrently": true, + "method": "btree", + "with": {} + }, "chat_actions_github_terminal_work_idx": { "name": "chat_actions_github_terminal_work_idx", "columns": [ @@ -16464,6 +16917,25 @@ "notNull": true, "default": "'board'" }, + "challenge_kind": { + "name": "challenge_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, + "requested_agent_name": { + "name": "requested_agent_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_agent_role": { + "name": "requested_agent_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, "requested_company_id": { "name": "requested_company_id", "type": "uuid", @@ -16494,6 +16966,12 @@ "primaryKey": false, "notNull": false }, + "approved_agent_id": { + "name": "approved_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "approved_at": { "name": "approved_at", "type": "timestamp with time zone", @@ -16613,6 +17091,19 @@ ], "onDelete": "set null", "onUpdate": "no action" + }, + "cli_auth_challenges_approved_agent_id_agents_id_fk": { + "name": "cli_auth_challenges_approved_agent_id_agents_id_fk", + "tableFrom": "cli_auth_challenges", + "tableTo": "agents", + "columnsFrom": [ + "approved_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" } }, "compositePrimaryKeys": {}, @@ -16754,6 +17245,12 @@ "primaryKey": false, "notNull": false }, + "agent_identity_policy": { + "name": "agent_identity_policy", + "type": "text", + "primaryKey": false, + "notNull": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -16790,7 +17287,12 @@ "compositePrimaryKeys": {}, "uniqueConstraints": {}, "policies": {}, - "checkConstraints": {}, + "checkConstraints": { + "companies_agent_identity_policy_check": { + "name": "companies_agent_identity_policy_check", + "value": "\"companies\".\"agent_identity_policy\" is null or \"companies\".\"agent_identity_policy\" in ('open_local_profiles', 'delegated_profiles', 'strict_agent_keys')" + } + }, "isRLSEnabled": false }, "public.company_logos": { @@ -17326,6 +17828,141 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.company_schemas": { + "name": "company_schemas", + "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 + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "json_schema": { + "name": "json_schema", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by_agent_id": { + "name": "created_by_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "company_schemas_company_name_version_uq": { + "name": "company_schemas_company_name_version_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "company_schemas_company_id_companies_id_fk": { + "name": "company_schemas_company_id_companies_id_fk", + "tableFrom": "company_schemas", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "company_schemas_created_by_agent_id_agents_id_fk": { + "name": "company_schemas_created_by_agent_id_agents_id_fk", + "tableFrom": "company_schemas", + "tableTo": "agents", + "columnsFrom": [ + "created_by_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "company_schemas_version_check": { + "name": "company_schemas_version_check", + "value": "\"company_schemas\".\"version\" >= 1" + } + }, + "isRLSEnabled": false + }, "public.company_secret_bindings": { "name": "company_secret_bindings", "schema": "", @@ -35248,6 +35885,546 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.board_events": { + "name": "board_events", + "schema": "", + "columns": { + "seq": { + "name": "seq", + "type": "bigserial", + "primaryKey": true, + "notNull": true + }, + "company_id": { + "name": "company_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "channel_path": { + "name": "channel_path", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_name": { + "name": "actor_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_profile": { + "name": "actor_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "payload": { + "name": "payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "board_events_company_seq_idx": { + "name": "board_events_company_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "board_events_company_channel_seq_idx": { + "name": "board_events_company_channel_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_path", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "board_events_company_issue_seq_idx": { + "name": "board_events_company_issue_seq_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "seq", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "board_events_company_id_companies_id_fk": { + "name": "board_events_company_id_companies_id_fk", + "tableFrom": "board_events", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "board_events_channel_id_channels_id_fk": { + "name": "board_events_channel_id_channels_id_fk", + "tableFrom": "board_events", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "board_events_issue_id_issues_id_fk": { + "name": "board_events_issue_id_issues_id_fk", + "tableFrom": "board_events", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.issue_batch_idempotency_keys": { + "name": "issue_batch_idempotency_keys", + "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 + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_hash": { + "name": "request_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "response_payload": { + "name": "response_payload", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "issue_batch_idempotency_keys_company_key_uq": { + "name": "issue_batch_idempotency_keys_company_key_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "issue_batch_idempotency_keys_company_id_companies_id_fk": { + "name": "issue_batch_idempotency_keys_company_id_companies_id_fk", + "tableFrom": "issue_batch_idempotency_keys", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.scheduled_board_posts": { + "name": "scheduled_board_posts", + "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 + }, + "target": { + "name": "target", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "post_only": { + "name": "post_only", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "interval_ms": { + "name": "interval_ms", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "until_at": { + "name": "until_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "last_run_at": { + "name": "last_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "run_count": { + "name": "run_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'scheduled'" + }, + "author_user_id": { + "name": "author_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "author_agent_id": { + "name": "author_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "author_profile": { + "name": "author_profile", + "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", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "scheduled_board_posts_due_idx": { + "name": "scheduled_board_posts_due_idx", + "columns": [ + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"scheduled_board_posts\".\"status\" = 'scheduled'", + "concurrently": false, + "method": "btree", + "with": {} + }, + "scheduled_board_posts_company_idx": { + "name": "scheduled_board_posts_company_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "next_run_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "scheduled_board_posts_company_id_companies_id_fk": { + "name": "scheduled_board_posts_company_id_companies_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_channel_id_channels_id_fk": { + "name": "scheduled_board_posts_channel_id_channels_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_issue_id_issues_id_fk": { + "name": "scheduled_board_posts_issue_id_issues_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "scheduled_board_posts_author_agent_id_agents_id_fk": { + "name": "scheduled_board_posts_author_agent_id_agents_id_fk", + "tableFrom": "scheduled_board_posts", + "tableTo": "agents", + "columnsFrom": [ + "author_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "scheduled_board_posts_status_check": { + "name": "scheduled_board_posts_status_check", + "value": "\"scheduled_board_posts\".\"status\" in ('scheduled', 'cancelled', 'completed')" + } + }, + "isRLSEnabled": false + }, "public.heartbeat_run_events": { "name": "heartbeat_run_events", "schema": "", @@ -39003,6 +40180,13 @@ "primaryKey": false, "notNull": false }, + "issue_level": { + "name": "issue_level", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, "created_at": { "name": "created_at", "type": "timestamp with time zone", @@ -39303,6 +40487,33 @@ "primaryKey": false, "notNull": false }, + "actor_profile": { + "name": "actor_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "no_sync": { + "name": "no_sync", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, "source_trust": { "name": "source_trust", "type": "jsonb", @@ -44230,6 +45441,12 @@ "primaryKey": false, "notNull": false }, + "channel_id": { + "name": "channel_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, "project_workspace_id": { "name": "project_workspace_id", "type": "uuid", @@ -44387,12 +45604,88 @@ "primaryKey": false, "notNull": false }, + "created_by_profile": { + "name": "created_by_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, "responsible_user_id": { "name": "responsible_user_id", "type": "text", "primaryKey": false, "notNull": false }, + "kv_labels": { + "name": "kv_labels", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "schema_blocks": { + "name": "schema_blocks", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "result_schema_ref": { + "name": "result_schema_ref", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_epoch": { + "name": "claim_epoch", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "claim_token_hash": { + "name": "claim_token_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_holder_agent_id": { + "name": "claim_holder_agent_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "claim_holder_user_id": { + "name": "claim_holder_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_holder_profile": { + "name": "claim_holder_profile", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "claim_leased_at": { + "name": "claim_leased_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_lease_expires_at": { + "name": "claim_lease_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "claim_attempt_count": { + "name": "claim_attempt_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, "issue_number": { "name": "issue_number", "type": "integer", @@ -45410,6 +46703,119 @@ "concurrently": false, "method": "btree", "with": {} + }, + "issues_company_channel_created_idx": { + "name": "issues_company_channel_created_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_kv_labels_gin_idx": { + "name": "issues_kv_labels_gin_idx", + "columns": [ + { + "expression": "kv_labels", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "gin", + "with": {} + }, + "issues_ready_pool_queue_idx": { + "name": "issues_ready_pool_queue_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "channel_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "priority", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issues\".\"status\" = 'todo'\n and \"issues\".\"assignee_agent_id\" is null\n and \"issues\".\"assignee_user_id\" is null\n and \"issues\".\"hidden_at\" is null\n and \"issues\".\"conversation_agent_id\" is null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_active_claim_lease_due_idx": { + "name": "issues_active_claim_lease_due_idx", + "columns": [ + { + "expression": "claim_lease_expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"issues\".\"status\" = 'in_progress'\n and \"issues\".\"claim_lease_expires_at\" is not null\n and \"issues\".\"claim_token_hash\" is not null", + "concurrently": true, + "method": "btree", + "with": {} + }, + "issues_company_issue_number_idx": { + "name": "issues_company_issue_number_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": true, + "method": "btree", + "with": {} } }, "foreignKeys": { @@ -45452,6 +46858,19 @@ "onDelete": "no action", "onUpdate": "no action" }, + "issues_channel_id_channels_id_fk": { + "name": "issues_channel_id_channels_id_fk", + "tableFrom": "issues", + "tableTo": "channels", + "columnsFrom": [ + "channel_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, "issues_project_workspace_id_project_workspaces_id_fk": { "name": "issues_project_workspace_id_project_workspaces_id_fk", "tableFrom": "issues", @@ -45569,6 +46988,19 @@ "onDelete": "no action", "onUpdate": "no action" }, + "issues_claim_holder_agent_id_agents_id_fk": { + "name": "issues_claim_holder_agent_id_agents_id_fk", + "tableFrom": "issues", + "tableTo": "agents", + "columnsFrom": [ + "claim_holder_agent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, "issues_origin_issue_id_issues_id_fk": { "name": "issues_origin_issue_id_issues_id_fk", "tableFrom": "issues", @@ -45620,6 +47052,10 @@ "issues_conversation_identity_check": { "name": "issues_conversation_identity_check", "value": "(\n \"issues\".\"conversation_agent_id\" is null and \"issues\".\"conversation_user_id\" is null and \"issues\".\"conversation_state\" is null\n ) or (\n \"issues\".\"conversation_agent_id\" is not null and \"issues\".\"conversation_user_id\" is not null\n and \"issues\".\"assignee_agent_id\" = \"issues\".\"conversation_agent_id\" and \"issues\".\"assignee_agent_id\" is not null\n and \"issues\".\"assignee_user_id\" is null and \"issues\".\"conversation_state\" is not null\n and \"issues\".\"conversation_state\" in ('active', 'waiting')\n and \"issues\".\"status\" not in ('done', 'cancelled')\n )" + }, + "issues_conversation_channel_exclusion_check": { + "name": "issues_conversation_channel_exclusion_check", + "value": "(\"issues\".\"conversation_agent_id\" is null) or (\"issues\".\"channel_id\" is null)" } }, "isRLSEnabled": false @@ -67164,6 +68600,162 @@ }, "isRLSEnabled": false }, + "public.user_recent_tasks": { + "name": "user_recent_tasks", + "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 + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "issue_id": { + "name": "issue_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "recorded_at": { + "name": "recorded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "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": { + "user_recent_tasks_company_user_recorded_idx": { + "name": "user_recent_tasks_company_user_recorded_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recorded_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_recent_tasks_issue_idx": { + "name": "user_recent_tasks_issue_idx", + "columns": [ + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "user_recent_tasks_company_user_issue_uq": { + "name": "user_recent_tasks_company_user_issue_uq", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "issue_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "user_recent_tasks_company_id_companies_id_fk": { + "name": "user_recent_tasks_company_id_companies_id_fk", + "tableFrom": "user_recent_tasks", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "user_recent_tasks_issue_id_issues_id_fk": { + "name": "user_recent_tasks_issue_id_issues_id_fk", + "tableFrom": "user_recent_tasks", + "tableTo": "issues", + "columnsFrom": [ + "issue_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, "public.user_secret_declarations": { "name": "user_secret_declarations", "schema": "", diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 873876d754d..b505d342955 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3599,6 +3599,13 @@ "when": 1796362090964, "tag": "0515_fixed_grandmaster", "breakpoints": true + }, + { + "idx": 516, + "version": "7", + "when": 1796435141126, + "tag": "0516_exotic_spectrum", + "breakpoints": true } ] } \ No newline at end of file diff --git a/packages/db/src/schema/chat_channels.ts b/packages/db/src/schema/chat_channels.ts index 4e6015851e9..67c939d0161 100644 --- a/packages/db/src/schema/chat_channels.ts +++ b/packages/db/src/schema/chat_channels.ts @@ -715,6 +715,21 @@ export const chatActions = pgTable( .on(table.companyId, table.endpointId, sql`(${table.payload}->'session'->>'issueId')`, table.updatedAt) .where(sql`${table.kind} = 'github_review_publication' and ${table.status} = 'processed'`) .concurrently(), + index("chat_actions_github_run_publications_idx") + .on( + table.companyId, + table.endpointId, + sql`(${table.payload}->'session'->>'issueId')`, + sql`(${table.payload}->'session'->>'runId')`, + ) + .where(sql`${table.kind} = 'github_review_publication'`) + .concurrently(), + index("chat_actions_pending_work_idx") + .on(table.kind, table.createdAt, table.id) + .where( + sql`${table.status} IN ('received', 'processing', 'queued', 'provider_confirmed', 'admitting', 'resolving', 'validating', 'dispatching') OR (${table.kind} = 'failed_run_retry' AND ${table.status} IN ('issued', 'processing')) OR (${table.status} = 'failed' AND ${table.result}->>'retryable' = 'true')`, + ) + .concurrently(), index("chat_actions_github_terminal_work_idx").on(table.id).where(sql`${table.kind} = 'github_response_comment' and ${table.status} = 'processed' and ${table.deliveryId} is not null and coalesce(${table.result}->>'final', 'false') <> 'true'`), diff --git a/server/src/__tests__/chat-admission-condition.test.ts b/server/src/__tests__/chat-admission-condition.test.ts index e568539d9fc..fe38b1a0dc3 100644 --- a/server/src/__tests__/chat-admission-condition.test.ts +++ b/server/src/__tests__/chat-admission-condition.test.ts @@ -1,9 +1,14 @@ import { randomUUID } from "node:crypto"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { and, eq } from "drizzle-orm"; +import { and, asc, eq } from "drizzle-orm"; import { agentWakeupRequests, agents, chatActions, chatConversations, createDb, issues, type Db } from "@paperclipai/db"; import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { seedGitHubReviewWait } from "./helpers/github-review-wait.js"; +import { dueChatAction, nextChatActionAt } from "../services/chat-action-work.js"; +import { githubResponseCommentService } from "../services/chat-github-response-comments.js"; +import { githubChatReviewService } from "../services/chat-github-reviews.js"; +import { githubRunReplyState } from "../services/chat-run-publications.js"; +import { CHAT_ACTION_QUEUES, type ScheduledChatAction } from "../services/chat-work-notifications.js"; import { unadmittedChatWakeupCondition } from "../services/durable-chat-wakeup.js"; // Pins which saved chat input holds an issue as "not admitted". Recovery skips @@ -168,4 +173,209 @@ describe("unadmitted chat wakeup condition", () => { expect(scans.length).toBeGreaterThan(0); for (const scan of scans) expect(scan).toMatch(/Index.*Scan:chat_actions_company_issue_kind_idx/); }); + + it("uses chat_actions partial indexes for GitHub run reply state and scheduled work polling", async () => { + const s = await seed(); + const runId = randomUUID(); + const explainChatActions = async (querySql: string, params: unknown[]) => { + const [row] = await db.$client.unsafe(`EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) ${querySql}`, params as never[]); + const seqScans: string[] = []; + const indexScans: string[] = []; + const walk = (node: Record) => { + const nodeType = String(node["Node Type"] ?? ""); + const relation = node["Relation Name"]; + const indexName = node["Index Name"]; + if (relation === "chat_actions" && nodeType.includes("Seq Scan")) seqScans.push(nodeType); + if (typeof indexName === "string" && indexName.startsWith("chat_actions_")) { + indexScans.push(`${nodeType}:${indexName}`); + } + for (const child of (node.Plans as Array> | undefined) ?? []) walk(child); + }; + walk((row!["QUERY PLAN"] as Array<{ Plan: Record }>)[0]!.Plan); + return { seqScans, indexScans }; + }; + const captureSelects = async (fn: () => Promise) => { + const captured: Array<{ sql: string; params: unknown[] }> = []; + const previousDebug = db.$client.options.debug; + db.$client.options.debug = (_conn: number, text: string, params: unknown[]) => { + if (/^select\b/i.test(text.trim()) && text.includes('"chat_actions"')) { + captured.push({ sql: text, params: [...params] }); + } + }; + try { + await fn(); + } finally { + db.$client.options.debug = previousDebug; + } + return captured; + }; + + try { + await db.$client.unsafe( + `insert into chat_actions (company_id, endpoint_id, kind, provider_action_id, status, payload, result) + select $1::uuid, $2::uuid, 'github_webhook_ingress', 'hist-ingress-' || g, 'processed', + jsonb_build_object('deliveryId', 'd-' || g, 'body', repeat('x', 500)), + jsonb_build_object('httpStatus', 200, 'retryable', false) + from generate_series(1, 4000) g`, + [s.companyId, s.endpointId], + ); + await db.$client.unsafe( + `insert into chat_actions (company_id, endpoint_id, conversation_id, kind, provider_action_id, status, payload, result) + select $1::uuid, $2::uuid, $3::uuid, 'github_review_publication', 'hist-pub-' || g, 'processed', + jsonb_build_object('operation', 'comment', 'session', jsonb_build_object('companyId', $1::text, 'issueId', gen_random_uuid()::text, 'runId', gen_random_uuid()::text, 'agentId', $4::text)), + jsonb_build_object('id', 'c-' || g, 'url', 'https://github.com/o/r/pull/1#issuecomment-' || g) + from generate_series(1, 500) g`, + [s.companyId, s.endpointId, s.conversationId, s.agentId], + ); + await db.$client.unsafe( + `insert into chat_actions (company_id, endpoint_id, kind, provider_action_id, status, payload) + select $1::uuid, $2::uuid, 'task_control_authorization', 'hist-auth-' || g, 'issued', + jsonb_build_object('publicationId', gen_random_uuid()::text) + from generate_series(1, 500) g`, + [s.companyId, s.endpointId], + ); + + const pubId = randomUUID(); + const ingressId = randomUUID(); + const retryId = randomUUID(); + await db.insert(chatActions).values([ + { + id: pubId, + companyId: s.companyId, + endpointId: s.endpointId, + conversationId: s.conversationId, + kind: "github_review_publication", + providerActionId: `pub-target-${pubId}`, + status: "processing", + payload: { + operation: "comment", + session: { companyId: s.companyId, issueId: s.issueId, runId, agentId: s.agentId }, + }, + result: { replyWriteStarted: true }, + }, + { + id: ingressId, + companyId: s.companyId, + endpointId: s.endpointId, + kind: "github_webhook_ingress", + providerActionId: `ingress-target-${ingressId}`, + status: "received", + payload: { deliveryId: "target" }, + }, + { + id: retryId, + companyId: s.companyId, + endpointId: s.endpointId, + kind: "failed_run_retry", + providerActionId: `retry-target-${retryId}`, + status: "issued", + payload: { issueId: s.issueId }, + }, + ]); + await db.$client.unsafe("analyze chat_actions"); + + let replyState: Awaited> | undefined; + const replyQueries = await captureSelects(async () => { + replyState = await githubRunReplyState(db, { + companyId: s.companyId, + endpointId: s.endpointId, + issueId: s.issueId, + runId, + }); + }); + expect(replyState).toBe("unsettled"); + expect(replyQueries).toHaveLength(1); + const replyPlan = await explainChatActions(replyQueries[0]!.sql, replyQueries[0]!.params); + expect(replyPlan.seqScans).toEqual([]); + expect(replyPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_github_run_publications_idx"))).toBe(true); + + await db.update(chatActions) + .set({ status: "processed", result: { id: "c-target", url: "https://github.com/o/r/pull/1#issuecomment-target" } }) + .where(eq(chatActions.id, pubId)); + await expect(githubRunReplyState(db, { + companyId: s.companyId, + endpointId: s.endpointId, + issueId: s.issueId, + runId, + })).resolves.toBe("confirmed"); + + let ingressNext: number | null = null; + const scheduledKinds = Object.keys(CHAT_ACTION_QUEUES) as ScheduledChatAction[]; + const workQueries = await captureSelects(async () => { + for (const kind of scheduledKinds) { + const at = await nextChatActionAt(db, kind); + if (kind === "github_webhook_ingress") ingressNext = at; + } + }); + expect(ingressNext).toBe(0); + expect(workQueries).toHaveLength(scheduledKinds.length); + for (const query of workQueries) { + const plan = await explainChatActions(query.sql, query.params); + expect(plan.seqScans).toEqual([]); + expect(plan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true); + } + + const noProviderFetch: typeof fetch = async () => { + throw new Error("unexpected provider call"); + }; + const githubReviewQueries = await captureSelects(async () => { + const reviews = githubChatReviewService(db, noProviderFetch); + await reviews.nextPendingAt(); + await reviews.processPending(); + }); + expect(githubReviewQueries).toHaveLength(2); + for (const query of githubReviewQueries) { + const plan = await explainChatActions(query.sql, query.params); + expect(plan.seqScans).toEqual([]); + expect(plan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true); + } + + const githubResponseQueries = await captureSelects(async () => { + await githubResponseCommentService(db, noProviderFetch).processPending(); + }); + expect(githubResponseQueries.length).toBeGreaterThanOrEqual(1); + const pendingResponsePlan = await explainChatActions(githubResponseQueries[0]!.sql, githubResponseQueries[0]!.params); + expect(pendingResponsePlan.seqScans).toEqual([]); + expect(pendingResponsePlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true); + + const voiceDispatchSql = db + .select({ id: chatActions.id }) + .from(chatActions) + .where(and(eq(chatActions.kind, "speko_voice_reply_push"), eq(chatActions.status, "dispatching"))) + .orderBy(asc(chatActions.id)) + .limit(100) + .toSQL(); + const voiceDispatchPlan = await explainChatActions(voiceDispatchSql.sql, voiceDispatchSql.params); + expect(voiceDispatchPlan.seqScans).toEqual([]); + expect(voiceDispatchPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true); + + const dueIngressQuery = db + .select({ id: chatActions.id }) + .from(chatActions) + .where(dueChatAction("github_webhook_ingress", Date.now())) + .orderBy(asc(chatActions.createdAt)) + .limit(25); + const dueIngressRows = await dueIngressQuery; + expect(dueIngressRows.map((row) => row.id)).toContain(ingressId); + const dueIngressSql = dueIngressQuery.toSQL(); + const dueIngressPlan = await explainChatActions(dueIngressSql.sql, dueIngressSql.params); + expect(dueIngressPlan.seqScans).toEqual([]); + expect(dueIngressPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true); + + const dueRetryQuery = db + .select({ id: chatActions.id }) + .from(chatActions) + .where(dueChatAction("failed_run_retry", Date.now())) + .orderBy(asc(chatActions.createdAt), asc(chatActions.id)) + .limit(20); + const dueRetryRows = await dueRetryQuery; + expect(dueRetryRows.map((row) => row.id)).toContain(retryId); + const dueRetrySql = dueRetryQuery.toSQL(); + const dueRetryPlan = await explainChatActions(dueRetrySql.sql, dueRetrySql.params); + expect(dueRetryPlan.seqScans).toEqual([]); + expect(dueRetryPlan.indexScans.some((scan) => scan.endsWith(":chat_actions_pending_work_idx"))).toBe(true); + } finally { + await db.delete(chatActions).where(eq(chatActions.companyId, s.companyId)); + } + }); });