diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 867e205c2f1..303d460e803 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -925,6 +925,7 @@ const MIGRATIONS_WITH_TOP_LEVEL_STATEMENTS = new Set([ "0507_special_kang.sql", "0511_simple_the_hunter.sql", "0512_stormy_the_hood.sql", + "0513_closed_wither.sql", ]); async function applyPendingMigrationsManually( diff --git a/packages/db/src/migrations/0513_closed_wither.sql b/packages/db/src/migrations/0513_closed_wither.sql new file mode 100644 index 00000000000..75aaeb521fa --- /dev/null +++ b/packages/db/src/migrations/0513_closed_wither.sql @@ -0,0 +1 @@ +CREATE INDEX CONCURRENTLY IF NOT EXISTS "issues_company_issue_number_idx" ON "issues" USING btree ("company_id","issue_number"); diff --git a/packages/db/src/migrations/meta/0508_snapshot.json b/packages/db/src/migrations/meta/0513_snapshot.json similarity index 97% rename from packages/db/src/migrations/meta/0508_snapshot.json rename to packages/db/src/migrations/meta/0513_snapshot.json index b63b08c8692..93a43e70c54 100644 --- a/packages/db/src/migrations/meta/0508_snapshot.json +++ b/packages/db/src/migrations/meta/0513_snapshot.json @@ -1,6 +1,6 @@ { - "id": "8ddb0345-f9e8-4dde-8156-391f71d858b1", - "prevId": "2f88a046-845e-47f5-ad81-b3b338c79fb5", + "id": "9a37a733-51bb-4fbf-a1a9-ac65344e70cc", + "prevId": "d51fc684-2373-470f-91c1-bdb01e0def42", "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": "", @@ -16464,6 +16855,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 +16904,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 +17029,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 +17183,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 +17225,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 +17766,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": "", @@ -26298,6 +26873,160 @@ "checkConstraints": {}, "isRLSEnabled": false }, + "public.document_annotation_comment_reactions": { + "name": "document_annotation_comment_reactions", + "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 + }, + "comment_id": { + "name": "comment_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "reaction": { + "name": "reaction", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "removed_at": { + "name": "removed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "document_annotation_comment_reactions_company_comment_idx": { + "name": "document_annotation_comment_reactions_company_comment_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "document_annotation_comment_reactions_comment_reaction_actor_idx": { + "name": "document_annotation_comment_reactions_comment_reaction_actor_idx", + "columns": [ + { + "expression": "comment_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "reaction", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_type", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "actor_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "document_annotation_comment_reactions_company_id_companies_id_fk": { + "name": "document_annotation_comment_reactions_company_id_companies_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "companies", + "columnsFrom": [ + "company_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk": { + "name": "document_annotation_comment_reactions_comment_id_document_annotation_comments_id_fk", + "tableFrom": "document_annotation_comment_reactions", + "tableTo": "document_annotation_comments", + "columnsFrom": [ + "comment_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "document_annotation_comment_reactions_reaction_chk": { + "name": "document_annotation_comment_reactions_reaction_chk", + "value": "\"document_annotation_comment_reactions\".\"reaction\" in ('done', 'check', 'thumbs_up', 'question')" + }, + "document_annotation_comment_reactions_actor_type_chk": { + "name": "document_annotation_comment_reactions_actor_type_chk", + "value": "\"document_annotation_comment_reactions\".\"actor_type\" in ('agent', 'user')" + } + }, + "isRLSEnabled": false + }, "public.document_annotation_comments": { "name": "document_annotation_comments", "schema": "", @@ -35094,6 +35823,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": "", @@ -39149,6 +40418,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", @@ -44076,6 +45372,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", @@ -44139,6 +45441,13 @@ "notNull": true, "default": "'backlog'" }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'board'" + }, "status_version": { "name": "status_version", "type": "bigint", @@ -44226,12 +45535,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", @@ -44505,6 +45890,60 @@ "method": "btree", "with": {} }, + "issues_company_scope_status_idx": { + "name": "issues_company_scope_status_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "issues_company_scope_updated_idx": { + "name": "issues_company_scope_updated_idx", + "columns": [ + { + "expression": "company_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "scope", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "updated_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, "issues_company_harness_kind_idx": { "name": "issues_company_harness_kind_idx", "columns": [ @@ -45195,6 +46634,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": { @@ -45237,6 +46789,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", @@ -45354,6 +46919,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", @@ -45398,9 +46976,17 @@ "name": "issues_visibility_check", "value": "\"issues\".\"visibility\" in ('open', 'private')" }, + "issues_scope_check": { + "name": "issues_scope_check", + "value": "\"issues\".\"scope\" in ('board', 'channel', 'agent', 'chat')" + }, "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 diff --git a/packages/db/src/migrations/meta/_journal.json b/packages/db/src/migrations/meta/_journal.json index 1ccecebecff..2258adff6de 100644 --- a/packages/db/src/migrations/meta/_journal.json +++ b/packages/db/src/migrations/meta/_journal.json @@ -3578,6 +3578,13 @@ "when": 1796072868844, "tag": "0512_stormy_the_hood", "breakpoints": true + }, + { + "idx": 513, + "version": "7", + "when": 1796171923647, + "tag": "0513_closed_wither", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/packages/db/src/schema/issues.ts b/packages/db/src/schema/issues.ts index db60cc681ec..40e9292415a 100644 --- a/packages/db/src/schema/issues.ts +++ b/packages/db/src/schema/issues.ts @@ -267,5 +267,8 @@ export const issues = pgTable( and ${table.claimTokenHash} is not null`, ) .concurrently(), + companyIssueNumberIdx: index("issues_company_issue_number_idx") + .on(table.companyId, table.issueNumber) + .concurrently(), }), ); diff --git a/server/src/__tests__/activity-log-responsible-user.test.ts b/server/src/__tests__/activity-log-responsible-user.test.ts index 5b855ff0577..eb4466bb68d 100644 --- a/server/src/__tests__/activity-log-responsible-user.test.ts +++ b/server/src/__tests__/activity-log-responsible-user.test.ts @@ -1,5 +1,6 @@ +import os from "node:os"; import { randomUUID } from "node:crypto"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { eq } from "drizzle-orm"; import { activityLog, @@ -9,14 +10,19 @@ import { createDb, heartbeatRuns, issues, + subscribeDatabaseWork, type Db, } from "@paperclipai/db"; import { + createActivityDetailsRedactor, logActivity, + persistActivity, resolveResponsibleUserIdForActivity, type ActivityPublication, type LogActivityInput, } from "../services/activity-log.js"; +import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; +import { instanceSettingsService } from "../services/instance-settings.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, @@ -243,4 +249,84 @@ describeEmbeddedPostgres("logActivity responsible-user stamping", () => { expect(row?.responsibleUserId).toBe("key-user"); }); + + it("reuses a supplied redactor and skips nested savepoints when persistActivity runs inside a PgTransaction", async () => { + const companyId = randomUUID(); + const issueId = randomUUID(); + const currentUsername = os.userInfo().username; + + await db.insert(companies).values({ + id: companyId, + name: "TxActivityCo", + issuePrefix: `A${companyId.replace(/-/g, "").slice(0, 6).toUpperCase()}`, + defaultResponsibleUserId: "tx-owner", + requireBoardApprovalForNewAgents: false, + }); + await db.insert(issues).values({ + id: issueId, + companyId, + title: "Transactional activity issue", + status: "todo", + scope: "board", + responsibleUserId: "tx-owner", + }); + + await instanceSettingsService(db).updateGeneral({ + censorUsernameInLogs: true, + }); + try { + const redactor = await createActivityDetailsRedactor(db); + const settledHints: string[] = []; + const unsubscribe = subscribeDatabaseWork( + db, + DELIVERY_QUEUES.mcpEvents, + (event, hints) => { + if (event === "settled" && hints) { + settledHints.push(...hints); + } + }, + ); + + try { + await db.transaction(async (tx) => { + const nestedTxSpy = vi.spyOn(tx, "transaction"); + await persistActivity( + tx as unknown as Db, + { + companyId, + actorType: "user", + actorId: "tx-owner", + action: "issue.comment_added", + entityType: "issue", + entityId: issueId, + issueId, + responsibleUserIdOverride: "tx-owner", + details: { + workspacePath: `/Users/${currentUsername}/project`, + }, + }, + undefined, + { redactor }, + ); + expect(nestedTxSpy).not.toHaveBeenCalled(); + }); + } finally { + unsubscribe(); + } + + expect(settledHints).toContain(`task:${issueId}`); + const [stored] = await db + .select({ details: activityLog.details }) + .from(activityLog) + .where(eq(activityLog.entityId, issueId)); + const workspacePath = String( + (stored?.details as Record | null)?.workspacePath ?? "", + ); + expect(workspacePath).not.toContain(currentUsername); + } finally { + await instanceSettingsService(db).updateGeneral({ + censorUsernameInLogs: false, + }); + } + }); }); diff --git a/server/src/__tests__/headless-channels-schemas-batch.test.ts b/server/src/__tests__/headless-channels-schemas-batch.test.ts index bfadbf3c975..24345ac07be 100644 --- a/server/src/__tests__/headless-channels-schemas-batch.test.ts +++ b/server/src/__tests__/headless-channels-schemas-batch.test.ts @@ -18,6 +18,7 @@ import { actorMiddleware } from "../middleware/auth.js"; import { errorHandler } from "../middleware/error-handler.js"; import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js"; import { issueRoutes } from "../routes/issues.js"; +import { resolveHeadlessActor } from "../services/headless-common.js"; import { issueService } from "../services/issues.js"; import { getEmbeddedPostgresTestSupport, @@ -1327,4 +1328,168 @@ describeEmbeddedPostgres("headless channels, schemas, CAS labels, and batch DAG" }, ]); }); + + it("10. self-heals drifted company issueCounter on channel post and batch create without O(N) pre-scans", async () => { + const app = express(); + app.use(express.json()); + app.use( + actorMiddleware(db, { + deploymentMode: "authenticated", + resolveSession: async (req) => { + const uid = req.header("x-test-user-id"); + if (!uid) return null; + return { + session: { id: `sess-${uid}`, userId: uid }, + user: { id: uid, name: uid, email: `${uid}@example.test` }, + }; + }, + }), + ); + app.use( + "/api", + headlessChannelsSchemasRoutes(db, { deploymentMode: "authenticated" }), + ); + app.use(errorHandler); + + const [companyRow] = await db + .select({ issuePrefix: companies.issuePrefix }) + .from(companies) + .where(eq(companies.id, companyId)); + const prefix = companyRow!.issuePrefix; + + await db.insert(issues).values({ + companyId, + title: "Imported legacy #50 without #1..49", + status: "backlog", + scope: "board", + issueNumber: 50, + identifier: `${prefix}-50`, + createdByUserId: ownerUserId, + }); + await db + .update(companies) + .set({ issueCounter: 0 }) + .where(eq(companies.id, companyId)); + + const postRes = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .set("x-paperclip-actor-profile", "perf-bot") + .send({ + channel: "eng/perf", + text: "Post after non-colliding drifted counter", + labels: { env: "prod" }, + tagLabels: ["fast-path"], + }) + .expect(201); + + expect(postRes.body.identifier).toBe(`${prefix}-51`); + expect(postRes.body.channel).toBe("eng/perf"); + expect(postRes.body.kvLabels).toEqual({ env: "prod" }); + expect(postRes.body.tagLabels).toEqual(["fast-path"]); + expect(postRes.body.actorProfile).toBe("perf-bot"); + + await db.insert(issues).values({ + companyId, + title: "Lone backdated imported #95 without #52..94", + status: "backlog", + scope: "board", + issueNumber: 95, + identifier: `${prefix}-95`, + createdByUserId: ownerUserId, + createdAt: new Date("2000-01-01T00:00:00.000Z"), + updatedAt: new Date("2000-01-01T00:00:00.000Z"), + }); + + const batchRes = await request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "eng/perf", + tasks: [ + { key: "t1", title: "Batch task 1" }, + { key: "t2", title: "Batch task 2", needs: ["t1"] }, + ], + }) + .expect(201); + + expect(batchRes.body.tasks.map((t: { identifier: string }) => t.identifier)).toEqual([ + `${prefix}-96`, + `${prefix}-97`, + ]); + + const [concurrentPost, concurrentBatch] = await Promise.all([ + request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "eng/perf", + text: "Concurrent tagged post", + tagLabels: ["shared-concurrent-z", "shared-concurrent-a"], + }), + request(app) + .post(`/api/companies/${companyId}/issues/batch`) + .set("x-test-user-id", ownerUserId) + .send({ + channel: "eng/perf", + tasks: [ + { + key: "ct1", + title: "Concurrent tagged batch task", + tagLabels: ["shared-concurrent-a", "shared-concurrent-z"], + }, + ], + }), + ]); + expect(concurrentPost.status).toBe(201); + expect(concurrentBatch.status).toBe(201); + expect(concurrentPost.body.tagLabels.sort()).toEqual([ + "shared-concurrent-a", + "shared-concurrent-z", + ]); + + await db.insert(agents).values([ + { + companyId, + name: "\t雪\t", + role: "engineer", + status: "idle", + }, + { + companyId, + name: "\tguardian-bot\t", + role: "engineer", + status: "idle", + }, + ]); + + const tabReservedRes = await request(app) + .post(`/api/companies/${companyId}/channels/posts`) + .set("x-test-user-id", ownerUserId) + .set("x-paperclip-actor-profile", "guardian-bot") + .send({ channel: "eng/perf", text: "Should collide with tab-padded agent" }); + expect(tabReservedRes.status).toBe(409); + expect(tabReservedRes.body.code).toBe("profile_matches_registered_agent"); + + await expect( + resolveHeadlessActor( + db, + { + actor: { + type: "board", + userId: ownerUserId, + source: "session", + companyIds: [companyId], + isInstanceAdmin: false, + }, + header: (name: string) => + name.toLowerCase() === "x-paperclip-actor-profile" ? "雪" : undefined, + } as any, + companyId, + { deploymentMode: "authenticated", requiredAction: "post" }, + ), + ).rejects.toMatchObject({ + status: 409, + }); + }); }); diff --git a/server/src/__tests__/headless-queues-leases-events.test.ts b/server/src/__tests__/headless-queues-leases-events.test.ts index e3cf468ed59..cec52ca81f2 100644 --- a/server/src/__tests__/headless-queues-leases-events.test.ts +++ b/server/src/__tests__/headless-queues-leases-events.test.ts @@ -15,6 +15,7 @@ import { agents, authUsers, boardEvents, + channelAccessMembers, channels, companies, companyMemberships, @@ -28,6 +29,7 @@ import { issueThreadInteractions, issueTreeHolds, issueWorkProducts, + labels, projectAccessMembers, projects, reconcileDatabaseWork, @@ -45,6 +47,7 @@ import { import { parseSseEventStream } from "@paperclipai/shared/sdk/sse"; import { actorMiddleware } from "../middleware/auth.js"; import { errorHandler } from "../middleware/error-handler.js"; +import { headlessChannelsSchemasRoutes } from "../routes/headless-channels-schemas.js"; import { headlessQueuesEventsRoutes } from "../routes/headless-queues-events.js"; import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js"; import { DELIVERY_QUEUES } from "../services/delivery-work-notifications.js"; @@ -55,6 +58,7 @@ import { import { createScheduledBoardPostsWorker } from "../services/headless-events-schedules-interactions.js"; import { createClaimLeaseExpiryWorker } from "../services/headless-task-queue.js"; import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; +import { issueService } from "../services/issues.js"; import { recoveryService } from "../services/recovery/service.js"; import { getEmbeddedPostgresTestSupport, @@ -93,6 +97,7 @@ function createTestServer(db: Db) { } next(); }); + app.use("/api", headlessChannelsSchemasRoutes(db)); app.use("/api", headlessQueuesEventsRoutes(db)); app.use(errorHandler); return createServer(app); @@ -1562,4 +1567,524 @@ describeEmbeddedPostgres("headless queues, fenced leases, events & interactions" const wokenClaim = (await wokenClaimRes.json()) as TaskClaimView; expect(wokenClaim.issue.id).toBe(poolDep.id); }); + + it("11. drains live SSE bursts in strict seq order with payload.labels filtering and immediate private-channel revocation", async () => { + const { company, channel: openCh, agent } = await seedCompanyAndChannel("sse-burst"); + const [privCh] = await db + .insert(channels) + .values({ + companyId: company.id, + path: "sec/live", + visibility: "private", + createdByUserId: "owner-user", + }) + .returning(); + await db.insert(channelAccessMembers).values({ + companyId: company.id, + channelId: privCh!.id, + subjectType: "agent", + subjectId: agent.id, + }); + + const openIssue = await seedTask(company.id, company.issuePrefix, { + title: "Open burst thread", + channelId: openCh.id, + }); + const [privIssue] = await db + .insert(issues) + .values({ + companyId: company.id, + channelId: privCh!.id, + visibility: "private", + title: "Private burst thread", + status: "backlog", + scope: "channel", + issueNumber: ++issueSeq + 5000, + identifier: `${company.issuePrefix}-${issueSeq + 5000}`, + createdByUserId: "owner-user", + }) + .returning(); + await db + .update(issues) + .set({ privacyRootIssueId: privIssue!.id }) + .where(eq(issues.id, privIssue!.id)); + + const ac = new AbortController(); + const res = await fetch( + `${baseUrl}/api/companies/${company.id}/events/stream?label=env%3Dprod`, + { + headers: { + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + signal: ac.signal, + }, + ); + expect(res.status).toBe(200); + expect(res.body).not.toBeNull(); + + const received: BoardEventView[] = []; + const readerDone = (async () => { + for await (const ev of parseSseEventStream(res.body!, ac.signal)) { + received.push(ev); + } + })().catch(() => {}); + + try { + await new Promise((r) => setTimeout(r, 50)); + + const expectedSeqs: number[] = []; + for (let i = 0; i < 25; i += 1) { + const matchEv = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: openCh.id, + channelPath: openCh.path, + issueId: openIssue.id, + identifier: openIssue.identifier, + actor: { + principalType: "user", + userId: "owner-user", + agentId: null, + agentName: null, + actorProfile: "burst-bot", + }, + payload: { title: `Burst #${i}`, labels: { env: "prod", idx: String(i) } }, + }); + expectedSeqs.push(matchEv.seq); + publishCommittedBoardEvent(matchEv); + + if (i < 10) { + const skipEv = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: openCh.id, + channelPath: openCh.path, + issueId: openIssue.id, + identifier: openIssue.identifier, + actor: { + principalType: "user", + userId: "owner-user", + agentId: null, + agentName: null, + actorProfile: "burst-bot", + }, + payload: { title: `Skip #${i}`, labels: { env: "staging" } }, + }); + publishCommittedBoardEvent(skipEv); + } + } + + const allowedPrivEv = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: privCh!.id, + channelPath: privCh!.path, + issueId: privIssue!.id, + identifier: privIssue!.identifier, + actor: { + principalType: "user", + userId: "owner-user", + agentId: null, + agentName: null, + actorProfile: "owner", + }, + payload: { title: "Before revocation", labels: { env: "prod" } }, + }); + expectedSeqs.push(allowedPrivEv.seq); + publishCommittedBoardEvent(allowedPrivEv); + + await vi.waitFor(() => { + expect(received.map((e) => e.seq)).toEqual(expectedSeqs); + }); + + await db + .delete(channelAccessMembers) + .where( + and( + eq(channelAccessMembers.channelId, privCh!.id), + eq(channelAccessMembers.subjectId, agent.id), + ), + ); + + const revokedPrivEv = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: privCh!.id, + channelPath: privCh!.path, + issueId: privIssue!.id, + identifier: privIssue!.identifier, + actor: { + principalType: "user", + userId: "owner-user", + agentId: null, + agentName: null, + actorProfile: "owner", + }, + payload: { title: "After revocation", labels: { env: "prod" } }, + }); + publishCommittedBoardEvent(revokedPrivEv); + + const sentinelEv = await appendBoardEvent(db, { + companyId: company.id, + type: "thread.posted", + channelId: openCh.id, + channelPath: openCh.path, + issueId: openIssue.id, + identifier: openIssue.identifier, + actor: { + principalType: "user", + userId: "owner-user", + agentId: null, + agentName: null, + actorProfile: "burst-bot", + }, + payload: { title: "Sentinel after revocation", labels: { env: "prod" } }, + }); + expectedSeqs.push(sentinelEv.seq); + publishCommittedBoardEvent(sentinelEv); + + await vi.waitFor(() => { + expect(received.map((e) => e.seq)).toEqual(expectedSeqs); + }); + } finally { + ac.abort(); + await readerDone; + } + + const [urgentLabelRow] = await db + .insert(labels) + .values({ + companyId: company.id, + name: "urgent", + color: "#ef4444", + }) + .returning(); + + const [maxBeforeRealBurst] = await db + .select({ maxSeq: sql`coalesce(max(${boardEvents.seq}), 0)::int` }) + .from(boardEvents) + .where(eq(boardEvents.companyId, company.id)); + const afterBeforeRealBurst = `evt_${maxBeforeRealBurst?.maxSeq ?? 0}`; + + const claimOnlyAc = new AbortController(); + const claimOnlyRes = await fetch( + `${baseUrl}/api/companies/${company.id}/events/stream?event=task.claimed&label=urgent`, + { + headers: { + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + signal: claimOnlyAc.signal, + }, + ); + expect(claimOnlyRes.status).toBe(200); + const claimOnlyReceived: BoardEventView[] = []; + const claimOnlyDone = (async () => { + for await (const ev of parseSseEventStream(claimOnlyRes.body!, claimOnlyAc.signal)) { + claimOnlyReceived.push(ev); + } + })().catch(() => {}); + + const existsAc = new AbortController(); + const existsRes = await fetch( + `${baseUrl}/api/companies/${company.id}/events/stream?label=urgent`, + { + headers: { + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + signal: existsAc.signal, + }, + ); + expect(existsRes.status).toBe(200); + const existsReceived: BoardEventView[] = []; + const existsReaderDone = (async () => { + for await (const ev of parseSseEventStream(existsRes.body!, existsAc.signal)) { + existsReceived.push(ev); + } + })().catch(() => {}); + + try { + await new Promise((r) => setTimeout(r, 50)); + + const untaggedCreateRes = await fetch( + `${baseUrl}/api/companies/${company.id}/channels/posts`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + channel: "burst/open/real-1", + status: "todo", + title: "Initially untagged task", + }), + }, + ); + expect(untaggedCreateRes.status).toBe(201); + const untaggedTask = (await untaggedCreateRes.json()) as HeadlessIssueView; + + await issueService(db).update(untaggedTask.id, { + labelIds: [urgentLabelRow!.id], + }); + + const untaggedClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ channel: "burst/open/real-1" }), + }, + ); + expect(untaggedClaimRes.status).toBe(200); + const untaggedClaim = (await untaggedClaimRes.json()) as TaskClaimView; + expect(untaggedClaim.issue.id).toBe(untaggedTask.id); + + await vi.waitFor(() => { + expect( + claimOnlyReceived.map((e) => `${e.issueId}:${e.type}`), + ).toContain(`${untaggedTask.id}:task.claimed`); + expect( + existsReceived.map((e) => `${e.issueId}:${e.type}`), + ).toContain(`${untaggedTask.id}:task.claimed`); + }); + expect( + claimOnlyReceived.find((e) => e.issueId === untaggedTask.id)?.payload.tagLabels, + ).toEqual(["urgent"]); + + await issueService(db).update(untaggedTask.id, { labelIds: [] }); + + const untaggedReleaseRes = await fetch( + `${baseUrl}/api/issues/${untaggedTask.id}/claim/release`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": untaggedClaim.claimToken, + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ claimEpoch: untaggedClaim.claimEpoch }), + }, + ); + expect(untaggedReleaseRes.status).toBe(200); + + const taggedCreateRes = await fetch( + `${baseUrl}/api/companies/${company.id}/channels/posts`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + channel: "burst/open/real-2", + status: "todo", + title: "Tagged lifecycle task", + tagLabels: ["urgent"], + }), + }, + ); + expect(taggedCreateRes.status).toBe(201); + const taggedTask = (await taggedCreateRes.json()) as HeadlessIssueView; + + const taggedClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ channel: "burst/open/real-2" }), + }, + ); + expect(taggedClaimRes.status).toBe(200); + const taggedClaim = (await taggedClaimRes.json()) as TaskClaimView; + expect(taggedClaim.issue.id).toBe(taggedTask.id); + + const taggedCommentRes = await fetch( + `${baseUrl}/api/issues/${taggedTask.id}/comments`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ body: "Unlabeled comment while issue has urgent tag" }), + }, + ); + expect(taggedCommentRes.status).toBe(201); + + await vi.waitFor(() => { + expect( + existsReceived.map((e) => `${e.issueId}:${e.type}`), + ).toContain(`${taggedTask.id}:comment.posted`); + }); + expect( + existsReceived.find( + (e) => e.issueId === taggedTask.id && e.type === "task.claimed", + )?.payload.tagLabels, + ).toEqual(["urgent"]); + expect( + existsReceived.find( + (e) => e.issueId === taggedTask.id && e.type === "comment.posted", + )?.payload.tagLabels, + ).toEqual(["urgent"]); + + await issueService(db).update(taggedTask.id, { labelIds: [] }); + + const taggedReleaseRes = await fetch( + `${baseUrl}/api/issues/${taggedTask.id}/claim/release`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": taggedClaim.claimToken, + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ claimEpoch: taggedClaim.claimEpoch }), + }, + ); + expect(taggedReleaseRes.status).toBe(200); + + const kvCreateRes = await fetch( + `${baseUrl}/api/companies/${company.id}/channels/posts`, + { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + channel: "burst/open/real-3", + status: "todo", + title: "KV urgent lifecycle task", + labels: { urgent: "1" }, + }), + }, + ); + expect(kvCreateRes.status).toBe(201); + const kvTask = (await kvCreateRes.json()) as HeadlessIssueView; + + const kvClaimRes = await fetch( + `${baseUrl}/api/companies/${company.id}/tasks/claim`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ channel: "burst/open/real-3" }), + }, + ); + expect(kvClaimRes.status).toBe(200); + const kvClaim = (await kvClaimRes.json()) as TaskClaimView; + expect(kvClaim.issue.id).toBe(kvTask.id); + + const [legacyPreDeployRow] = await db + .insert(boardEvents) + .values({ + companyId: company.id, + eventType: "task.lease_renewed", + channelId: openCh.id, + channelPath: "burst/open/real-3", + issueId: kvTask.id, + identifier: kvTask.identifier, + actorType: "agent", + actorId: agent.id, + actorName: agent.name, + payload: { leaseExpiresAt: "2099-01-01T00:00:00.000Z" }, + }) + .returning(); + + const kvUnsetRes = await fetch( + `${baseUrl}/api/issues/${kvTask.id}/kv-labels`, + { + method: "PATCH", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ unset: ["urgent"] }), + }, + ); + expect(kvUnsetRes.status).toBe(200); + + const kvReleaseRes = await fetch( + `${baseUrl}/api/issues/${kvTask.id}/claim/release`, + { + method: "POST", + headers: { + "content-type": "application/json", + "x-paperclip-claim-token": kvClaim.claimToken, + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + body: JSON.stringify({ claimEpoch: kvClaim.claimEpoch }), + }, + ); + expect(kvReleaseRes.status).toBe(200); + + const expectedLivePairs = [ + `${untaggedTask.id}:task.claimed`, + `${taggedTask.id}:task.created`, + `${taggedTask.id}:task.ready`, + `${taggedTask.id}:task.claimed`, + `${taggedTask.id}:comment.posted`, + `${kvTask.id}:task.created`, + `${kvTask.id}:task.ready`, + `${kvTask.id}:task.claimed`, + ]; + + await vi.waitFor(() => { + expect(existsReceived.map((e) => `${e.issueId}:${e.type}`)).toEqual( + expectedLivePairs, + ); + }); + + const expectedReplayPairs = [ + ...expectedLivePairs, + `${kvTask.id}:task.lease_renewed`, + ]; + expect(legacyPreDeployRow).toBeDefined(); + + const replayAc = new AbortController(); + const replayRes = await fetch( + `${baseUrl}/api/companies/${company.id}/events/stream?after=${encodeURIComponent(afterBeforeRealBurst)}&label=urgent`, + { + headers: { + "x-test-actor-type": "agent", + "x-test-agent-id": agent.id, + "x-test-company-id": company.id, + }, + signal: replayAc.signal, + }, + ); + expect(replayRes.status).toBe(200); + const replayReceived: BoardEventView[] = []; + const replayDone = (async () => { + for await (const ev of parseSseEventStream(replayRes.body!, replayAc.signal)) { + replayReceived.push(ev); + } + })().catch(() => {}); + try { + await vi.waitFor(() => { + expect(replayReceived.map((e) => `${e.issueId}:${e.type}`)).toEqual( + expectedReplayPairs, + ); + }); + } finally { + replayAc.abort(); + await replayDone; + } + } finally { + claimOnlyAc.abort(); + existsAc.abort(); + await Promise.all([claimOnlyDone, existsReaderDone]); + } + }); }); diff --git a/server/src/app.ts b/server/src/app.ts index a98bd4ccad7..4a295d6e4ba 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -785,7 +785,16 @@ export async function createApp( api.use("/cloud", cloudRoutes()); api.use(cloudInferenceRoutes(db, cloudTrialInferenceController)); api.use(onboardingTelemetryRoutes()); + const headlessHeartbeat = heartbeatService(db, { pluginWorkerManager: workerManager }); api.use(headlessIdentityRoutes(db, { deploymentMode: opts.deploymentMode })); + api.use(headlessChannelsSchemasRoutes(db, { + deploymentMode: opts.deploymentMode, + heartbeat: headlessHeartbeat, + })); + api.use(headlessQueuesEventsRoutes(db, { + deploymentMode: opts.deploymentMode, + heartbeat: headlessHeartbeat, + })); api.use("/companies", companyRoutes(db, opts.storageService)); api.use(llmRoutes(db)); api.use(folderRoutes(db)); @@ -1012,11 +1021,6 @@ export async function createApp( // Issue routes are intentionally mounted after the gateway is constructed because // issue approval endpoints delegate to it. The intervening routers use distinct // route prefixes, so this dependency does not change issue-route precedence. - api.use(headlessChannelsSchemasRoutes(db, { deploymentMode: opts.deploymentMode })); - api.use(headlessQueuesEventsRoutes(db, { - deploymentMode: opts.deploymentMode, - heartbeat: heartbeatService(db, { pluginWorkerManager: workerManager }), - })); api.use(issueRoutes(db, opts.storageService, { chatRunRetries: chatChannels, pluginWorkerManager: workerManager, diff --git a/server/src/routes/headless-channels-schemas.ts b/server/src/routes/headless-channels-schemas.ts index 379d94c2363..a0aced7c6d1 100644 --- a/server/src/routes/headless-channels-schemas.ts +++ b/server/src/routes/headless-channels-schemas.ts @@ -22,6 +22,7 @@ import { issueRelations, issues, issueThreadInteractions, + primeDatabaseWorkTransactionId, projects, } from "@paperclipai/db"; import { @@ -56,6 +57,7 @@ import { updateChannel, } from "../services/headless-channel-admin.js"; import { + createActivityDetailsRedactor, logActivity, publishActivity, type ActivityPublication, @@ -92,6 +94,7 @@ import { resolveHeadlessActor, resolveHeadlessIssueReadCondition, resolveIssueByIdOrIdentifier, + resolveIssueCommentTarget, resolveProjectReference, serializeCommentView, } from "../services/headless-common.js"; @@ -562,9 +565,9 @@ export function headlessChannelsSchemasRoutes( const hasProfileHeader = Boolean(req.header("x-paperclip-actor-profile")); const isExplicitHeadless = hasHeadlessBody || hasProfileHeader; - let targetIssue: typeof issues.$inferSelect; + let targetIssue: Awaited>; try { - targetIssue = await resolveIssueByIdOrIdentifier( + targetIssue = await resolveIssueCommentTarget( db, req.params.id as string, ); @@ -633,11 +636,14 @@ export function headlessChannelsSchemasRoutes( data: schemaInput.data as Record, }); } - const validatedBlocks = await validateSchemaBlocks( - db, - targetIssue.companyId, - combinedBlocks, - ); + const validatedBlocks = + combinedBlocks.length > 0 + ? await validateSchemaBlocks( + db, + targetIssue.companyId, + combinedBlocks, + ) + : []; let bodyText = typeof b.body === "string" && b.body.length > 0 @@ -671,15 +677,20 @@ export function headlessChannelsSchemasRoutes( const authorUserId = actor.agentId ? null : (actor.userId ?? "local-board"); const identifier = targetIssue.identifier ?? targetIssue.id; + const activityRedactor = await createActivityDetailsRedactor(db); const publications: ActivityPublication[] = []; let committedEvent: BoardEventView | null = null; + const needsSerializedThreadCheck = + Boolean(clientRequestId) || afterCursor !== undefined; const txResult = await db.transaction(async (tx) => { - await tx - .select({ id: issues.id }) - .from(issues) - .where(eq(issues.id, targetIssue.id)) - .for("update"); + if (needsSerializedThreadCheck) { + await tx + .select({ id: issues.id }) + .from(issues) + .where(eq(issues.id, targetIssue.id)) + .for("update"); + } if (clientRequestId) { const [existing] = await tx @@ -754,7 +765,24 @@ export function headlessChannelsSchemasRoutes( createdAt: now, updatedAt: now, }) - .returning(); + .returning({ + id: issueComments.id, + issueId: issueComments.issueId, + body: issueComments.body, + authorType: issueComments.authorType, + authorUserId: issueComments.authorUserId, + authorAgentId: issueComments.authorAgentId, + actorProfile: issueComments.actorProfile, + kvLabels: issueComments.kvLabels, + schemaBlocks: issueComments.schemaBlocks, + noSync: issueComments.noSync, + createdAt: issueComments.createdAt, + xid: sql`pg_current_xact_id()::text`, + }); + + if (inserted?.xid) { + primeDatabaseWorkTransactionId(tx, inserted.xid); + } await tx .update(issues) @@ -790,6 +818,7 @@ export function headlessChannelsSchemasRoutes( }, }, publications, + { redactor: activityRedactor }, ); committedEvent = await appendBoardEvent(tx, { @@ -853,9 +882,9 @@ export function headlessChannelsSchemasRoutes( return; } - let targetIssue: typeof issues.$inferSelect; + let targetIssue: Awaited>; try { - targetIssue = await resolveIssueByIdOrIdentifier( + targetIssue = await resolveIssueCommentTarget( db, req.params.id as string, ); @@ -1524,9 +1553,9 @@ export function headlessChannelsSchemasRoutes( const isBrowserRequest = Boolean(req.header("referer")) || Boolean(req.header("sec-fetch-mode")); - let targetIssue: typeof issues.$inferSelect; + let targetIssue: Awaited>; try { - targetIssue = await resolveIssueByIdOrIdentifier( + targetIssue = await resolveIssueCommentTarget( db, req.params.id as string, ); diff --git a/server/src/routes/headless-queues-events.ts b/server/src/routes/headless-queues-events.ts index 14f4405c205..0fa4f00a5d8 100644 --- a/server/src/routes/headless-queues-events.ts +++ b/server/src/routes/headless-queues-events.ts @@ -44,7 +44,7 @@ import { cancelSchedule, confirmOnIssue, createSchedule, - eventMatchesFiltersAndAccess, + filterBoardEventsBatchForSubscriber, getCurrentCompanyMaxEventSeq, listSchedules, parseBoardEventFilters, @@ -662,48 +662,57 @@ export function headlessQueuesEventsRoutes( let replaying = true; let lastSentSeq = parsedFilters.afterSeq; const buffered: BoardEventView[] = []; - const issueLabelCache = new Map< - string, - { kvLabels: Record; tagLabels: string[] } - >(); + const pendingLiveEvents: BoardEventView[] = []; + let drainingLive = false; + const drainLiveEvents = async () => { + if (drainingLive || closed) return; + drainingLive = true; + try { + while (!closed && pendingLiveEvents.length > 0) { + const rawBatch = pendingLiveEvents.splice(0, 256); + const unseenBatch = rawBatch.filter((ev) => ev.seq > lastSentSeq); + if (unseenBatch.length === 0) continue; - // Serialize live filter checks and writes so SSE frames preserve order. - let writeChain = Promise.resolve(); + const matched = await filterBoardEventsBatchForSubscriber( + db, + companyId, + actor, + unseenBatch, + parsedFilters, + req.actor, + undefined, + pendingLiveEvents, + ); + if (closed) break; - const deliverEvent = async (ev: BoardEventView) => { - if (ev.type === "labels.changed" && ev.issueId) { - issueLabelCache.delete(ev.issueId); + const frames: string[] = []; + for (const ev of matched) { + if (ev.seq <= lastSentSeq) continue; + lastSentSeq = ev.seq; + frames.push(formatSseFrame(ev)); + } + if (frames.length > 0 && !closed) { + res.write(frames.join("")); + } + } + } catch (err) { + void err; + } finally { + drainingLive = false; + if (!closed && pendingLiveEvents.length > 0) { + void drainLiveEvents(); + } } - if (closed || ev.seq <= lastSentSeq) return; - // Evaluate channel access fresh on live events so revoked channel membership applies immediately. - const matches = await eventMatchesFiltersAndAccess( - db, - companyId, - actor, - ev, - parsedFilters, - undefined, - issueLabelCache, - undefined, - req.actor, - ); - if (closed || !matches || ev.seq <= lastSentSeq) return; - lastSentSeq = ev.seq; - res.write(formatSseFrame(ev)); }; const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { if (closed) return; - if (ev.type === "labels.changed" && ev.issueId) { - issueLabelCache.delete(ev.issueId); - } if (replaying) { buffered.push(ev); return; } - writeChain = writeChain - .then(() => deliverEvent(ev)) - .catch(() => {}); + pendingLiveEvents.push(ev); + void drainLiveEvents(); }); const keepaliveTimer = setInterval(() => { @@ -753,13 +762,14 @@ export function headlessQueuesEventsRoutes( parsedFilters.afterSeq = maxSeq; lastSentSeq = maxSeq; } - replaying = false; - if (!closed && buffered.length > 0) { buffered.sort((a, b) => a.seq - b.seq); - for (const ev of buffered) { - await deliverEvent(ev); - } + pendingLiveEvents.push(...buffered); + } + replaying = false; + + if (!closed && pendingLiveEvents.length > 0) { + await drainLiveEvents(); } } catch { cleanup(); diff --git a/server/src/services/activity-log.ts b/server/src/services/activity-log.ts index 14687c6665d..3a28c259d37 100644 --- a/server/src/services/activity-log.ts +++ b/server/src/services/activity-log.ts @@ -5,7 +5,8 @@ import { beginRunPhase } from "./execution-preparation-timing.js"; import type { ActivityPublication } from "../types/activity-publication.js"; export type { ActivityPublication } from "../types/activity-publication.js"; import { randomUUID } from "node:crypto"; -import { and, eq } from "drizzle-orm"; +import { and, eq, is } from "drizzle-orm"; +import { PgTransaction } from "drizzle-orm/pg-core"; import type { Db } from "@paperclipai/db"; import { activityLog, agentApiKeys, companies, heartbeatRuns, issues } from "@paperclipai/db"; import { isUuidLike, PLUGIN_EVENT_TYPES, type PluginEventType } from "@paperclipai/shared"; @@ -74,7 +75,15 @@ export interface LogActivityInput { } -export async function createActivityDetailsRedactor(db: Db) { +export type ActivityDetailsRedactor = ( + details: Record | null, +) => Record | null; + +export interface PersistActivityOptions { + redactor?: ActivityDetailsRedactor; +} + +export async function createActivityDetailsRedactor(db: Db): Promise { const currentUserRedactionOptions = { enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs, }; @@ -171,8 +180,22 @@ export function publishActivity(publication: ActivityPublication) { } finally { finish(); } } -export async function persistActivity(db: Db, input: LogActivityInput, receipt?: { id: string }) { - const redactedDetails = await redactActivityDetails(db, input.authorization ? { ...input.details, permissionDecision: input.authorization, ...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}) } : input.details ?? null); +export async function persistActivity( + db: Db, + input: LogActivityInput, + receipt?: { id: string }, + options?: PersistActivityOptions, +) { + const rawDetails = input.authorization + ? { + ...input.details, + permissionDecision: input.authorization, + ...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}), + } + : (input.details ?? null); + const redactedDetails = options?.redactor + ? options.redactor(rawDetails) + : await redactActivityDetails(db, rawDetails); const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input); const insert = (runner: Db) => runner.insert(activityLog).values({ ...(receipt ? { id: receipt.id } : {}), @@ -187,13 +210,16 @@ export async function persistActivity(db: Db, input: LogActivityInput, receipt?: responsibleUserId, details: redactedDetails, }).returning({ id: activityLog.id }); + const insertIssueActivity = async (runner: Db) => { + await notifyDeliveryWork(runner, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`); + if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status))) + await notifyActiveRunSilence(runner, { companyId: input.companyId, runId: input.runId }); + return insert(runner); + }; const [activity] = input.entityType === "issue" - ? await db.transaction(async tx => { - await notifyDeliveryWork(tx, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`); - if (input.runId && input.action === "issue.updated" && ["done", "cancelled"].includes(String(input.details?.status))) - await notifyActiveRunSilence(tx, { companyId: input.companyId, runId: input.runId }); - return insert(tx as unknown as Db); - }) + ? (is(db, PgTransaction) + ? await insertIssueActivity(db) + : await db.transaction(async tx => insertIssueActivity(tx as unknown as Db))) : await insert(db); const payload = { @@ -242,8 +268,9 @@ export async function logActivity( db: Db, input: LogActivityInput, postCommitPublications?: ActivityPublication[], + options?: PersistActivityOptions, ) { - const { activity, publication } = await persistActivity(db, input); + const { activity, publication } = await persistActivity(db, input, undefined, options); if (postCommitPublications) { postCommitPublications.push(publication); } else { diff --git a/server/src/services/headless-board-event-stream.ts b/server/src/services/headless-board-event-stream.ts new file mode 100644 index 00000000000..dd6e96ef8e6 --- /dev/null +++ b/server/src/services/headless-board-event-stream.ts @@ -0,0 +1,848 @@ +import { and, asc, eq, gt, inArray } from "drizzle-orm"; +import type { Db } from "@paperclipai/db"; +import { + boardEvents, + channels, + issueLabels, + issues, + labels, +} from "@paperclipai/db"; +import { + boardEventTypeSchema, + formatEventCursor, + isUuidLike, + matchesLabelFilter, + normalizeChannelPath, + normalizeIssueIdentifier, + parseEventCursor, + parseLabelFilterExpr, + parseSchemaRef, + type BoardEventType, + type BoardEventView, + type LabelFilterExpr, + type SchemaBlock, +} from "@paperclipai/shared"; +import { badRequest } from "../errors.js"; +import { issueReadSqlCondition, type AuthorizationActor } from "./authorization.js"; +import { + buildAuthActorFromHeadless, + canAccessChannel, + enforceHeadlessScopes, + findInaccessibleChannelIds, + getLatestCompanyEventCursor, + subscribeCompanyBoardEvents, + type DbOrTx, + type HeadlessActorContext, +} from "./headless-common.js"; + +export type IssueLabelSnapshot = { + kvLabels: Record; + tagLabels: string[]; +}; + +export type IssueLabelCache = Map; + +export interface BoardEventFilterInput { + channel?: string; + issueId?: string; + event?: BoardEventType[]; + label?: string[]; + mentions?: string; + schema?: string; + after?: string; +} + +export interface ParsedBoardEventFilters { + afterSeq: number; + hasExplicitAfter: boolean; + channelNorm: { path: string; isSubtreePrefix: boolean } | null; + issueUuid: string | null; + issueIdentifierUpper: string | null; + eventTypes: Set | null; + labelExprs: LabelFilterExpr[]; + mentionsName: string | null; + schemaFilter: { name: string; version: null | number } | null; +} + +function escapeRegExp(input: string): string { + return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function isChannelAllowedByScopes( + actor: HeadlessActorContext, + channelPath: string, +): boolean { + try { + enforceHeadlessScopes(actor, { channelPath }); + return true; + } catch { + return false; + } +} + +function isStringRecord(val: unknown): val is Record { + return Boolean(val) && typeof val === "object" && !Array.isArray(val); +} + +function extractIssuePayloadKvLabels( + ev: BoardEventView, +): Record | null { + if (ev.type === "labels.changed" && isStringRecord(ev.payload.current)) { + return ev.payload.current; + } + if (isStringRecord(ev.payload.kvLabels)) return ev.payload.kvLabels; + if (isStringRecord(ev.payload.current)) return ev.payload.current; + if ( + (ev.type === "thread.posted" || + ev.type === "task.created" || + ev.type === "task.ready") && + isStringRecord(ev.payload.labels) + ) { + return ev.payload.labels; + } + return null; +} + +function extractPayloadTagLabels( + payload: Record, +): string[] | undefined { + return Array.isArray(payload.tagLabels) + ? payload.tagLabels.filter((x): x is string => typeof x === "string") + : undefined; +} + +export function parseBoardEventFilters( + filters: BoardEventFilterInput, +): ParsedBoardEventFilters { + let afterSeq = 0; + let hasExplicitAfter = false; + if (filters.after !== undefined && filters.after.trim() !== "") { + const parsed = parseEventCursor(filters.after); + if (parsed === null) { + throw badRequest( + `Invalid cursor "${filters.after}": expected evt_`, + ); + } + afterSeq = parsed; + hasExplicitAfter = true; + } + + let channelNorm: { path: string; isSubtreePrefix: boolean } | null = null; + if (filters.channel && filters.channel.trim() !== "") { + try { + channelNorm = normalizeChannelPath(filters.channel, { + allowSubtreePrefix: true, + }); + } catch (err) { + throw badRequest(err instanceof Error ? err.message : "Invalid channel"); + } + } + + let issueUuid: string | null = null; + let issueIdentifierUpper: string | null = null; + if (filters.issueId && filters.issueId.trim() !== "") { + const trimmed = filters.issueId.trim(); + if (isUuidLike(trimmed)) { + issueUuid = trimmed.toLowerCase(); + } else { + issueIdentifierUpper = ( + normalizeIssueIdentifier(trimmed) ?? trimmed + ).toUpperCase(); + } + } + + let eventTypes: Set | null = null; + if (filters.event && filters.event.length > 0) { + eventTypes = new Set(); + for (const raw of filters.event) { + const parsed = boardEventTypeSchema.safeParse(raw); + if (!parsed.success) { + throw badRequest(`Invalid board event type "${raw}"`); + } + eventTypes.add(parsed.data); + } + } + + const labelExprs: LabelFilterExpr[] = []; + if (filters.label && filters.label.length > 0) { + for (const raw of filters.label) { + try { + labelExprs.push(parseLabelFilterExpr(raw)); + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : "Invalid label filter", + ); + } + } + } + + let mentionsName: string | null = null; + if (filters.mentions && filters.mentions.trim() !== "") { + mentionsName = filters.mentions.trim().replace(/^@/, "").toLowerCase(); + } + + let schemaFilter: { name: string; version: number | null } | null = null; + if (filters.schema && filters.schema.trim() !== "") { + const rawSchema = filters.schema.trim(); + if (rawSchema.includes("@")) { + try { + const parsed = parseSchemaRef(rawSchema); + schemaFilter = { name: parsed.name, version: parsed.version }; + } catch (err) { + throw badRequest( + err instanceof Error ? err.message : "Invalid schema filter", + ); + } + } else { + schemaFilter = { name: rawSchema, version: null }; + } + } + + return { + afterSeq, + hasExplicitAfter, + channelNorm, + issueUuid, + issueIdentifierUpper, + eventTypes, + labelExprs, + mentionsName, + schemaFilter, + }; +} + +export async function getCurrentCompanyMaxEventSeq( + dbOrTx: DbOrTx, + companyId: string, +): Promise { + const cursor = await getLatestCompanyEventCursor(dbOrTx, companyId); + return parseEventCursor(cursor) ?? 0; +} + +function serializeBoardEventRow( + row: typeof boardEvents.$inferSelect, +): BoardEventView { + const seq = Number(row.seq); + return { + cursor: formatEventCursor(seq), + seq, + type: row.eventType, + companyId: row.companyId, + channel: row.channelPath ?? null, + issueId: row.issueId ?? null, + identifier: row.identifier ?? null, + actor: { + type: row.actorType, + id: row.actorId ?? null, + name: row.actorName ?? null, + profile: row.actorProfile ?? null, + }, + payload: (row.payload ?? {}) as Record, + createdAt: row.createdAt.toISOString(), + }; +} + +function matchesNonDbEventFilters( + ev: BoardEventView, + parsed: ParsedBoardEventFilters, +): boolean { + if (ev.seq <= parsed.afterSeq) return false; + + if (parsed.eventTypes && !parsed.eventTypes.has(ev.type)) { + return false; + } + + if (parsed.channelNorm) { + if (!ev.channel) return false; + if (parsed.channelNorm.isSubtreePrefix) { + if ( + ev.channel !== parsed.channelNorm.path && + !ev.channel.startsWith(`${parsed.channelNorm.path}/`) + ) { + return false; + } + } else if (ev.channel !== parsed.channelNorm.path) { + return false; + } + } + + if (parsed.issueUuid) { + if (!ev.issueId || ev.issueId.toLowerCase() !== parsed.issueUuid) { + return false; + } + } else if (parsed.issueIdentifierUpper) { + if ( + !ev.identifier || + ev.identifier.toUpperCase() !== parsed.issueIdentifierUpper + ) { + return false; + } + } + + if (parsed.mentionsName) { + const mentionRegex = new RegExp( + `(^|\\s)@${escapeRegExp(parsed.mentionsName)}(\\b|$)`, + "i", + ); + const candidateTexts = [ + ev.payload.text, + ev.payload.body, + ev.payload.title, + ev.payload.message, + ev.payload.description, + ].filter((v): v is string => typeof v === "string"); + if (!candidateTexts.some((txt) => mentionRegex.test(txt))) { + return false; + } + } + + if (parsed.schemaFilter) { + const blocks = Array.isArray(ev.payload.blocks) + ? (ev.payload.blocks as Array>) + : []; + const matched = blocks.some( + (b) => + b && + b.schema === parsed.schemaFilter!.name && + (parsed.schemaFilter!.version === null || + b.version === parsed.schemaFilter!.version), + ); + if (!matched) { + return false; + } + } + + return true; +} + +function canBypassEventChannelPrivacy( + companyId: string, + actor: HeadlessActorContext, +): boolean { + return ( + actor.companyId === companyId && + (actor.isInstanceAdmin || actor.principalType === "local_trusted") + ); +} + +async function canActorAccessEventChannel( + db: Db, + companyId: string, + actor: HeadlessActorContext, + channelPath: string | null, + cache?: Map, +): Promise { + if (!channelPath) return true; + if (!isChannelAllowedByScopes(actor, channelPath)) return false; + if (canBypassEventChannelPrivacy(companyId, actor)) { + return true; + } + + const cached = cache?.get(channelPath); + if (cached !== undefined) return cached; + + const [ch] = await db + .select({ + id: channels.id, + companyId: channels.companyId, + visibility: channels.visibility, + createdByUserId: channels.createdByUserId, + createdByAgentId: channels.createdByAgentId, + }) + .from(channels) + .where(and(eq(channels.companyId, companyId), eq(channels.path, channelPath))) + .limit(1); + + const allowed = ch ? await canAccessChannel(db, ch, actor) : true; + cache?.set(channelPath, allowed); + return allowed; +} + +function findHistoricalKvLabelsBeforeLaterChange( + events: BoardEventView[], + fromIndex: number, + issueId: string, + lookaheadEvents?: BoardEventView[], +): Record | undefined { + for (let j = fromIndex + 1; j < events.length; j += 1) { + const later = events[j]!; + if ( + later.type === "labels.changed" && + later.issueId === issueId && + isStringRecord(later.payload.previous) + ) { + return later.payload.previous; + } + } + if (lookaheadEvents) { + for (let j = 0; j < lookaheadEvents.length; j += 1) { + const later = lookaheadEvents[j]!; + if ( + later.type === "labels.changed" && + later.issueId === issueId && + isStringRecord(later.payload.previous) + ) { + return later.payload.previous; + } + } + } + return undefined; +} + +async function loadCurrentIssueLabelSnapshot( + db: Db, + issueId: string, +): Promise { + const [issueRow] = await db + .select({ kvLabels: issues.kvLabels }) + .from(issues) + .where(eq(issues.id, issueId)) + .limit(1); + const tagRows = await db + .select({ name: labels.name }) + .from(issueLabels) + .innerJoin(labels, eq(issueLabels.labelId, labels.id)) + .where(eq(issueLabels.issueId, issueId)); + return { + kvLabels: (issueRow?.kvLabels ?? {}) as Record, + tagLabels: tagRows.map((t) => t.name), + }; +} + +async function eventMatchesLabelFilters( + db: Db, + ev: BoardEventView, + labelExprs: LabelFilterExpr[], + batchFallbackCache?: IssueLabelCache, + historicalKvLabelsOverride?: Record, +): Promise { + if (ev.type === "labels.changed" && ev.issueId) { + batchFallbackCache?.delete(ev.issueId); + } + if (labelExprs.length === 0) return true; + + let kvLabels = + extractIssuePayloadKvLabels(ev) ?? historicalKvLabelsOverride ?? null; + let tagLabels = extractPayloadTagLabels(ev.payload); + + const unresolvedExistsExpr = labelExprs.some( + (expr) => + expr.kind === "exists" && + (kvLabels === null || + !Object.prototype.hasOwnProperty.call(kvLabels, expr.key)), + ); + const needsTagLookup = tagLabels === undefined && unresolvedExistsExpr; + + if ((kvLabels === null || needsTagLookup) && ev.issueId) { + let fallback = batchFallbackCache?.get(ev.issueId); + if (!fallback) { + fallback = await loadCurrentIssueLabelSnapshot(db, ev.issueId); + if (historicalKvLabelsOverride === undefined) { + batchFallbackCache?.set(ev.issueId, fallback); + } + } + if (kvLabels === null) { + kvLabels = fallback.kvLabels; + } + if (tagLabels === undefined) { + tagLabels = fallback.tagLabels; + } + } + + const effectiveKv = kvLabels ?? {}; + return labelExprs.every((expr) => + matchesLabelFilter(effectiveKv, tagLabels, expr), + ); +} + +export async function eventMatchesFiltersAndAccess( + db: Db, + companyId: string, + actor: HeadlessActorContext, + ev: BoardEventView, + parsed: ParsedBoardEventFilters, + channelCache?: Map, + batchFallbackCache?: IssueLabelCache, + readableIssueIds?: Set, + authActor?: AuthorizationActor, + historicalKvLabelsOverride?: Record, +): Promise { + if (!matchesNonDbEventFilters(ev, parsed)) { + if (ev.type === "labels.changed" && ev.issueId) { + batchFallbackCache?.delete(ev.issueId); + } + return false; + } + if (!(await canActorAccessEventChannel(db, companyId, actor, ev.channel, channelCache))) { + if (ev.type === "labels.changed" && ev.issueId) { + batchFallbackCache?.delete(ev.issueId); + } + return false; + } + if (ev.issueId) { + if (readableIssueIds) { + if (!readableIssueIds.has(ev.issueId)) { + if (ev.type === "labels.changed") { + batchFallbackCache?.delete(ev.issueId); + } + return false; + } + } else { + const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor); + const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); + const [readable] = await db + .select({ id: issues.id }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + eq(issues.id, ev.issueId), + readCondition, + ), + ) + .limit(1); + if (!readable) { + if (ev.type === "labels.changed") { + batchFallbackCache?.delete(ev.issueId); + } + return false; + } + } + } + return eventMatchesLabelFilters( + db, + ev, + parsed.labelExprs, + batchFallbackCache, + historicalKvLabelsOverride, + ); +} + +async function prepareBatchAccessMaps( + db: Db, + companyId: string, + actor: HeadlessActorContext, + events: BoardEventView[], + parsed: ParsedBoardEventFilters, + effectiveAuthActor: AuthorizationActor, + channelCache?: Map, +): Promise<{ + batchChannelAccess: Map; + readableIssueIds: Set; +}> { + const batchChannelAccess = channelCache ?? new Map(); + const scopeEligible = events.filter( + (ev) => + matchesNonDbEventFilters(ev, parsed) && + (!ev.channel || isChannelAllowedByScopes(actor, ev.channel)), + ); + + if (scopeEligible.length === 0) { + return { batchChannelAccess, readableIssueIds: new Set() }; + } + + if (canBypassEventChannelPrivacy(companyId, actor)) { + for (const ev of scopeEligible) { + if (ev.channel) batchChannelAccess.set(ev.channel, true); + } + } else { + const uncheckedPaths = Array.from( + new Set( + scopeEligible + .map((ev) => ev.channel) + .filter( + (ch): ch is string => Boolean(ch) && !batchChannelAccess.has(ch!), + ), + ), + ); + if (uncheckedPaths.length > 0) { + const chRows = await db + .select({ + id: channels.id, + companyId: channels.companyId, + path: channels.path, + visibility: channels.visibility, + createdByUserId: channels.createdByUserId, + createdByAgentId: channels.createdByAgentId, + }) + .from(channels) + .where( + and( + eq(channels.companyId, companyId), + inArray(channels.path, uncheckedPaths), + ), + ); + const inaccessibleIds = new Set( + await findInaccessibleChannelIds(db, companyId, actor, chRows), + ); + for (const ch of chRows) { + batchChannelAccess.set(ch.path, !inaccessibleIds.has(ch.id)); + } + for (const path of uncheckedPaths) { + if (!batchChannelAccess.has(path)) { + batchChannelAccess.set(path, true); + } + } + } + } + + const distinctIssueIds = Array.from( + new Set( + scopeEligible + .filter((ev) => (ev.channel ? batchChannelAccess.get(ev.channel) !== false : true)) + .map((ev) => ev.issueId) + .filter((id): id is string => Boolean(id)), + ), + ); + const readableIssueIds = new Set(); + if (distinctIssueIds.length > 0) { + const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); + const readableRows = await db + .select({ id: issues.id }) + .from(issues) + .where( + and( + eq(issues.companyId, companyId), + inArray(issues.id, distinctIssueIds), + readCondition, + ), + ); + for (const r of readableRows) { + readableIssueIds.add(r.id); + } + } + + return { batchChannelAccess, readableIssueIds }; +} + +export async function filterBoardEventsBatchForSubscriber( + db: Db, + companyId: string, + actor: HeadlessActorContext, + events: BoardEventView[], + parsed: ParsedBoardEventFilters, + authActor?: AuthorizationActor, + channelCache?: Map, + lookaheadEvents?: BoardEventView[], +): Promise { + if (events.length === 0) return []; + const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor); + const { batchChannelAccess, readableIssueIds } = await prepareBatchAccessMaps( + db, + companyId, + actor, + events, + parsed, + effectiveAuthActor, + channelCache, + ); + const batchFallbackCache: IssueLabelCache = new Map(); + + const matched: BoardEventView[] = []; + for (let i = 0; i < events.length; i += 1) { + const ev = events[i]!; + const historicalKv = + parsed.labelExprs.length > 0 && + ev.issueId && + extractIssuePayloadKvLabels(ev) === null + ? findHistoricalKvLabelsBeforeLaterChange( + events, + i, + ev.issueId, + lookaheadEvents, + ) + : undefined; + const ok = await eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsed, + batchChannelAccess, + batchFallbackCache, + readableIssueIds, + effectiveAuthActor, + historicalKv, + ); + if (ok) { + matched.push(ev); + } + } + return matched; +} + +export async function queryBoardEventsAfter( + db: Db, + companyId: string, + actor: HeadlessActorContext, + filtersOrParsed: BoardEventFilterInput | ParsedBoardEventFilters, + opts: { limit?: number; authActor?: AuthorizationActor } = {}, +): Promise { + enforceHeadlessScopes(actor, { action: "events.read" }); + const parsed = + "afterSeq" in filtersOrParsed + ? filtersOrParsed + : parseBoardEventFilters(filtersOrParsed); + const limit = Math.min(Math.max(1, opts.limit ?? 100), 500); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + const channelCache = new Map(); + + const results: BoardEventView[] = []; + let cursorSeq = parsed.afterSeq; + const batchSize = 200; + + while (results.length < limit) { + const conditions = [ + eq(boardEvents.companyId, companyId), + gt(boardEvents.seq, cursorSeq), + ]; + if (parsed.eventTypes && parsed.eventTypes.size > 0) { + const sqlEventTypes: BoardEventType[] = + parsed.labelExprs.length > 0 && !parsed.eventTypes.has("labels.changed") + ? [...parsed.eventTypes, "labels.changed"] + : Array.from(parsed.eventTypes); + conditions.push(inArray(boardEvents.eventType, sqlEventTypes)); + } + if (parsed.issueUuid) { + conditions.push(eq(boardEvents.issueId, parsed.issueUuid)); + } + + const rows = await db + .select() + .from(boardEvents) + .where(and(...conditions)) + .orderBy(asc(boardEvents.seq)) + .limit(batchSize); + + if (rows.length === 0) break; + + const batchEvents = rows.map(serializeBoardEventRow); + cursorSeq = Math.max(cursorSeq, batchEvents[batchEvents.length - 1]!.seq); + + const matchedBatch = await filterBoardEventsBatchForSubscriber( + db, + companyId, + actor, + batchEvents, + parsed, + effectiveAuthActor, + channelCache, + ); + for (const ev of matchedBatch) { + results.push(ev); + if (results.length >= limit) break; + } + + if (rows.length < batchSize) break; + } + + return results; +} + +export async function waitForBoardEvent( + db: Db, + companyId: string, + actor: HeadlessActorContext, + filters: BoardEventFilterInput, + opts: { + timeoutMs?: number; + signal?: AbortSignal; + authActor?: AuthorizationActor; + onResolvedCursor?: (cursor: string) => void; + } = {}, +): Promise { + enforceHeadlessScopes(actor, { action: "events.read" }); + const parsed = parseBoardEventFilters(filters); + const timeoutMs = Math.min(Math.max(0, opts.timeoutMs ?? 30_000), 120_000); + const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); + const channelCache = new Map(); + + const buffered: BoardEventView[] = []; + let checkingInitial = true; + let resolveWaiter: ((ev: BoardEventView | null) => void) | null = null; + + const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { + if (checkingInitial) { + buffered.push(ev); + return; + } + if (ev.seq <= parsed.afterSeq) return; + void eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsed, + channelCache, + undefined, + undefined, + effectiveAuthActor, + ) + .then((ok) => { + if (ok && resolveWaiter) { + const resolveFn = resolveWaiter; + resolveWaiter = null; + resolveFn(ev); + } + }) + .catch(() => {}); + }); + + try { + if (parsed.hasExplicitAfter) { + opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq)); + const existing = await queryBoardEventsAfter(db, companyId, actor, parsed, { + limit: 1, + authActor: effectiveAuthActor, + }); + if (existing.length > 0) { + return existing[0]!; + } + } else { + parsed.afterSeq = await getCurrentCompanyMaxEventSeq(db, companyId); + opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq)); + } + + while (buffered.length > 0) { + const ev = buffered.shift()!; + if ( + await eventMatchesFiltersAndAccess( + db, + companyId, + actor, + ev, + parsed, + channelCache, + undefined, + undefined, + effectiveAuthActor, + ) + ) { + return ev; + } + } + + if (timeoutMs <= 0 || opts.signal?.aborted) { + return null; + } + + return await new Promise((resolve) => { + let settled = false; + const finish = (result: BoardEventView | null) => { + if (settled) return; + settled = true; + clearTimeout(timer); + opts.signal?.removeEventListener("abort", onAbort); + resolveWaiter = null; + resolve(result); + }; + const onAbort = () => finish(null); + resolveWaiter = finish; + checkingInitial = false; + const timer = setTimeout(() => finish(null), timeoutMs); + opts.signal?.addEventListener("abort", onAbort, { once: true }); + }); + } finally { + unsubscribe(); + } +} diff --git a/server/src/services/headless-channels.ts b/server/src/services/headless-channels.ts index 44ce1e32e6a..803efff2658 100644 --- a/server/src/services/headless-channels.ts +++ b/server/src/services/headless-channels.ts @@ -26,6 +26,7 @@ import { issueLabels, issues, labels, + primeDatabaseWorkTransactionId, projects, } from "@paperclipai/db"; import { @@ -58,6 +59,7 @@ import { } from "@paperclipai/shared"; import { badRequest, conflict, forbidden, notFound } from "../errors.js"; import { + createActivityDetailsRedactor, logActivity, publishActivity, type ActivityPublication, @@ -67,6 +69,7 @@ import { appendBoardEvent, assertChannelAccess, assertProjectReadAccess, + buildNextIssueCounterSql, buildSqlIssueLabelFilterCondition, canAccessChannel, channelDescendantsCondition, @@ -79,6 +82,7 @@ import { resolveIssueByIdOrIdentifier, resolveProjectReference, serializeCommentView, + serializeCreatedHeadlessIssueView, type DbOrTx, type HeadlessActorContext, } from "./headless-common.js"; @@ -223,16 +227,15 @@ export async function resolveAssigneeAgent( return null; } -export async function attachTagLabels( +export async function ensureCompanyTagLabels( tx: DbOrTx, companyId: string, - issueId: string, tagNames: string[], -): Promise { +): Promise> { const uniqueNames = Array.from( new Set(tagNames.map((t) => t.trim()).filter((t) => t.length > 0)), - ); - if (uniqueNames.length === 0) return; + ).sort(); + if (uniqueNames.length === 0) return []; await tx .insert(labels) @@ -247,12 +250,20 @@ export async function attachTagLabels( target: [labels.companyId, labels.name], }); - const labelRows = await tx - .select({ id: labels.id }) + return tx + .select({ id: labels.id, name: labels.name }) .from(labels) .where(and(eq(labels.companyId, companyId), inArray(labels.name, uniqueNames))); +} - if (labelRows.length === 0) return; +export async function attachTagLabels( + tx: DbOrTx, + companyId: string, + issueId: string, + tagNames: string[], +): Promise { + const labelRows = await ensureCompanyTagLabels(tx, companyId, tagNames); + if (labelRows.length === 0) return []; await tx .insert(issueLabels) @@ -266,6 +277,8 @@ export async function attachTagLabels( .onConflictDoNothing({ target: [issueLabels.issueId, issueLabels.labelId], }); + + return labelRows.map((l) => l.name); } async function addChannelCreatorMembership( @@ -380,7 +393,7 @@ export async function ensureChannel( input: EnsureChannelInput | CreateChannelInput, opts: { allowUpdateExisting?: boolean; publications?: ActivityPublication[] } = {}, ): Promise { - const { normalizedPath, hasPrivateAncestor } = + const { normalizedPath, existingChannel, hasPrivateAncestor } = await assertChannelPathWritePreconditions(dbOrTx, companyId, actor, input.path); const normalized = { path: normalizedPath }; @@ -427,14 +440,12 @@ export async function ensureChannel( visibility = "private"; } - const [preExisting] = await dbOrTx - .select({ id: channels.id }) - .from(channels) - .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) - .limit(1); + if (existingChannel && !opts.allowUpdateExisting) { + return existingChannel; + } - let inserted: typeof channels.$inferSelect | undefined; - if (!preExisting) { + let existing = existingChannel; + if (!existing) { if (validatedQueueConfig?.managedPool) { await assertCanConfigureManagedPool( dbOrTx, @@ -450,7 +461,7 @@ export async function ensureChannel( } const now = new Date(); - const [createdRow] = await dbOrTx + const [inserted] = await dbOrTx .insert(channels) .values({ companyId, @@ -470,55 +481,55 @@ export async function ensureChannel( target: [channels.companyId, channels.path], }) .returning(); - inserted = createdRow; - } - if (inserted) { - if (inserted.visibility === "private") { - await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor); - } - if (opts.publications) { - await logActivity( - dbOrTx as unknown as Db, - { - companyId, - actorType: actor.principalType === "agent" ? "agent" : "user", - actorId: - actor.principalType === "agent" - ? actor.agentId! - : (actor.userId ?? "local-board"), - agentId: actor.agentId, - responsibleUserIdOverride: actor.responsibleUserId, - action: "channel.created", - entityType: "channel", - entityId: inserted.id, - details: { - path: inserted.path, - visibility: inserted.visibility, + if (inserted) { + if (inserted.visibility === "private") { + await addChannelCreatorMembership(dbOrTx, companyId, inserted.id, actor); + } + if (opts.publications) { + await logActivity( + dbOrTx as unknown as Db, + { + companyId, + actorType: actor.principalType === "agent" ? "agent" : "user", + actorId: + actor.principalType === "agent" + ? actor.agentId! + : (actor.userId ?? "local-board"), + agentId: actor.agentId, + responsibleUserIdOverride: actor.responsibleUserId, + action: "channel.created", + entityType: "channel", + entityId: inserted.id, + details: { + path: inserted.path, + visibility: inserted.visibility, + }, }, - }, - opts.publications, - ); + opts.publications, + ); + } + return inserted; } - return inserted; - } - const [existing] = await dbOrTx - .select() - .from(channels) - .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) - .limit(1); + const [raced] = await dbOrTx + .select() + .from(channels) + .where(and(eq(channels.companyId, companyId), eq(channels.path, normalized.path))) + .limit(1); - if (!existing) { - throw notFound(`Channel '${normalized.path}' not found`); - } + if (!raced || raced.archivedAt !== null) { + throw notFound(`Channel '${normalized.path}' not found`); + } - if (existing.visibility === "private") { - await assertChannelAccess(dbOrTx, existing, actor); - } + if (raced.visibility === "private") { + await assertChannelAccess(dbOrTx, raced, actor); + } - if (!opts.allowUpdateExisting) { - return existing; + if (!opts.allowUpdateExisting) { + return raced; + } + existing = raced; } const updates: Partial = {}; @@ -912,7 +923,10 @@ export async function createChannelPost( data: input.schema.data, }); } - const validatedBlocks = await validateSchemaBlocks(db, companyId, combinedBlocks); + const validatedBlocks = + combinedBlocks.length > 0 + ? await validateSchemaBlocks(db, companyId, combinedBlocks) + : []; const resolvedResultSchemaRef = input.resultSchema ? await assertSchemaExists(db, companyId, input.resultSchema) @@ -1011,6 +1025,7 @@ export async function createChannelPost( } } + const activityRedactor = await createActivityDetailsRedactor(db); const publications: ActivityPublication[] = []; const committedEvents: BoardEventView[] = []; @@ -1020,7 +1035,11 @@ export async function createChannelPost( sql`select pg_advisory_xact_lock(hashtext(${companyId}), hashtext(${"post:" + originId}))`, ); const [existingInTx] = await tx - .select() + .select({ + id: issues.id, + channelId: issues.channelId, + originFingerprint: issues.originFingerprint, + }) .from(issues) .where( and( @@ -1056,9 +1075,15 @@ export async function createChannelPost( } } - const channel = await ensureChannel(tx, companyId, actor, { - path: normalizedChannel.path, - }); + const channel = await ensureChannel( + tx, + companyId, + actor, + { + path: normalizedChannel.path, + }, + { publications }, + ); const now = new Date(); let projectId: string | null = channel.defaultProjectId ?? null; @@ -1076,28 +1101,6 @@ export async function createChannelPost( for: input.for, }); - const [maxRow] = await tx - .select({ - maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, - }) - .from(issues) - .where(eq(issues.companyId, companyId)); - const currentMax = Number(maxRow?.maxNum ?? 0); - - const [companyRow] = await tx - .update(companies) - .set({ - issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + 1`, - updatedAt: now, - }) - .where(eq(companies.id, companyId)) - .returning({ - issueCounter: companies.issueCounter, - issuePrefix: companies.issuePrefix, - }); - - const issueNumber = companyRow!.issueCounter; - const identifier = `${companyRow!.issuePrefix}-${issueNumber}`; const scope: IssueScope = input.board ? "board" : "channel"; const priority: IssuePriority = input.priority ?? "medium"; let issueVisibility: "open" | "private" = @@ -1112,49 +1115,69 @@ export async function createChannelPost( issueVisibility = "private"; } } + + const nextCounterExpr = buildNextIssueCounterSql(companyId, 1); + + const [companyRow] = await tx + .update(companies) + .set({ + issueCounter: nextCounterExpr, + updatedAt: now, + }) + .where(eq(companies.id, companyId)) + .returning({ + issueCounter: companies.issueCounter, + issuePrefix: companies.issuePrefix, + xid: sql`pg_current_xact_id()::text`, + }); + + if (companyRow?.xid) { + primeDatabaseWorkTransactionId(tx, companyRow.xid); + } + + const issueNumber = companyRow!.issueCounter; + const identifier = `${companyRow!.issuePrefix}-${issueNumber}`; const newIssueId = randomUUID(); const privacyRootIssueId = issueVisibility === "private" ? newIssueId : null; - const [inserted] = await tx - .insert(issues) - .values({ - id: newIssueId, - companyId, - projectId, - channelId: channel.id, - visibility: issueVisibility, - privacyRootIssueId, - title: resolvedTitle, - description: resolvedDescription, - status: requestedStatus, - scope, - priority, - assigneeAgentId, - createdByAgentId: actor.agentId, - createdByUserId: actor.agentId ? null : actor.userId, - createdByProfile: actor.actorProfile, - responsibleUserId: actor.responsibleUserId, - kvLabels: mergedKvLabels, - schemaBlocks: validatedBlocks, - resultSchemaRef: resolvedResultSchemaRef, - issueNumber, - identifier, - originKind: "manual", - originId, - originFingerprint: requestHash ?? "default", - createdAt: now, - updatedAt: now, - }) - .returning(); + await tx.insert(issues).values({ + id: newIssueId, + companyId, + projectId, + channelId: channel.id, + visibility: issueVisibility, + privacyRootIssueId, + title: resolvedTitle, + description: resolvedDescription, + status: requestedStatus, + scope, + priority, + assigneeAgentId, + createdByAgentId: actor.agentId, + createdByUserId: actor.agentId ? null : actor.userId, + createdByProfile: actor.actorProfile, + responsibleUserId: actor.responsibleUserId, + kvLabels: mergedKvLabels, + schemaBlocks: validatedBlocks, + resultSchemaRef: resolvedResultSchemaRef, + issueNumber, + identifier, + originKind: "manual", + originId, + originFingerprint: requestHash ?? "default", + createdAt: now, + updatedAt: now, + }); await tx .update(channels) .set({ lastActivityAt: now, updatedAt: now }) .where(eq(channels.id, channel.id)); - if (input.tagLabels && input.tagLabels.length > 0) { - await attachTagLabels(tx, companyId, inserted!.id, input.tagLabels); - } + const attachedTagNames = + input.tagLabels && input.tagLabels.length > 0 + ? await attachTagLabels(tx, companyId, newIssueId, input.tagLabels) + : []; await logActivity( tx as unknown as Db, @@ -1166,12 +1189,12 @@ export async function createChannelPost( ? actor.agentId! : (actor.userId ?? "local-board"), agentId: actor.agentId, - issueId: inserted!.id, + issueId: newIssueId, responsibleUserIdOverride: actor.responsibleUserId, action: requestedStatus === "todo" ? "issue.created" : "channel.post_created", entityType: "issue", - entityId: inserted!.id, + entityId: newIssueId, details: { identifier, channel: channel.path, @@ -1180,6 +1203,7 @@ export async function createChannelPost( }, }, publications, + { redactor: activityRedactor }, ); const isReadyTask = requestedStatus === "todo" && assigneeAgentId === null; @@ -1188,7 +1212,7 @@ export async function createChannelPost( type: requestedStatus === "todo" ? "task.created" : "thread.posted", channelId: channel.id, channelPath: channel.path, - issueId: inserted!.id, + issueId: newIssueId, identifier, actor, payload: { @@ -1196,6 +1220,8 @@ export async function createChannelPost( ...(resolvedDescription ? { description: resolvedDescription.slice(0, 4000) } : {}), blocks: validatedBlocks, labels: mergedKvLabels, + kvLabels: mergedKvLabels, + tagLabels: attachedTagNames, ...(isReadyTask ? { ready: true } : {}), }, }); @@ -1208,16 +1234,42 @@ export async function createChannelPost( type: "task.ready", channelId: channel.id, channelPath: channel.path, - issueId: inserted!.id, + issueId: newIssueId, identifier, actor, - payload: {}, + payload: { + kvLabels: mergedKvLabels, + tagLabels: attachedTagNames, + }, }); committedEvents.push(readyEvent); lastCursor = readyEvent.cursor; } - const view = await loadHeadlessIssueView(tx, inserted!.id, lastCursor); + const view = serializeCreatedHeadlessIssueView({ + id: newIssueId, + companyId, + identifier, + title: resolvedTitle, + description: resolvedDescription, + status: requestedStatus, + scope, + priority, + channelId: channel.id, + channel: channel.path, + projectId, + assigneeAgentId, + assigneeUserId: null, + actorProfile: actor.actorProfile, + kvLabels: mergedKvLabels, + tagLabels: attachedTagNames, + blocks: validatedBlocks, + resultSchemaRef: resolvedResultSchemaRef, + blockedByIssueIds: [], + cursor: lastCursor, + createdAt: now, + updatedAt: now, + }); return { issue: view, created: true }; }); diff --git a/server/src/services/headless-common.ts b/server/src/services/headless-common.ts index 93d617bccee..c6fd37ecd52 100644 --- a/server/src/services/headless-common.ts +++ b/server/src/services/headless-common.ts @@ -439,7 +439,6 @@ export async function resolveHeadlessActor( ); } - // Check whether an active registered agent with this name or derived urlKey already exists. const profileLower = effectiveProfile.toLowerCase(); const companyAgents = await db .select({ @@ -907,35 +906,48 @@ export async function resolveProjectReference( return resolvedId; } -export async function resolveIssueByIdOrIdentifier( - dbOrTx: DbOrTx, +export function buildNextIssueCounterSql( + companyId: string, + count: number, +): SQL { + return sql`greatest(${companies.issueCounter}, coalesce((select max(${issues.issueNumber}) from ${issues} where ${issues.companyId} = ${companyId}), 0)) + ${count}`; +} + +async function queryIssueByIdOrIdentifier( idOrIdentifier: string, - expectedCompanyId?: string, -) { + expectedCompanyId: string | undefined, + runQuery: (whereClause: SQL | undefined) => Promise, +): Promise { const trimmed = idOrIdentifier.trim(); - let row; + let row: T | undefined; if (isUuidLike(trimmed)) { - [row] = await dbOrTx - .select() - .from(issues) - .where( - expectedCompanyId - ? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId)) - : eq(issues.id, trimmed), - ); + [row] = await runQuery( + expectedCompanyId + ? and(eq(issues.id, trimmed), eq(issues.companyId, expectedCompanyId)) + : eq(issues.id, trimmed), + ); } else { - const normalized = normalizeIssueIdentifier(trimmed) ?? trimmed.toUpperCase(); - [row] = await dbOrTx - .select() - .from(issues) - .where( + const normalizedUpper = ( + normalizeIssueIdentifier(trimmed) ?? trimmed + ).toUpperCase(); + [row] = await runQuery( + expectedCompanyId + ? and( + eq(issues.identifier, normalizedUpper), + eq(issues.companyId, expectedCompanyId), + ) + : eq(issues.identifier, normalizedUpper), + ); + if (!row) { + [row] = await runQuery( expectedCompanyId ? and( - sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`, + sql`upper(${issues.identifier}) = ${normalizedUpper}`, eq(issues.companyId, expectedCompanyId), ) - : sql`upper(${issues.identifier}) = ${normalized.toUpperCase()}`, + : sql`upper(${issues.identifier}) = ${normalizedUpper}`, ); + } } if (!row) { throw notFound(`Issue '${idOrIdentifier}' not found`); @@ -943,6 +955,53 @@ export async function resolveIssueByIdOrIdentifier( return row; } +export async function resolveIssueByIdOrIdentifier( + dbOrTx: DbOrTx, + idOrIdentifier: string, + expectedCompanyId?: string, +) { + return queryIssueByIdOrIdentifier( + idOrIdentifier, + expectedCompanyId, + (whereClause) => dbOrTx.select().from(issues).where(whereClause).limit(1), + ); +} + +const issueCommentTargetSelection = { + id: issues.id, + identifier: issues.identifier, + companyId: issues.companyId, + channelId: issues.channelId, + projectId: issues.projectId, + parentId: issues.parentId, + assigneeAgentId: issues.assigneeAgentId, + assigneeUserId: issues.assigneeUserId, + status: issues.status, + scope: issues.scope, + conversationAgentId: issues.conversationAgentId, +}; + +export async function resolveIssueCommentTarget( + dbOrTx: DbOrTx, + idOrIdentifier: string, + expectedCompanyId?: string, +) { + return queryIssueByIdOrIdentifier( + idOrIdentifier, + expectedCompanyId, + (whereClause) => + dbOrTx + .select(issueCommentTargetSelection) + .from(issues) + .where(whereClause) + .limit(1), + ); +} + +function isPlainObjectRecord(val: unknown): val is Record { + return Boolean(val) && typeof val === "object" && !Array.isArray(val); +} + export async function appendBoardEvent( dbOrTx: DbOrTx, input: { @@ -982,36 +1041,89 @@ export async function appendBoardEvent( ? input.actor.agentName ?? null : null; const actorProfile = input.actor.actorProfile ?? null; + const payloadObj = input.payload ?? {}; + const payloadJson = JSON.stringify(payloadObj); + const issueIdVal = input.issueId ?? null; - await dbOrTx.execute( - sql`SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId}))`, - ); + const hasExplicitIssueKv = + isPlainObjectRecord(payloadObj.kvLabels) || + (input.type === "labels.changed" && isPlainObjectRecord(payloadObj.current)) || + ((input.type === "thread.posted" || + input.type === "task.created" || + input.type === "task.ready") && + isPlainObjectRecord(payloadObj.labels)); + const hasExplicitTagLabels = Array.isArray(payloadObj.tagLabels); - const [inserted] = await dbOrTx - .insert(boardEvents) - .values({ - companyId: input.companyId, - eventType: input.type, - channelId: input.channelId ?? null, - channelPath: input.channelPath ?? null, - issueId: input.issueId ?? null, - identifier: input.identifier ?? null, - actorType, - actorId, - actorName, - actorProfile, - payload: input.payload ?? {}, - }) - .returning(); + let payloadExpr: SQL = sql`${payloadJson}::jsonb`; + if (issueIdVal && (!hasExplicitIssueKv || !hasExplicitTagLabels)) { + const kvSelectSql = sql`coalesce((select ${issues.kvLabels} from ${issues} where ${issues.id} = ${issueIdVal}::uuid and ${issues.companyId} = ${input.companyId}::uuid), '{}'::jsonb)`; + const tagSelectSql = sql`coalesce((select jsonb_agg(${labels.name} order by ${labels.name}) from ${issueLabels} inner join ${labels} on ${labels.id} = ${issueLabels.labelId} where ${issueLabels.issueId} = ${issueIdVal}::uuid and ${issueLabels.companyId} = ${input.companyId}::uuid), '[]'::jsonb)`; + if (!hasExplicitIssueKv && !hasExplicitTagLabels) { + payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}, 'tagLabels', ${tagSelectSql}))`; + } else if (!hasExplicitIssueKv) { + payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('kvLabels', ${kvSelectSql}))`; + } else { + payloadExpr = sql`(${payloadJson}::jsonb || jsonb_build_object('tagLabels', ${tagSelectSql}))`; + } + } + + const [inserted] = await dbOrTx.execute<{ + seq: string | number; + created_at: Date | string; + payload: Record | string; + }>(sql` + INSERT INTO ${boardEvents} ( + ${sql.raw(boardEvents.companyId.name)}, + ${sql.raw(boardEvents.eventType.name)}, + ${sql.raw(boardEvents.channelId.name)}, + ${sql.raw(boardEvents.channelPath.name)}, + ${sql.raw(boardEvents.issueId.name)}, + ${sql.raw(boardEvents.identifier.name)}, + ${sql.raw(boardEvents.actorType.name)}, + ${sql.raw(boardEvents.actorId.name)}, + ${sql.raw(boardEvents.actorName.name)}, + ${sql.raw(boardEvents.actorProfile.name)}, + ${sql.raw(boardEvents.payload.name)} + ) + SELECT + ${input.companyId}::uuid, + ${input.type}, + ${input.channelId ?? null}::uuid, + ${input.channelPath ?? null}, + ${issueIdVal}::uuid, + ${input.identifier ?? null}, + ${actorType}, + ${actorId}, + ${actorName}, + ${actorProfile}, + ${payloadExpr} + FROM ( + SELECT pg_advisory_xact_lock(hashtext('board_events'), hashtext(${input.companyId})) + ) AS _lock + RETURNING + ${sql.raw(boardEvents.seq.name)}, + ${sql.raw(boardEvents.createdAt.name)}, + ${sql.raw(boardEvents.payload.name)} + `); const seq = Number(inserted!.seq); + const createdAtIso = + inserted!.created_at instanceof Date + ? inserted!.created_at.toISOString() + : new Date(inserted!.created_at).toISOString(); + const persistedPayload: Record = + typeof inserted!.payload === "string" + ? (JSON.parse(inserted!.payload) as Record) + : isPlainObjectRecord(inserted!.payload) + ? inserted!.payload + : payloadObj; return { cursor: formatEventCursor(seq), seq, type: input.type, companyId: input.companyId, channel: input.channelPath ?? null, - issueId: input.issueId ?? null, + issueId: issueIdVal, identifier: input.identifier ?? null, actor: { type: actorType, @@ -1019,8 +1131,8 @@ export async function appendBoardEvent( name: actorName, profile: actorProfile, }, - payload: (inserted!.payload ?? {}) as Record, - createdAt: inserted!.createdAt.toISOString(), + payload: persistedPayload, + createdAt: createdAtIso, }; } @@ -1108,52 +1220,149 @@ export async function loadHeadlessIssueViews( return issueRows.map((row) => { const channelPath = row.channelId ? channelMap.get(row.channelId) ?? null : null; - const isPassivePost = - row.scope === "channel" && - row.status === "backlog" && - !row.assigneeAgentId && - !row.assigneeUserId; const issueSeq = seqMap.get(row.id); const cursor = explicitCursor ?? (issueSeq !== undefined ? formatEventCursor(issueSeq) : fallbackCursor); - return { - id: row.id, - companyId: row.companyId, - identifier: row.identifier ?? row.id, - title: row.title, - description: row.description ?? null, - status: row.status as IssueStatus, - scope: row.scope as IssueScope, - priority: row.priority as IssuePriority, - channelId: row.channelId ?? null, - channel: channelPath, - projectId: row.projectId ?? null, - assigneeAgentId: row.assigneeAgentId ?? null, - assigneeUserId: row.assigneeUserId ?? null, - actorProfile: row.createdByProfile ?? null, - kvLabels: (row.kvLabels ?? {}) as Record, + return mapHeadlessIssueRowToView(row, { + channelPath, tagLabels: tagMap.get(row.id) ?? [], - blocks: (row.schemaBlocks ?? []) as SchemaBlock[], - resultSchemaRef: row.resultSchemaRef ?? null, blockedByIssueIds: blockerMap.get(row.id) ?? [], - isPassivePost, - claimEpoch: Number(row.claimEpoch ?? 0), - claimHolderProfile: row.claimHolderProfile ?? null, - claimHolderAgentId: row.claimHolderAgentId ?? null, - claimHolderUserId: row.claimHolderUserId ?? null, - claimLeaseExpiresAt: row.claimLeaseExpiresAt - ? row.claimLeaseExpiresAt.toISOString() - : null, - claimAttemptCount: row.claimAttemptCount ?? 0, cursor, - createdAt: row.createdAt.toISOString(), - updatedAt: row.updatedAt.toISOString(), - }; + }); }); } +function mapHeadlessIssueRowToView( + row: { + id: string; + companyId: string; + identifier: string | null; + title: string; + description: string | null; + status: string; + scope: string; + priority: string; + channelId: string | null; + projectId: string | null; + assigneeAgentId: string | null; + assigneeUserId: string | null; + createdByProfile: string | null; + kvLabels: Record | null; + schemaBlocks: SchemaBlock[] | null; + resultSchemaRef: string | null; + claimEpoch?: number | null; + claimHolderProfile?: string | null; + claimHolderAgentId?: string | null; + claimHolderUserId?: string | null; + claimLeaseExpiresAt?: Date | null; + claimAttemptCount?: number | null; + createdAt: Date; + updatedAt: Date; + }, + extra: { + channelPath: string | null; + tagLabels: string[]; + blockedByIssueIds: string[]; + cursor: string; + }, +): HeadlessIssueView { + const isPassivePost = + row.scope === "channel" && + row.status === "backlog" && + !row.assigneeAgentId && + !row.assigneeUserId; + + return { + id: row.id, + companyId: row.companyId, + identifier: row.identifier ?? row.id, + title: row.title, + description: row.description ?? null, + status: row.status as IssueStatus, + scope: row.scope as IssueScope, + priority: row.priority as IssuePriority, + channelId: row.channelId ?? null, + channel: extra.channelPath, + projectId: row.projectId ?? null, + assigneeAgentId: row.assigneeAgentId ?? null, + assigneeUserId: row.assigneeUserId ?? null, + actorProfile: row.createdByProfile ?? null, + kvLabels: (row.kvLabels ?? {}) as Record, + tagLabels: extra.tagLabels, + blocks: (row.schemaBlocks ?? []) as SchemaBlock[], + resultSchemaRef: row.resultSchemaRef ?? null, + blockedByIssueIds: extra.blockedByIssueIds, + isPassivePost, + claimEpoch: Number(row.claimEpoch ?? 0), + claimHolderProfile: row.claimHolderProfile ?? null, + claimHolderAgentId: row.claimHolderAgentId ?? null, + claimHolderUserId: row.claimHolderUserId ?? null, + claimLeaseExpiresAt: row.claimLeaseExpiresAt + ? row.claimLeaseExpiresAt.toISOString() + : null, + claimAttemptCount: row.claimAttemptCount ?? 0, + cursor: extra.cursor, + createdAt: row.createdAt.toISOString(), + updatedAt: row.updatedAt.toISOString(), + }; +} + +export function serializeCreatedHeadlessIssueView(input: { + id: string; + companyId: string; + identifier: string; + title: string; + description: string | null; + status: IssueStatus; + scope: IssueScope; + priority: IssuePriority; + channelId: string | null; + channel: string | null; + projectId: string | null; + assigneeAgentId: string | null; + assigneeUserId: string | null; + actorProfile: string | null; + kvLabels: Record; + tagLabels: string[]; + blocks: SchemaBlock[]; + resultSchemaRef: string | null; + blockedByIssueIds: string[]; + cursor: string; + createdAt: Date; + updatedAt: Date; +}): HeadlessIssueView { + return mapHeadlessIssueRowToView( + { + id: input.id, + companyId: input.companyId, + identifier: input.identifier, + title: input.title, + description: input.description, + status: input.status, + scope: input.scope, + priority: input.priority, + channelId: input.channelId, + projectId: input.projectId, + assigneeAgentId: input.assigneeAgentId, + assigneeUserId: input.assigneeUserId, + createdByProfile: input.actorProfile, + kvLabels: input.kvLabels, + schemaBlocks: input.blocks, + resultSchemaRef: input.resultSchemaRef, + createdAt: input.createdAt, + updatedAt: input.updatedAt, + }, + { + channelPath: input.channel, + tagLabels: input.tagLabels, + blockedByIssueIds: input.blockedByIssueIds, + cursor: input.cursor, + }, + ); +} + export async function loadHeadlessIssueView( dbOrTx: DbOrTx, issueId: string, diff --git a/server/src/services/headless-events-schedules-interactions.ts b/server/src/services/headless-events-schedules-interactions.ts index 0e186bfcf8e..de374fa435b 100644 --- a/server/src/services/headless-events-schedules-interactions.ts +++ b/server/src/services/headless-events-schedules-interactions.ts @@ -1,46 +1,34 @@ import { randomUUID } from "node:crypto"; -import { and, asc, desc, eq, gt, inArray, isNull, ne, sql } from "drizzle-orm"; +import { and, asc, desc, eq, inArray, isNull, ne, sql } from "drizzle-orm"; import { z } from "zod"; import type { Db } from "@paperclipai/db"; import { activityLog, agents, - boardEvents, channels, companies, issueComments, - issueLabels, issues, issueThreadInteractions, - labels, projects, scheduledBoardPosts, } from "@paperclipai/db"; import { - boardEventTypeSchema, deriveAgentUrlKey, - formatEventCursor, isUuidLike, - matchesLabelFilter, normalizeChannelPath, - normalizeIssueIdentifier, OneLineAskSchema, OneLineConfirmSchema, parseDurationMs, - parseEventCursor, - parseLabelFilterExpr, - parseSchemaRef, ResolveInteractionInputSchema, SchedulePostSchema, splitMessageIntoTitleAndDescription, type AskUserQuestionsPayload, type AskUserQuestionsResult, - type BoardEventType, type BoardEventView, type InteractionView, type IssueThreadInteractionPayload, type IssueThreadInteractionResult, - type LabelFilterExpr, type RequestConfirmationPayload, type RequestConfirmationResult, type SchemaBlock, @@ -66,11 +54,22 @@ import { getLatestCompanyEventCursor, publishCommittedBoardEvent, resolveIssueByIdOrIdentifier, - subscribeCompanyBoardEvents, type DbOrTx, type HeadlessActorContext, } from "./headless-common.js"; import { extractClaimToken, verifyClaimToken } from "./headless-task-queue.js"; +export { + eventMatchesFiltersAndAccess, + filterBoardEventsBatchForSubscriber, + getCurrentCompanyMaxEventSeq, + parseBoardEventFilters, + queryBoardEventsAfter, + waitForBoardEvent, + type BoardEventFilterInput, + type IssueLabelCache, + type IssueLabelSnapshot, + type ParsedBoardEventFilters, +} from "./headless-board-event-stream.js"; const ISSUE_REF_RE = /^[A-Z][A-Z0-9]*-\d+$/i; @@ -81,32 +80,6 @@ function isIssueReferenceTarget(target: string): boolean { export { ResolveInteractionInputSchema }; -export interface BoardEventFilterInput { - channel?: string; - issueId?: string; - event?: BoardEventType[]; - label?: string[]; - mentions?: string; - schema?: string; - after?: string; -} - -export interface ParsedBoardEventFilters { - afterSeq: number; - hasExplicitAfter: boolean; - channelNorm: { path: string; isSubtreePrefix: boolean } | null; - issueUuid: string | null; - issueIdentifierUpper: string | null; - eventTypes: Set | null; - labelExprs: LabelFilterExpr[]; - mentionsName: string | null; - schemaFilter: { name: string; version: number | null } | null; -} - -function escapeRegExp(input: string): string { - return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} - function isChannelAllowedByScopes( actor: HeadlessActorContext, channelPath: string, @@ -1119,565 +1092,6 @@ export async function rejectOnIssue( return resolveInteractionOnIssue(db, issueId, actor, rawInput, "reject", opts); } -export function parseBoardEventFilters( - filters: BoardEventFilterInput, -): ParsedBoardEventFilters { - let afterSeq = 0; - let hasExplicitAfter = false; - if (filters.after !== undefined && filters.after.trim() !== "") { - const parsed = parseEventCursor(filters.after); - if (parsed === null) { - throw badRequest( - `Invalid cursor "${filters.after}": expected evt_`, - ); - } - afterSeq = parsed; - hasExplicitAfter = true; - } - - let channelNorm: { path: string; isSubtreePrefix: boolean } | null = null; - if (filters.channel && filters.channel.trim() !== "") { - try { - channelNorm = normalizeChannelPath(filters.channel, { - allowSubtreePrefix: true, - }); - } catch (err) { - throw badRequest(err instanceof Error ? err.message : "Invalid channel"); - } - } - - let issueUuid: string | null = null; - let issueIdentifierUpper: string | null = null; - if (filters.issueId && filters.issueId.trim() !== "") { - const trimmed = filters.issueId.trim(); - if (isUuidLike(trimmed)) { - issueUuid = trimmed.toLowerCase(); - } else { - issueIdentifierUpper = ( - normalizeIssueIdentifier(trimmed) ?? trimmed - ).toUpperCase(); - } - } - - let eventTypes: Set | null = null; - if (filters.event && filters.event.length > 0) { - eventTypes = new Set(); - for (const raw of filters.event) { - const parsed = boardEventTypeSchema.safeParse(raw); - if (!parsed.success) { - throw badRequest(`Invalid board event type "${raw}"`); - } - eventTypes.add(parsed.data); - } - } - - const labelExprs: LabelFilterExpr[] = []; - if (filters.label && filters.label.length > 0) { - for (const raw of filters.label) { - try { - labelExprs.push(parseLabelFilterExpr(raw)); - } catch (err) { - throw badRequest( - err instanceof Error ? err.message : "Invalid label filter", - ); - } - } - } - - let mentionsName: string | null = null; - if (filters.mentions && filters.mentions.trim() !== "") { - mentionsName = filters.mentions.trim().replace(/^@/, "").toLowerCase(); - } - - let schemaFilter: { name: string; version: number | null } | null = null; - if (filters.schema && filters.schema.trim() !== "") { - const rawSchema = filters.schema.trim(); - if (rawSchema.includes("@")) { - try { - const parsed = parseSchemaRef(rawSchema); - schemaFilter = { name: parsed.name, version: parsed.version }; - } catch (err) { - throw badRequest( - err instanceof Error ? err.message : "Invalid schema filter", - ); - } - } else { - schemaFilter = { name: rawSchema, version: null }; - } - } - - return { - afterSeq, - hasExplicitAfter, - channelNorm, - issueUuid, - issueIdentifierUpper, - eventTypes, - labelExprs, - mentionsName, - schemaFilter, - }; -} - -export async function getCurrentCompanyMaxEventSeq( - dbOrTx: DbOrTx, - companyId: string, -): Promise { - const cursor = await getLatestCompanyEventCursor(dbOrTx, companyId); - return parseEventCursor(cursor) ?? 0; -} - -function serializeBoardEventRow( - row: typeof boardEvents.$inferSelect, -): BoardEventView { - const seq = Number(row.seq); - return { - cursor: formatEventCursor(seq), - seq, - type: row.eventType, - companyId: row.companyId, - channel: row.channelPath ?? null, - issueId: row.issueId ?? null, - identifier: row.identifier ?? null, - actor: { - type: row.actorType, - id: row.actorId ?? null, - name: row.actorName ?? null, - profile: row.actorProfile ?? null, - }, - payload: (row.payload ?? {}) as Record, - createdAt: row.createdAt.toISOString(), - }; -} - -function matchesNonDbEventFilters( - ev: BoardEventView, - parsed: ParsedBoardEventFilters, -): boolean { - if (ev.seq <= parsed.afterSeq) return false; - - if (parsed.eventTypes && !parsed.eventTypes.has(ev.type)) { - return false; - } - - if (parsed.channelNorm) { - if (!ev.channel) return false; - if (parsed.channelNorm.isSubtreePrefix) { - if ( - ev.channel !== parsed.channelNorm.path && - !ev.channel.startsWith(`${parsed.channelNorm.path}/`) - ) { - return false; - } - } else if (ev.channel !== parsed.channelNorm.path) { - return false; - } - } - - if (parsed.issueUuid) { - if (!ev.issueId || ev.issueId.toLowerCase() !== parsed.issueUuid) { - return false; - } - } else if (parsed.issueIdentifierUpper) { - if ( - !ev.identifier || - ev.identifier.toUpperCase() !== parsed.issueIdentifierUpper - ) { - return false; - } - } - - if (parsed.mentionsName) { - const mentionRegex = new RegExp( - `(^|\\s)@${escapeRegExp(parsed.mentionsName)}(\\b|$)`, - "i", - ); - const candidateTexts = [ - ev.payload.text, - ev.payload.body, - ev.payload.title, - ev.payload.message, - ev.payload.description, - ].filter((v): v is string => typeof v === "string"); - if (!candidateTexts.some((txt) => mentionRegex.test(txt))) { - return false; - } - } - - if (parsed.schemaFilter) { - const blocks = Array.isArray(ev.payload.blocks) - ? (ev.payload.blocks as Array>) - : []; - const matched = blocks.some( - (b) => - b && - b.schema === parsed.schemaFilter!.name && - (parsed.schemaFilter!.version === null || - b.version === parsed.schemaFilter!.version), - ); - if (!matched) { - return false; - } - } - - return true; -} - -async function canActorAccessEventChannel( - db: Db, - companyId: string, - actor: HeadlessActorContext, - channelPath: string | null, - cache?: Map, -): Promise { - if (!channelPath) return true; - if (!isChannelAllowedByScopes(actor, channelPath)) return false; - - const cached = cache?.get(channelPath); - if (cached !== undefined) return cached; - - const [ch] = await db - .select({ - id: channels.id, - companyId: channels.companyId, - visibility: channels.visibility, - createdByUserId: channels.createdByUserId, - createdByAgentId: channels.createdByAgentId, - }) - .from(channels) - .where(and(eq(channels.companyId, companyId), eq(channels.path, channelPath))) - .limit(1); - - const allowed = ch ? await canAccessChannel(db, ch, actor) : true; - cache?.set(channelPath, allowed); - return allowed; -} - -async function eventMatchesLabelFilters( - db: Db, - ev: BoardEventView, - labelExprs: LabelFilterExpr[], - issueLabelCache: Map< - string, - { kvLabels: Record; tagLabels: string[] } - >, -): Promise { - if (ev.type === "labels.changed" && ev.issueId) { - issueLabelCache.delete(ev.issueId); - } - if (labelExprs.length === 0) return true; - - let kvLabels = - ev.payload.kvLabels && - typeof ev.payload.kvLabels === "object" && - !Array.isArray(ev.payload.kvLabels) - ? (ev.payload.kvLabels as Record) - : ev.payload.current && - typeof ev.payload.current === "object" && - !Array.isArray(ev.payload.current) - ? (ev.payload.current as Record) - : null; - let tagLabels = Array.isArray(ev.payload.tagLabels) - ? (ev.payload.tagLabels.filter((x): x is string => typeof x === "string")) - : undefined; - - if ( - !ev.payload.kvLabels && - !( - ev.payload.current && - typeof ev.payload.current === "object" && - !Array.isArray(ev.payload.current) - ) && - ev.issueId - ) { - // Re-check issue labels if not carried on payload - let cached = issueLabelCache.get(ev.issueId); - if (!cached) { - const [issueRow] = await db - .select({ kvLabels: issues.kvLabels }) - .from(issues) - .where(eq(issues.id, ev.issueId)) - .limit(1); - const tagRows = await db - .select({ name: labels.name }) - .from(issueLabels) - .innerJoin(labels, eq(issueLabels.labelId, labels.id)) - .where(eq(issueLabels.issueId, ev.issueId)); - cached = { - kvLabels: (issueRow?.kvLabels ?? {}) as Record, - tagLabels: tagRows.map((t) => t.name), - }; - issueLabelCache.set(ev.issueId, cached); - } - kvLabels = cached.kvLabels; - tagLabels = cached.tagLabels; - } - - const effectiveKv = kvLabels ?? {}; - return labelExprs.every((expr) => - matchesLabelFilter(effectiveKv, tagLabels, expr), - ); -} - -export async function eventMatchesFiltersAndAccess( - db: Db, - companyId: string, - actor: HeadlessActorContext, - ev: BoardEventView, - parsed: ParsedBoardEventFilters, - channelCache?: Map, - issueLabelCache = new Map< - string, - { kvLabels: Record; tagLabels: string[] } - >(), - readableIssueIds?: Set, - authActor?: AuthorizationActor, -): Promise { - if (ev.type === "labels.changed" && ev.issueId) { - issueLabelCache.delete(ev.issueId); - } - if (!matchesNonDbEventFilters(ev, parsed)) return false; - if (!(await canActorAccessEventChannel(db, companyId, actor, ev.channel, channelCache))) { - return false; - } - if (ev.issueId) { - if (readableIssueIds) { - if (!readableIssueIds.has(ev.issueId)) { - return false; - } - } else { - const effectiveAuthActor = authActor ?? buildAuthActorFromHeadless(actor); - const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); - const [readable] = await db - .select({ id: issues.id }) - .from(issues) - .where( - and( - eq(issues.companyId, companyId), - eq(issues.id, ev.issueId), - readCondition, - ), - ) - .limit(1); - if (!readable) { - return false; - } - } - } - if (!(await eventMatchesLabelFilters(db, ev, parsed.labelExprs, issueLabelCache))) { - return false; - } - return true; -} - -export async function queryBoardEventsAfter( - db: Db, - companyId: string, - actor: HeadlessActorContext, - filtersOrParsed: BoardEventFilterInput | ParsedBoardEventFilters, - opts: { limit?: number; authActor?: AuthorizationActor } = {}, -): Promise { - enforceHeadlessScopes(actor, { action: "events.read" }); - const parsed = - "afterSeq" in filtersOrParsed - ? filtersOrParsed - : parseBoardEventFilters(filtersOrParsed); - const limit = Math.min(Math.max(1, opts.limit ?? 100), 500); - const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); - const channelCache = new Map(); - const issueLabelCache = new Map< - string, - { kvLabels: Record; tagLabels: string[] } - >(); - - const results: BoardEventView[] = []; - let cursorSeq = parsed.afterSeq; - const batchSize = 200; - - while (results.length < limit) { - const conditions = [ - eq(boardEvents.companyId, companyId), - gt(boardEvents.seq, cursorSeq), - ]; - if (parsed.eventTypes && parsed.eventTypes.size > 0) { - conditions.push(inArray(boardEvents.eventType, Array.from(parsed.eventTypes))); - } - if (parsed.issueUuid) { - conditions.push(eq(boardEvents.issueId, parsed.issueUuid)); - } - - const rows = await db - .select() - .from(boardEvents) - .where(and(...conditions)) - .orderBy(asc(boardEvents.seq)) - .limit(batchSize); - - if (rows.length === 0) break; - - const batchIssueIds = Array.from( - new Set(rows.map((r) => r.issueId).filter((id): id is string => Boolean(id))), - ); - const readableIssueIds = new Set(); - if (batchIssueIds.length > 0) { - const readCondition = await issueReadSqlCondition(db, effectiveAuthActor); - const readableRows = await db - .select({ id: issues.id }) - .from(issues) - .where( - and( - eq(issues.companyId, companyId), - inArray(issues.id, batchIssueIds), - readCondition, - ), - ); - for (const r of readableRows) { - readableIssueIds.add(r.id); - } - } - - for (const row of rows) { - const ev = serializeBoardEventRow(row); - cursorSeq = Math.max(cursorSeq, ev.seq); - if ( - await eventMatchesFiltersAndAccess( - db, - companyId, - actor, - ev, - parsed, - channelCache, - issueLabelCache, - readableIssueIds, - effectiveAuthActor, - ) - ) { - results.push(ev); - if (results.length >= limit) break; - } - } - - if (rows.length < batchSize) break; - } - - return results; -} - -export async function waitForBoardEvent( - db: Db, - companyId: string, - actor: HeadlessActorContext, - filters: BoardEventFilterInput, - opts: { - timeoutMs?: number; - signal?: AbortSignal; - authActor?: AuthorizationActor; - onResolvedCursor?: (cursor: string) => void; - } = {}, -): Promise { - enforceHeadlessScopes(actor, { action: "events.read" }); - const parsed = parseBoardEventFilters(filters); - const timeoutMs = Math.min(Math.max(0, opts.timeoutMs ?? 30_000), 120_000); - const effectiveAuthActor = opts.authActor ?? buildAuthActorFromHeadless(actor); - const channelCache = new Map(); - const issueLabelCache = new Map< - string, - { kvLabels: Record; tagLabels: string[] } - >(); - - const buffered: BoardEventView[] = []; - let checkingInitial = true; - let resolveWaiter: ((ev: BoardEventView | null) => void) | null = null; - - const unsubscribe = subscribeCompanyBoardEvents(companyId, (ev) => { - if (checkingInitial) { - buffered.push(ev); - return; - } - if (ev.seq <= parsed.afterSeq) return; - void eventMatchesFiltersAndAccess( - db, - companyId, - actor, - ev, - parsed, - channelCache, - issueLabelCache, - undefined, - effectiveAuthActor, - ) - .then((ok) => { - if (ok && resolveWaiter) { - const resolveFn = resolveWaiter; - resolveWaiter = null; - resolveFn(ev); - } - }) - .catch(() => {}); - }); - - try { - if (parsed.hasExplicitAfter) { - opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq)); - const existing = await queryBoardEventsAfter(db, companyId, actor, parsed, { - limit: 1, - authActor: effectiveAuthActor, - }); - if (existing.length > 0) { - return existing[0]!; - } - } else { - parsed.afterSeq = await getCurrentCompanyMaxEventSeq(db, companyId); - opts.onResolvedCursor?.(formatEventCursor(parsed.afterSeq)); - } - - // Drain any events buffered during the initial query while keeping - // checkingInitial=true so newly arriving events keep buffering until we - // synchronously install resolveWaiter below (zero missed-event window). - while (buffered.length > 0) { - const ev = buffered.shift()!; - if ( - await eventMatchesFiltersAndAccess( - db, - companyId, - actor, - ev, - parsed, - channelCache, - issueLabelCache, - undefined, - effectiveAuthActor, - ) - ) { - return ev; - } - } - - if (timeoutMs <= 0 || opts.signal?.aborted) { - return null; - } - - return await new Promise((resolve) => { - let settled = false; - const finish = (result: BoardEventView | null) => { - if (settled) return; - settled = true; - clearTimeout(timer); - opts.signal?.removeEventListener("abort", onAbort); - resolveWaiter = null; - resolve(result); - }; - const onAbort = () => finish(null); - resolveWaiter = finish; - checkingInitial = false; - const timer = setTimeout(() => finish(null), timeoutMs); - opts.signal?.addEventListener("abort", onAbort, { once: true }); - }); - } finally { - unsubscribe(); - } -} - export async function createSchedule( db: Db, companyId: string, @@ -2294,6 +1708,7 @@ export function createScheduledBoardPostsWorker( title, body: row.message, kvLabels: row.kvLabels ?? {}, + tagLabels: [], blocks: row.schemaBlocks ?? [], scheduleId: row.id, }, @@ -2313,6 +1728,7 @@ export function createScheduledBoardPostsWorker( title, body: row.message, kvLabels: row.kvLabels ?? {}, + tagLabels: [], blocks: row.schemaBlocks ?? [], scheduleId: row.id, }, @@ -2329,6 +1745,7 @@ export function createScheduledBoardPostsWorker( actor: scheduleActor, payload: { kvLabels: row.kvLabels ?? {}, + tagLabels: [], scheduleId: row.id, }, }), diff --git a/server/src/services/headless-labels-batch.ts b/server/src/services/headless-labels-batch.ts index e8674bb3d8f..a1e587f6b36 100644 --- a/server/src/services/headless-labels-batch.ts +++ b/server/src/services/headless-labels-batch.ts @@ -7,6 +7,7 @@ import { issueBatchIdempotencyKeys, issueRelations, issues, + primeDatabaseWorkTransactionId, projects, } from "@paperclipai/db"; import { @@ -20,6 +21,7 @@ import { } from "@paperclipai/shared"; import { badRequest, conflict, unprocessable } from "../errors.js"; import { + createActivityDetailsRedactor, logActivity, publishActivity, type ActivityPublication, @@ -33,8 +35,8 @@ import { appendBoardEvent, assertIssueChannelScopeAccess, assertProjectReadAccess, + buildNextIssueCounterSql, enforceHeadlessScopes, - loadHeadlessIssueView, loadHeadlessIssueViews, publishCommittedBoardEvent, resolveIssueByIdOrIdentifier, @@ -241,6 +243,7 @@ export async function createBatchIssuesPlan( }); const requestHash = hashCanonicalRequest(rawInput); + const activityRedactor = await createActivityDetailsRedactor(db); const publications: ActivityPublication[] = []; const committedEvents: BoardEventView[] = []; @@ -344,44 +347,6 @@ export async function createBatchIssuesPlan( }); } - // Atomically allocate issue numbers for the batch - const now = new Date(); - const [maxRow] = await tx - .select({ - maxNum: sql`coalesce(max(${issues.issueNumber}), 0)`, - }) - .from(issues) - .where(eq(issues.companyId, companyId)); - const currentMax = Number(maxRow?.maxNum ?? 0); - - const [companyRow] = await tx - .update(companies) - .set({ - issueCounter: sql`greatest(${companies.issueCounter}, ${currentMax}) + ${plan.tasks.length}`, - updatedAt: now, - }) - .where(eq(companies.id, companyId)) - .returning({ - issueCounter: companies.issueCounter, - issuePrefix: companies.issuePrefix, - }); - - const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1; - - const createdByKey = new Map(); - const createdRows: Array = []; - const pendingEvents: Array<{ - issueId: string; - identifier: string; - key: string | null; - type: "task.created" | "task.ready"; - payload: Record; - isTaskCreated?: boolean; - }> = []; - const cursorByIssueId = new Map(); - const keyByIssueId = new Map(); - - // Pre-fetch private project visibility for all referenced projects const referencedProjectIds = Array.from( new Set( resolvedTaskConfigs @@ -405,6 +370,44 @@ export async function createBatchIssuesPlan( } } + const now = new Date(); + const nextBatchCounterExpr = buildNextIssueCounterSql( + companyId, + plan.tasks.length, + ); + + const [companyRow] = await tx + .update(companies) + .set({ + issueCounter: nextBatchCounterExpr, + updatedAt: now, + }) + .where(eq(companies.id, companyId)) + .returning({ + issueCounter: companies.issueCounter, + issuePrefix: companies.issuePrefix, + xid: sql`pg_current_xact_id()::text`, + }); + + if (companyRow?.xid) { + primeDatabaseWorkTransactionId(tx, companyRow.xid); + } + + const firstIssueNumber = companyRow!.issueCounter - plan.tasks.length + 1; + + const createdByKey = new Map(); + const createdRows: Array = []; + const pendingEvents: Array<{ + issueId: string; + identifier: string; + key: string | null; + type: "task.created" | "task.ready"; + payload: Record; + isTaskCreated?: boolean; + }> = []; + const cursorByIssueId = new Map(); + const keyByIssueId = new Map(); + for (let i = 0; i < plan.tasks.length; i += 1) { const task = plan.tasks[i]!; const cfg = resolvedTaskConfigs[i]!; @@ -462,9 +465,10 @@ export async function createBatchIssuesPlan( createdByKey.set(task.key, inserted!); } - if (task.tagLabels.length > 0) { - await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels); - } + const attachedTagNames = + task.tagLabels.length > 0 + ? await attachTagLabels(tx, companyId, inserted!.id, task.tagLabels) + : []; const blockerIds: string[] = []; let hasOpenBlocker = false; @@ -530,6 +534,7 @@ export async function createBatchIssuesPlan( }, }, publications, + { redactor: activityRedactor }, ); pendingEvents.push({ @@ -542,6 +547,9 @@ export async function createBatchIssuesPlan( key: task.key, title: task.title, ...(description ? { description: description.slice(0, 4000) } : {}), + labels: task.labels, + kvLabels: task.labels, + tagLabels: attachedTagNames, blockedByIssueIds: blockerIds, }, }); @@ -552,7 +560,11 @@ export async function createBatchIssuesPlan( identifier, key: task.key ?? null, type: "task.ready", - payload: { key: task.key }, + payload: { + key: task.key, + kvLabels: task.labels, + tagLabels: attachedTagNames, + }, }); } }