⚡ Project management that doesn't become the project. Boards, Gantt charts, and GitHub integration. Self-host it or use Kaneo Cloud.
TypeScript honoissue-managementissue-trackerjira-alternativekanbanlinear-alternativemcpproject-managementreactself-hostedtypescript
feat: add external link and integration tables with relations
Andrej Acevskid8d6f4c8bf38
diff --git a/apps/api/drizzle/0009_harsh_blacklash.sql b/apps/api/drizzle/0009_harsh_blacklash.sqlnew file mode 100644index 000000000..7d23a59ed--- /dev/null+++ b/apps/api/drizzle/0009_harsh_blacklash.sql@@ -0,0 +1,32 @@+CREATE TABLE "external_link" (+ "id" text PRIMARY KEY NOT NULL,+ "task_id" text NOT NULL,+ "integration_id" text NOT NULL,+ "resource_type" text NOT NULL,+ "external_id" text NOT NULL,+ "url" text NOT NULL,+ "title" text,+ "metadata" text,+ "created_at" timestamp DEFAULT now() NOT NULL,+ "updated_at" timestamp DEFAULT now() NOT NULL+);+--> statement-breakpoint+CREATE TABLE "integration" (+ "id" text PRIMARY KEY NOT NULL,+ "project_id" text NOT NULL,+ "type" text NOT NULL,+ "config" text NOT NULL,+ "is_active" boolean DEFAULT true,+ "created_at" timestamp DEFAULT now() NOT NULL,+ "updated_at" timestamp DEFAULT now() NOT NULL+);+--> statement-breakpoint+ALTER TABLE "external_link" ADD CONSTRAINT "external_link_task_id_task_id_fk" FOREIGN KEY ("task_id") REFERENCES "public"."task"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "external_link" ADD CONSTRAINT "external_link_integration_id_integration_id_fk" FOREIGN KEY ("integration_id") REFERENCES "public"."integration"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+ALTER TABLE "integration" ADD CONSTRAINT "integration_project_id_project_id_fk" FOREIGN KEY ("project_id") REFERENCES "public"."project"("id") ON DELETE cascade ON UPDATE cascade;--> statement-breakpoint+CREATE INDEX "external_link_taskId_idx" ON "external_link" USING btree ("task_id");--> statement-breakpoint+CREATE INDEX "external_link_integrationId_idx" ON "external_link" USING btree ("integration_id");--> statement-breakpoint+CREATE INDEX "external_link_externalId_idx" ON "external_link" USING btree ("external_id");--> statement-breakpoint+CREATE INDEX "external_link_resourceType_idx" ON "external_link" USING btree ("resource_type");--> statement-breakpoint+CREATE INDEX "integration_projectId_idx" ON "integration" USING btree ("project_id");--> statement-breakpoint+CREATE INDEX "integration_type_idx" ON "integration" USING btree ("type");\ No newline at end of filediff --git a/apps/api/drizzle/meta/0009_snapshot.json b/apps/api/drizzle/meta/0009_snapshot.jsonnew file mode 100644index 000000000..0bcbdcb92--- /dev/null+++ b/apps/api/drizzle/meta/0009_snapshot.json@@ -0,0 +1,1806 @@+{+ "id": "4cfeef35-e58e-4076-bbe7-9b7c9396c32f",+ "prevId": "e1f2cb4b-1889-4d18-acc6-7909b3a97579",+ "version": "7",+ "dialect": "postgresql",+ "tables": {+ "public.account": {+ "name": "account",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "account_id": {+ "name": "account_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "access_token": {+ "name": "access_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token": {+ "name": "refresh_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "id_token": {+ "name": "id_token",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "access_token_expires_at": {+ "name": "access_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "refresh_token_expires_at": {+ "name": "refresh_token_expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "scope": {+ "name": "scope",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "password": {+ "name": "password",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "account_userId_idx": {+ "name": "account_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "account_user_id_user_id_fk": {+ "name": "account_user_id_user_id_fk",+ "tableFrom": "account",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.activity": {+ "name": "activity",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "activity_task_id_task_id_fk": {+ "name": "activity_task_id_task_id_fk",+ "tableFrom": "activity",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "activity_user_id_user_id_fk": {+ "name": "activity_user_id_user_id_fk",+ "tableFrom": "activity",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.apikey": {+ "name": "apikey",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start": {+ "name": "start",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "prefix": {+ "name": "prefix",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "refill_interval": {+ "name": "refill_interval",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "refill_amount": {+ "name": "refill_amount",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_refill_at": {+ "name": "last_refill_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "enabled": {+ "name": "enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_enabled": {+ "name": "rate_limit_enabled",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "rate_limit_time_window": {+ "name": "rate_limit_time_window",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 86400000+ },+ "rate_limit_max": {+ "name": "rate_limit_max",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 10+ },+ "request_count": {+ "name": "request_count",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "remaining": {+ "name": "remaining",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "last_request": {+ "name": "last_request",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "permissions": {+ "name": "permissions",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "apikey_key_idx": {+ "name": "apikey_key_idx",+ "columns": [+ {+ "expression": "key",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "apikey_userId_idx": {+ "name": "apikey_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "apikey_user_id_user_id_fk": {+ "name": "apikey_user_id_user_id_fk",+ "tableFrom": "apikey",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.external_link": {+ "name": "external_link",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "integration_id": {+ "name": "integration_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "external_id": {+ "name": "external_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "url": {+ "name": "url",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "external_link_taskId_idx": {+ "name": "external_link_taskId_idx",+ "columns": [+ {+ "expression": "task_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_integrationId_idx": {+ "name": "external_link_integrationId_idx",+ "columns": [+ {+ "expression": "integration_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_externalId_idx": {+ "name": "external_link_externalId_idx",+ "columns": [+ {+ "expression": "external_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "external_link_resourceType_idx": {+ "name": "external_link_resourceType_idx",+ "columns": [+ {+ "expression": "resource_type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "external_link_task_id_task_id_fk": {+ "name": "external_link_task_id_task_id_fk",+ "tableFrom": "external_link",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "external_link_integration_id_integration_id_fk": {+ "name": "external_link_integration_id_integration_id_fk",+ "tableFrom": "external_link",+ "tableTo": "integration",+ "columnsFrom": ["integration_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.github_integration": {+ "name": "github_integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_owner": {+ "name": "repository_owner",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "repository_name": {+ "name": "repository_name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "installation_id": {+ "name": "installation_id",+ "type": "integer",+ "primaryKey": false,+ "notNull": false+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "github_integration_project_id_project_id_fk": {+ "name": "github_integration_project_id_project_id_fk",+ "tableFrom": "github_integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "github_integration_project_id_unique": {+ "name": "github_integration_project_id_unique",+ "nullsNotDistinct": false,+ "columns": ["project_id"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.integration": {+ "name": "integration",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "is_active": {+ "name": "is_active",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "integration_projectId_idx": {+ "name": "integration_projectId_idx",+ "columns": [+ {+ "expression": "project_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "integration_type_idx": {+ "name": "integration_type_idx",+ "columns": [+ {+ "expression": "type",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "integration_project_id_project_id_fk": {+ "name": "integration_project_id_project_id_fk",+ "tableFrom": "integration",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.invitation": {+ "name": "invitation",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'pending'"+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "inviter_id": {+ "name": "inviter_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "invitation_workspaceId_idx": {+ "name": "invitation_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "invitation_email_idx": {+ "name": "invitation_email_idx",+ "columns": [+ {+ "expression": "email",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "invitation_workspace_id_workspace_id_fk": {+ "name": "invitation_workspace_id_workspace_id_fk",+ "tableFrom": "invitation",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "invitation_inviter_id_user_id_fk": {+ "name": "invitation_inviter_id_user_id_fk",+ "tableFrom": "invitation",+ "tableTo": "user",+ "columnsFrom": ["inviter_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.label": {+ "name": "label",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "color": {+ "name": "color",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "label_task_id_task_id_fk": {+ "name": "label_task_id_task_id_fk",+ "tableFrom": "label",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "label_workspace_id_workspace_id_fk": {+ "name": "label_workspace_id_workspace_id_fk",+ "tableFrom": "label",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.notification": {+ "name": "notification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "type": {+ "name": "type",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'info'"+ },+ "is_read": {+ "name": "is_read",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ },+ "resource_id": {+ "name": "resource_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "resource_type": {+ "name": "resource_type",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp with time zone",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "notification_user_id_user_id_fk": {+ "name": "notification_user_id_user_id_fk",+ "tableFrom": "notification",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.project": {+ "name": "project",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "icon": {+ "name": "icon",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'Layout'"+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_public": {+ "name": "is_public",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {+ "project_workspace_id_workspace_id_fk": {+ "name": "project_workspace_id_workspace_id_fk",+ "tableFrom": "project",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.session": {+ "name": "session",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "token": {+ "name": "token",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "ip_address": {+ "name": "ip_address",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_agent": {+ "name": "user_agent",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "active_organization_id": {+ "name": "active_organization_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "active_team_id": {+ "name": "active_team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "session_userId_idx": {+ "name": "session_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "session_user_id_user_id_fk": {+ "name": "session_user_id_user_id_fk",+ "tableFrom": "session",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "session_token_unique": {+ "name": "session_token_unique",+ "nullsNotDistinct": false,+ "columns": ["token"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.task": {+ "name": "task",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "project_id": {+ "name": "project_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "position": {+ "name": "position",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "number": {+ "name": "number",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 1+ },+ "assignee_id": {+ "name": "assignee_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'to-do'"+ },+ "priority": {+ "name": "priority",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "default": "'low'"+ },+ "due_date": {+ "name": "due_date",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "task_project_id_project_id_fk": {+ "name": "task_project_id_project_id_fk",+ "tableFrom": "task",+ "tableTo": "project",+ "columnsFrom": ["project_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "task_assignee_id_user_id_fk": {+ "name": "task_assignee_id_user_id_fk",+ "tableFrom": "task",+ "tableTo": "user",+ "columnsFrom": ["assignee_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team_member": {+ "name": "team_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "team_id": {+ "name": "team_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "teamMember_teamId_idx": {+ "name": "teamMember_teamId_idx",+ "columns": [+ {+ "expression": "team_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "teamMember_userId_idx": {+ "name": "teamMember_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_member_team_id_team_id_fk": {+ "name": "team_member_team_id_team_id_fk",+ "tableFrom": "team_member",+ "tableTo": "team",+ "columnsFrom": ["team_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "team_member_user_id_user_id_fk": {+ "name": "team_member_user_id_user_id_fk",+ "tableFrom": "team_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.team": {+ "name": "team",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ }+ },+ "indexes": {+ "team_workspaceId_idx": {+ "name": "team_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "team_workspace_id_workspace_id_fk": {+ "name": "team_workspace_id_workspace_id_fk",+ "tableFrom": "team",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.time_entry": {+ "name": "time_entry",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "task_id": {+ "name": "task_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "start_time": {+ "name": "start_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "end_time": {+ "name": "end_time",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": false+ },+ "duration": {+ "name": "duration",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "default": 0+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "time_entry_task_id_task_id_fk": {+ "name": "time_entry_task_id_task_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "task",+ "columnsFrom": ["task_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ },+ "time_entry_user_id_user_id_fk": {+ "name": "time_entry_user_id_user_id_fk",+ "tableFrom": "time_entry",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.user": {+ "name": "user",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email": {+ "name": "email",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "email_verified": {+ "name": "email_verified",+ "type": "boolean",+ "primaryKey": false,+ "notNull": true+ },+ "image": {+ "name": "image",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "is_anonymous": {+ "name": "is_anonymous",+ "type": "boolean",+ "primaryKey": false,+ "notNull": false,+ "default": false+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "user_email_unique": {+ "name": "user_email_unique",+ "nullsNotDistinct": false,+ "columns": ["email"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.verification": {+ "name": "verification",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "identifier": {+ "name": "identifier",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "expires_at": {+ "name": "expires_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true,+ "default": "now()"+ }+ },+ "indexes": {+ "verification_identifier_idx": {+ "name": "verification_identifier_idx",+ "columns": [+ {+ "expression": "identifier",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace": {+ "name": "workspace",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "slug": {+ "name": "slug",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "logo": {+ "name": "logo",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "description": {+ "name": "description",+ "type": "text",+ "primaryKey": false,+ "notNull": false+ },+ "created_at": {+ "name": "created_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {+ "workspace_slug_unique": {+ "name": "workspace_slug_unique",+ "nullsNotDistinct": false,+ "columns": ["slug"]+ }+ },+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ },+ "public.workspace_member": {+ "name": "workspace_member",+ "schema": "",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true+ },+ "workspace_id": {+ "name": "workspace_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "user_id": {+ "name": "user_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true+ },+ "role": {+ "name": "role",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "default": "'member'"+ },+ "joined_at": {+ "name": "joined_at",+ "type": "timestamp",+ "primaryKey": false,+ "notNull": true+ }+ },+ "indexes": {+ "workspace_member_workspaceId_idx": {+ "name": "workspace_member_workspaceId_idx",+ "columns": [+ {+ "expression": "workspace_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ },+ "workspace_member_userId_idx": {+ "name": "workspace_member_userId_idx",+ "columns": [+ {+ "expression": "user_id",+ "isExpression": false,+ "asc": true,+ "nulls": "last"+ }+ ],+ "isUnique": false,+ "concurrently": false,+ "method": "btree",+ "with": {}+ }+ },+ "foreignKeys": {+ "workspace_member_workspace_id_workspace_id_fk": {+ "name": "workspace_member_workspace_id_workspace_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "workspace",+ "columnsFrom": ["workspace_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ },+ "workspace_member_user_id_user_id_fk": {+ "name": "workspace_member_user_id_user_id_fk",+ "tableFrom": "workspace_member",+ "tableTo": "user",+ "columnsFrom": ["user_id"],+ "columnsTo": ["id"],+ "onDelete": "cascade",+ "onUpdate": "no action"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "policies": {},+ "checkConstraints": {},+ "isRLSEnabled": false+ }+ },+ "enums": {},+ "schemas": {},+ "sequences": {},+ "roles": {},+ "policies": {},+ "views": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ }+}diff --git a/apps/api/drizzle/meta/_journal.json b/apps/api/drizzle/meta/_journal.jsonindex 8ea815720..db4fb0727 100644--- a/apps/api/drizzle/meta/_journal.json+++ b/apps/api/drizzle/meta/_journal.json@@ -64,6 +64,13 @@"when": 1765392072530,"tag": "0008_square_silvermane","breakpoints": true+ },+ {+ "idx": 9,+ "version": "7",+ "when": 1766950050412,+ "tag": "0009_harsh_blacklash",+ "breakpoints": true}]}diff --git a/apps/api/src/database/index.ts b/apps/api/src/database/index.tsindex 7a6fe24f0..63d5b72cd 100644--- a/apps/api/src/database/index.ts+++ b/apps/api/src/database/index.ts@@ -5,7 +5,9 @@ import {accountTableRelations,activityTableRelations,apikeyTableRelations,+ externalLinkTableRelations,githubIntegrationTableRelations,+ integrationTableRelations,invitationTableRelations,labelTableRelations,notificationTableRelations,@@ -24,7 +26,9 @@ import {accountTable,activityTable,apikeyTable,+ externalLinkTable,githubIntegrationTable,+ integrationTable,invitationTable,labelTable,notificationTable,@@ -51,38 +55,42 @@ const pool = new Pool({export const schema = {accountTable,activityTable,+ apikeyTable,+ externalLinkTable,githubIntegrationTable,+ integrationTable,+ invitationTable,labelTable,notificationTable,projectTable,sessionTable,taskTable,+ teamMemberTable,+ teamTable,timeEntryTable,userTable,verificationTable,workspaceTable,workspaceUserTable,- invitationTable,- teamTable,- teamMemberTable,- userTableRelations,- sessionTableRelations,accountTableRelations,- verificationTableRelations,- workspaceTableRelations,- workspaceUserTableRelations,- teamTableRelations,- teamMemberTableRelations,- projectTableRelations,- taskTableRelations,- timeEntryTableRelations,activityTableRelations,- labelTableRelations,- notificationTableRelations,+ apikeyTableRelations,+ externalLinkTableRelations,githubIntegrationTableRelations,+ integrationTableRelations,invitationTableRelations,- apikeyTable,- apikeyTableRelations,+ labelTableRelations,+ notificationTableRelations,+ projectTableRelations,+ sessionTableRelations,+ taskTableRelations,+ teamMemberTableRelations,+ teamTableRelations,+ timeEntryTableRelations,+ userTableRelations,+ verificationTableRelations,+ workspaceTableRelations,+ workspaceUserTableRelations,};const db = drizzle(pool, {diff --git a/apps/api/src/database/relations.ts b/apps/api/src/database/relations.tsindex fc09b185d..c1f8bd15e 100644--- a/apps/api/src/database/relations.ts+++ b/apps/api/src/database/relations.ts@@ -3,7 +3,9 @@ import {accountTable,activityTable,apikeyTable,+ externalLinkTable,githubIntegrationTable,+ integrationTable,invitationTable,labelTable,notificationTable,@@ -85,6 +87,7 @@ export const projectTableRelations = relations(}),tasks: many(taskTable),githubIntegration: many(githubIntegrationTable),+ integrations: many(integrationTable),}),);@@ -100,6 +103,7 @@ export const taskTableRelations = relations(taskTable, ({ one, many }) => ({timeEntries: many(timeEntryTable),activities: many(activityTable),labels: many(labelTable),+ externalLinks: many(externalLinkTable),}));export const timeEntryTableRelations = relations(timeEntryTable, ({ one }) => ({@@ -193,3 +197,28 @@ export const apikeyTableRelations = relations(apikeyTable, ({ one }) => ({references: [userTable.id],}),}));++export const integrationTableRelations = relations(+ integrationTable,+ ({ one, many }) => ({+ project: one(projectTable, {+ fields: [integrationTable.projectId],+ references: [projectTable.id],+ }),+ externalLinks: many(externalLinkTable),+ }),+);++export const externalLinkTableRelations = relations(+ externalLinkTable,+ ({ one }) => ({+ task: one(taskTable, {+ fields: [externalLinkTable.taskId],+ references: [taskTable.id],+ }),+ integration: one(integrationTable, {+ fields: [externalLinkTable.integrationId],+ references: [integrationTable.id],+ }),+ }),+);diff --git a/apps/api/src/database/schema.ts b/apps/api/src/database/schema.tsindex 32fc29957..2822f3e56 100644--- a/apps/api/src/database/schema.ts+++ b/apps/api/src/database/schema.ts@@ -332,6 +332,70 @@ export const githubIntegrationTable = pgTable("github_integration", {updatedAt: timestamp("updated_at", { mode: "date" }).defaultNow().notNull(),});+export const integrationTable = pgTable(+ "integration",+ {+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+ projectId: text("project_id")+ .notNull()+ .references(() => projectTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ type: text("type").notNull(),+ config: text("config").notNull(),+ isActive: boolean("is_active").default(true),+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .$onUpdate(() => new Date())+ .notNull(),+ },+ (table) => [+ index("integration_projectId_idx").on(table.projectId),+ index("integration_type_idx").on(table.type),+ ],+);++export const externalLinkTable = pgTable(+ "external_link",+ {+ id: text("id")+ .$defaultFn(() => createId())+ .primaryKey(),+ taskId: text("task_id")+ .notNull()+ .references(() => taskTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ integrationId: text("integration_id")+ .notNull()+ .references(() => integrationTable.id, {+ onDelete: "cascade",+ onUpdate: "cascade",+ }),+ resourceType: text("resource_type").notNull(),+ externalId: text("external_id").notNull(),+ url: text("url").notNull(),+ title: text("title"),+ metadata: text("metadata"),+ createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(),+ updatedAt: timestamp("updated_at", { mode: "date" })+ .defaultNow()+ .$onUpdate(() => new Date())+ .notNull(),+ },+ (table) => [+ index("external_link_taskId_idx").on(table.taskId),+ index("external_link_integrationId_idx").on(table.integrationId),+ index("external_link_externalId_idx").on(table.externalId),+ index("external_link_resourceType_idx").on(table.resourceType),+ ],+);+export const apikeyTable = pgTable("apikey",{diff --git a/apps/api/src/external-link/index.ts b/apps/api/src/external-link/index.tsnew file mode 100644index 000000000..fb4ec3555--- /dev/null+++ b/apps/api/src/external-link/index.ts@@ -0,0 +1,65 @@+import { eq } from "drizzle-orm";+import { Hono } from "hono";+import { describeRoute, resolver, validator } from "hono-openapi";+import * as v from "valibot";+import db from "../database";+import { externalLinkTable } from "../database/schema";+import { workspaceAccess } from "../utils/workspace-access-middleware";++const externalLinkSchema = v.object({+ id: v.string(),+ taskId: v.string(),+ integrationId: v.string(),+ resourceType: v.string(),+ externalId: v.string(),+ url: v.string(),+ title: v.nullable(v.string()),+ metadata: v.any(),+ createdAt: v.date(),+ updatedAt: v.date(),+});++const externalLink = new Hono<{+ Variables: {+ userId: string;+ workspaceId: string;+ };+}>().get(+ "/task/:taskId",+ describeRoute({+ operationId: "getExternalLinksByTask",+ tags: ["External Links"],+ description: "Get all external links for a task",+ responses: {+ 200: {+ description: "External links for the task",+ content: {+ "application/json": {+ schema: resolver(v.array(externalLinkSchema)),+ },+ },+ },+ },+ }),+ validator("param", v.object({ taskId: v.string() })),+ workspaceAccess.fromTaskId("taskId"),+ async (c) => {+ const { taskId } = c.req.valid("param");++ const links = await db.query.externalLinkTable.findMany({+ where: eq(externalLinkTable.taskId, taskId),+ with: {+ integration: true,+ },+ });++ const formattedLinks = links.map((link) => ({+ ...link,+ metadata: link.metadata ? JSON.parse(link.metadata) : null,+ }));++ return c.json(formattedLinks);+ },+);++export default externalLink;diff --git a/apps/api/src/github-integration/controllers/create-github-integration.ts b/apps/api/src/github-integration/controllers/create-github-integration.tsindex b78d42ad2..10e66acd0 100644--- a/apps/api/src/github-integration/controllers/create-github-integration.ts+++ b/apps/api/src/github-integration/controllers/create-github-integration.ts@@ -1,10 +1,9 @@-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { githubIntegrationTable, projectTable } from "../../database/schema";-import createGithubApp from "../utils/create-github-app";--const githubApp = createGithubApp();+import { integrationTable, projectTable } from "../../database/schema";+import { defaultGitHubConfig } from "../../plugins/github/config";+import { getGithubApp } from "../../plugins/github/utils/github-app";async function createGithubIntegration({projectId,@@ -15,9 +14,11 @@ async function createGithubIntegration({repositoryOwner: string;repositoryName: string;}) {+ const githubApp = getGithubApp();+if (!githubApp) {throw new HTTPException(500, {- message: "GitHub app not found",+ message: "GitHub app not configured",});}@@ -41,38 +42,68 @@ async function createGithubIntegration({console.warn("Could not get installation ID for repository:", error);}- const existingIntegration = await db.query.githubIntegrationTable.findFirst({- where: eq(githubIntegrationTable.projectId, projectId),+ const existingIntegration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),});+ const config = {+ repositoryOwner,+ repositoryName,+ installationId,+ ...defaultGitHubConfig,+ };+if (existingIntegration) {const [updatedIntegration] = await db- .update(githubIntegrationTable)+ .update(integrationTable).set({- repositoryOwner,- repositoryName,- installationId,+ config: JSON.stringify(config),isActive: true,updatedAt: new Date(),})- .where(eq(githubIntegrationTable.projectId, projectId))+ .where(+ and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),+ ).returning();- return updatedIntegration;+ return {+ id: updatedIntegration?.id,+ projectId: updatedIntegration?.projectId,+ repositoryOwner,+ repositoryName,+ installationId,+ isActive: updatedIntegration?.isActive,+ createdAt: updatedIntegration?.createdAt,+ updatedAt: updatedIntegration?.updatedAt,+ };}const [newIntegration] = await db- .insert(githubIntegrationTable)+ .insert(integrationTable).values({projectId,- repositoryOwner,- repositoryName,- installationId,+ type: "github",+ config: JSON.stringify(config),isActive: true,}).returning();- return newIntegration;+ return {+ id: newIntegration?.id,+ projectId: newIntegration?.projectId,+ repositoryOwner,+ repositoryName,+ installationId,+ isActive: newIntegration?.isActive,+ createdAt: newIntegration?.createdAt,+ updatedAt: newIntegration?.updatedAt,+ };}export default createGithubIntegration;diff --git a/apps/api/src/github-integration/controllers/delete-github-integration.ts b/apps/api/src/github-integration/controllers/delete-github-integration.tsindex 81d84c268..a2fc1ab10 100644--- a/apps/api/src/github-integration/controllers/delete-github-integration.ts+++ b/apps/api/src/github-integration/controllers/delete-github-integration.ts@@ -1,11 +1,14 @@-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import { HTTPException } from "hono/http-exception";import db from "../../database";-import { githubIntegrationTable } from "../../database/schema";+import { integrationTable } from "../../database/schema";async function deleteGithubIntegration(projectId: string) {- const existingIntegration = await db.query.githubIntegrationTable.findFirst({- where: eq(githubIntegrationTable.projectId, projectId),+ const existingIntegration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),});if (!existingIntegration) {@@ -13,8 +16,13 @@ async function deleteGithubIntegration(projectId: string) {}await db- .delete(githubIntegrationTable)- .where(eq(githubIntegrationTable.projectId, projectId));+ .delete(integrationTable)+ .where(+ and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),+ );return { success: true, message: "GitHub integration deleted" };}diff --git a/apps/api/src/github-integration/controllers/get-github-integration.ts b/apps/api/src/github-integration/controllers/get-github-integration.tsindex 7f58b5967..404fd27d0 100644--- a/apps/api/src/github-integration/controllers/get-github-integration.ts+++ b/apps/api/src/github-integration/controllers/get-github-integration.ts@@ -1,17 +1,36 @@-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import db from "../../database";-import { githubIntegrationTable } from "../../database/schema";+import { integrationTable } from "../../database/schema";+import {+ defaultGitHubConfig,+ type GitHubConfig,+} from "../../plugins/github/config";async function getGithubIntegration(projectId: string) {- const integration = await db.query.githubIntegrationTable.findFirst({- where: eq(githubIntegrationTable.projectId, projectId),+ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),});if (!integration) {return null;}- return integration;+ const config = JSON.parse(integration.config) as GitHubConfig;++ return {+ id: integration.id,+ projectId: integration.projectId,+ repositoryOwner: config.repositoryOwner,+ repositoryName: config.repositoryName,+ installationId: config.installationId,+ branchPattern: config.branchPattern || defaultGitHubConfig.branchPattern,+ isActive: integration.isActive,+ createdAt: integration.createdAt,+ updatedAt: integration.updatedAt,+ };}export default getGithubIntegration;diff --git a/apps/api/src/github-integration/controllers/import-issues.ts b/apps/api/src/github-integration/controllers/import-issues.tsindex 1e6eb2da5..d328493f1 100644--- a/apps/api/src/github-integration/controllers/import-issues.ts+++ b/apps/api/src/github-integration/controllers/import-issues.ts@@ -1,64 +1,112 @@import { and, eq, notLike } from "drizzle-orm";import db from "../../database";-import { githubIntegrationTable, taskTable } from "../../database/schema";-import createGithubApp from "../utils/create-github-app";--const githubApp = createGithubApp();+import { integrationTable, taskTable } from "../../database/schema";+import { createExternalLink } from "../../plugins/github/services/link-manager";+import { getGithubApp } from "../../plugins/github/utils/github-app";export async function importIssues(projectId: string) {- const githubIntegration = await db.query.githubIntegrationTable.findFirst({- where: eq(githubIntegrationTable.projectId, projectId),+ const githubApp = getGithubApp();++ if (!githubApp) {+ return { error: "GitHub app not configured" };+ }++ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),});- if (!githubIntegration) {+ if (!integration) {return { error: "GitHub integration not found" };}- const installationOctokit = await githubApp?.getInstallationOctokit(- githubIntegration.installationId ?? 0,- );+ const config = JSON.parse(integration.config) as {+ repositoryOwner: string;+ repositoryName: string;+ installationId: number | null;+ };- if (!installationOctokit) {- return { error: "GitHub app not found" };+ if (!config.installationId) {+ return { error: "GitHub installation not found" };}+ const installationOctokit = await githubApp.getInstallationOctokit(+ config.installationId,+ );+const { data: issues } = await installationOctokit.rest.issues.listForRepo({- owner: githubIntegration.repositoryOwner,- repo: githubIntegration.repositoryName,+ owner: config.repositoryOwner,+ repo: config.repositoryName,+ state: "all",+ per_page: 100,});+ let imported = 0;+ let skipped = 0;+for (const issue of issues ?? []) {- const task = await db.query.taskTable.findFirst({+ if (issue.pull_request) {+ skipped++;+ continue;+ }++ const existingTask = await db.query.taskTable.findFirst({where: and(- eq(taskTable.number, issue.number),eq(taskTable.projectId, projectId),notLike(taskTable.title, "[Kaneo]%"),),});- if (task) {+ const hasExistingLink = existingTask+ ? await db.query.externalLinkTable.findFirst({+ where: and(+ eq(db._.fullSchema.externalLinkTable.taskId, existingTask.id),+ eq(+ db._.fullSchema.externalLinkTable.externalId,+ issue.number.toString(),+ ),+ ),+ })+ : null;++ if (hasExistingLink) {+ skipped++;continue;}- const githubIssueUrl = `https://github.com/${githubIntegration.repositoryOwner}/${githubIntegration.repositoryName}/issues/${issue.number}`;- let description = issue.body || "";- if (description) {- description += `\n\nLinked to GitHub issue: ${githubIssueUrl}`;- } else {- description = `Linked to GitHub issue: ${githubIssueUrl}`;- }+ const [newTask] = await db+ .insert(taskTable)+ .values({+ title: issue.title,+ description: issue.body || null,+ projectId,+ number: issue.number,+ status: issue.state === "closed" ? "done" : "to-do",+ priority: "medium",+ position: 0,+ createdAt: new Date(issue.created_at),+ })+ .returning();- await db.insert(taskTable).values({- title: issue.title,- description,- projectId,- number: issue.number,- status: "to-do",- priority: "low",- position: 0,- createdAt: new Date(issue.created_at),- });+ if (newTask) {+ await createExternalLink({+ taskId: newTask.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: issue.number.toString(),+ url: issue.html_url,+ title: issue.title,+ metadata: {+ state: issue.state,+ importedFrom: "github",+ author: issue.user?.login,+ },+ });+ imported++;+ }}- return { success: true, message: "Issues imported" };+ return { imported, skipped };}diff --git a/apps/api/src/github-integration/controllers/list-user-repositories.ts b/apps/api/src/github-integration/controllers/list-user-repositories.tsindex e7d1006ad..9ea2f21f8 100644--- a/apps/api/src/github-integration/controllers/list-user-repositories.ts+++ b/apps/api/src/github-integration/controllers/list-user-repositories.ts@@ -1,12 +1,12 @@import { HTTPException } from "hono/http-exception";-import createGithubApp from "../utils/create-github-app";--const githubApp = createGithubApp();+import { getGithubApp } from "../../plugins/github/utils/github-app";async function listUserRepositories() {+ const githubApp = getGithubApp();+if (!githubApp) {throw new HTTPException(500, {- message: "GitHub app not found",+ message: "GitHub app not configured",});}diff --git a/apps/api/src/github-integration/controllers/verify-github-installation.ts b/apps/api/src/github-integration/controllers/verify-github-installation.tsindex 37144a673..1e73f82de 100644--- a/apps/api/src/github-integration/controllers/verify-github-installation.ts+++ b/apps/api/src/github-integration/controllers/verify-github-installation.ts@@ -1,7 +1,5 @@import { HTTPException } from "hono/http-exception";-import createGithubApp from "../utils/create-github-app";--const githubApp = createGithubApp();+import { getGithubApp } from "../../plugins/github/utils/github-app";async function verifyGithubInstallation({repositoryOwner,@@ -10,10 +8,12 @@ async function verifyGithubInstallation({repositoryOwner: string;repositoryName: string;}) {+ const githubApp = getGithubApp();+try {if (!githubApp) {throw new HTTPException(500, {- message: "GitHub app not found",+ message: "GitHub app not configured",});}@@ -76,7 +76,7 @@ async function verifyGithubInstallation({try {if (!githubApp) {throw new HTTPException(500, {- message: "GitHub app not found",+ message: "GitHub app not configured",});}@@ -160,10 +160,12 @@ function getMissingPermissions(}async function getRepositoryId(owner: string, repo: string): Promise<number> {+ const githubApp = getGithubApp();+try {if (!githubApp) {throw new HTTPException(500, {- message: "GitHub app not found",+ message: "GitHub app not configured",});}diff --git a/apps/api/src/github-integration/index.ts b/apps/api/src/github-integration/index.tsindex 5dbc49c99..481a81ebf 100644--- a/apps/api/src/github-integration/index.ts+++ b/apps/api/src/github-integration/index.ts@@ -1,12 +1,12 @@-import { eq } from "drizzle-orm";+import { and, eq } from "drizzle-orm";import type { Context } from "hono";import { Hono } from "hono";import { HTTPException } from "hono/http-exception";import { describeRoute, resolver, validator } from "hono-openapi";import * as v from "valibot";import db from "../database";-import { githubIntegrationTable, projectTable } from "../database/schema";-import { subscribeToEvent } from "../events";+import { integrationTable, projectTable } from "../database/schema";+import { handleGitHubWebhook } from "../plugins/github/webhook-handler";import { githubIntegrationSchema } from "../schemas";import { validateWorkspaceAccess } from "../utils/validate-workspace-access";import { workspaceAccess } from "../utils/workspace-access-middleware";@@ -16,12 +16,6 @@ import getGithubIntegration from "./controllers/get-github-integration";import { importIssues } from "./controllers/import-issues";import listUserRepositories from "./controllers/list-user-repositories";import verifyGithubInstallation from "./controllers/verify-github-installation";-import createGithubApp from "./utils/create-github-app";-import { handleIssueClosed } from "./utils/issue-closed";-import { handleIssueOpened } from "./utils/issue-opened";-import { handleTaskCreated } from "./utils/task-created";-import { handleTaskPriorityChanged } from "./utils/task-priority-changed";-import { handleTaskStatusChanged } from "./utils/task-status-changed";const githubAppInfoSchema = v.object({appName: v.nullable(v.string()),@@ -49,40 +43,6 @@ const importResultSchema = v.object({errors: v.optional(v.array(v.string())),});-const githubApp = createGithubApp();--if (githubApp) {- githubApp.webhooks.on("issues.opened", handleIssueOpened);- githubApp.webhooks.on("issues.closed", handleIssueClosed);-}--subscribeToEvent<{- taskId: string;- userId: string;- title: string;- description: string;- priority: string;- status: string;- number: number;- projectId: string;-}>("task.created", handleTaskCreated);--subscribeToEvent<{- taskId: string;- userId: string | null;- oldStatus: string;- newStatus: string;- title: string;-}>("task.status_changed", handleTaskStatusChanged);--subscribeToEvent<{- taskId: string;- userId: string | null;- oldPriority: string;- newPriority: string;- title: string;-}>("task.priority_changed", handleTaskPriorityChanged);-const githubIntegration = new Hono<{Variables: {userId: string;@@ -272,13 +232,18 @@ const githubIntegration = new Hono<{}const [updatedIntegration] = await db- .update(githubIntegrationTable)+ .update(integrationTable).set({isActive:isActive !== undefined ? isActive : existingIntegration.isActive,updatedAt: new Date(),})- .where(eq(githubIntegrationTable.projectId, projectId))+ .where(+ and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.type, "github"),+ ),+ ).returning();return c.json(updatedIntegration, 200);@@ -362,38 +327,33 @@ const githubIntegration = new Hono<{},);-export async function handleGithubWebhook(c: Context) {- try {- if (!githubApp) {- return c.json({ error: "GitHub integration not configured" }, 400);- }+export async function handleGithubWebhookRoute(c: Context) {+ const arrayBuffer = await c.req.arrayBuffer();+ const body = Buffer.from(arrayBuffer).toString("utf8");- const arrayBuffer = await c.req.arrayBuffer();- const body = Buffer.from(arrayBuffer).toString("utf8");-- const signature = c.req.header("x-hub-signature-256");- if (!signature) {- return c.json({ error: "Missing signature" }, 400);- }+ const signature = c.req.header("x-hub-signature-256");+ if (!signature) {+ return c.json({ error: "Missing signature" }, 400);+ }- const eventName = c.req.header("x-github-event");- if (!eventName) {- return c.json({ error: "Missing event name" }, 400);- }+ const eventName = c.req.header("x-github-event");+ if (!eventName) {+ return c.json({ error: "Missing event name" }, 400);+ }- const deliveryId = c.req.header("x-github-delivery") || "";+ const deliveryId = c.req.header("x-github-delivery") || "";- await githubApp.webhooks.verifyAndReceive({- id: deliveryId,- name: eventName as "issues" | "pull_request" | "push" | string,- signature,- payload: body,- });+ const result = await handleGitHubWebhook(+ body,+ signature,+ eventName,+ deliveryId,+ );- return c.json({ status: "success" });- } catch (error) {- console.error("Webhook processing error:", error);- return c.json({ error: "Webhook processing failed" }, 400);+ if (!result.success) {+ return c.json({ error: result.error }, 400);}++ return c.json({ status: "success" });}export default githubIntegration;diff --git a/apps/api/src/github-integration/utils/create-github-app.ts b/apps/api/src/github-integration/utils/create-github-app.tsdeleted file mode 100644index 0d1c8d04c..000000000--- a/apps/api/src/github-integration/utils/create-github-app.ts+++ /dev/null@@ -1,26 +0,0 @@-import { config } from "dotenv-mono";-import { App } from "octokit";--config();--function createGithubApp(): App | null {- if (- !process.env.GITHUB_WEBHOOK_SECRET ||- !process.env.GITHUB_APP_ID ||- !process.env.GITHUB_PRIVATE_KEY- ) {- return null;- }-- const githubApp: App = new App({- appId: process.env.GITHUB_APP_ID ?? "",- privateKey: process.env.GITHUB_PRIVATE_KEY ?? "",- webhooks: {- secret: process.env.GITHUB_WEBHOOK_SECRET ?? "",- },- });-- return githubApp;-}--export default createGithubApp;diff --git a/apps/api/src/github-integration/utils/create-github-labels.ts b/apps/api/src/github-integration/utils/create-github-labels.tsdeleted file mode 100644index c2519be53..000000000--- a/apps/api/src/github-integration/utils/create-github-labels.ts+++ /dev/null@@ -1,55 +0,0 @@-import type { Octokit } from "octokit";-import { getLabelColor } from "./github-label-colors";--export async function createGitHubLabels(- octokit: Octokit,- owner: string,- repo: string,- labels: string[],-) {- for (const labelName of labels) {- try {- try {- await octokit.rest.issues.getLabel({- owner,- repo,- name: labelName,- });- console.log(`Label "${labelName}" already exists`);- } catch (_error) {- const color = getLabelColor(labelName);- await octokit.rest.issues.createLabel({- owner,- repo,- name: labelName,- color,- description: `Kaneo ${labelName.replace(":", " ")} label`,- });- console.log(`Created label "${labelName}" with color ${color}`);- }- } catch (error) {- console.error(`Failed to create label "${labelName}":`, error);- }- }-}--export async function addLabelsToIssue(- octokit: Octokit,- owner: string,- repo: string,- issueNumber: number,- labels: string[],-) {- try {- await createGitHubLabels(octokit, owner, repo, labels);-- await octokit.rest.issues.addLabels({- owner,- repo,- issue_number: issueNumber,- labels,- });- } catch (error) {- console.error("Failed to add labels to issue:", error);- }-}diff --git a/apps/api/src/github-integration/utils/extract-issue-priority.ts b/apps/api/src/github-integration/utils/extract-issue-priority.tsdeleted file mode 100644index e237bfde6..000000000--- a/apps/api/src/github-integration/utils/extract-issue-priority.ts+++ /dev/null@@ -1,31 +0,0 @@-type GitHubLabel = string | { name?: string };--export function extractIssuePriority(- labels: GitHubLabel[] | undefined,-): string {- if (!labels) return "medium";-- const priorityLabels = labels- .map((label) => (typeof label === "string" ? label : label?.name))- .filter((name) => name?.startsWith("priority:"));-- const firstPriorityLabel = priorityLabels[0];- const priority = firstPriorityLabel?.replace("priority:", "") || "medium";-- const validPriorities = ["low", "medium", "high", "urgent"];- return validPriorities.includes(priority) ? priority : "medium";-}--export function extractIssueStatus(labels: GitHubLabel[] | undefined): string {- if (!labels) return "to-do";-- const statusLabels = labels- .map((label) => (typeof label === "string" ? label : label?.name))- .filter((name) => name?.startsWith("status:"));-- const firstStatusLabel = statusLabels[0];- const status = firstStatusLabel?.replace("status:", "") || "to-do";-- const validStatuses = ["to-do", "in-progress", "done", "planned", "archived"];- return validStatuses.includes(status) ? status : "to-do";-}diff --git a/apps/api/src/github-integration/utils/format-github-comment.ts b/apps/api/src/github-integration/utils/format-github-comment.tsdeleted file mode 100644index 2a6100836..000000000--- a/apps/api/src/github-integration/utils/format-github-comment.ts+++ /dev/null@@ -1,23 +0,0 @@-export function formatGitHubComment({- id,- priority,- status,- title,-}: {- id: string;- priority: string;- status: string;- title: string;-}) {- return `🎯 **Task created** - ${title}-<details>-<summary>Task Details</summary>--- **Task ID:** ${id}-- **Priority:** ${priority}-- **Status:** ${status}---*This issue is automatically synchronized with your Kaneo project.*-</details>`;-}diff --git a/apps/api/src/github-integration/utils/format-task-description.ts b/apps/api/src/github-integration/utils/format-task-description.tsdeleted file mode 100644index 6b398ca7f..000000000--- a/apps/api/src/github-integration/utils/format-task-description.ts+++ /dev/null@@ -1,17 +0,0 @@-export function formatTaskDescription(payload: {- number: number;- body: string | null;- html_url: string;- user: { login: string } | null;- repository: {- full_name: string;- };-}): string {- const issueUrl = payload.html_url;- const body = payload.body || "No description provided";-- return `${body}------*Created from GitHub issue: ${issueUrl}*`;-}diff --git a/apps/api/src/github-integration/utils/github-label-colors.ts b/apps/api/src/github-integration/utils/github-label-colors.tsdeleted file mode 100644index 97e5f3e5f..000000000--- a/apps/api/src/github-integration/utils/github-label-colors.ts+++ /dev/null@@ -1,20 +0,0 @@-export const githubLabelColors = {- "priority:low": "0EA5E9", // Blue- "priority:medium": "EAB308", // Yellow- "priority:high": "F97316", // Orange- "priority:urgent": "EF4444", // Red-- "status:to-do": "6B7280", // Gray- "status:in-progress": "3B82F6", // Blue- "status:done": "10B981", // Green- "status:planned": "8B5CF6", // Purple- "status:archived": "6B7280", // Gray-- kaneo: "6366F1", // Indigo-};--export function getLabelColor(labelName: string): string {- return (- githubLabelColors[labelName as keyof typeof githubLabelColors] || "6B7280"- );-}diff --git a/apps/api/src/github-integration/utils/issue-closed.ts b/apps/api/src/github-integration/utils/issue-closed.tsdeleted file mode 100644index f22e62cc6..000000000--- a/apps/api/src/github-integration/utils/issue-closed.ts+++ /dev/null@@ -1,72 +0,0 @@-import type {- EmitterWebhookEvent,- EmitterWebhookEventName,-} from "@octokit/webhooks";-import { eq } from "drizzle-orm";-import type { Octokit } from "octokit";-import db from "../../database";-import { taskTable } from "../../database/schema";-import getGithubIntegrationByRepositoryId from "../controllers/get-github-integration-by-repository-id";--export type HandlerFunction<- TName extends EmitterWebhookEventName,- TTransformed = unknown,-> = (event: EmitterWebhookEvent<TName> & TTransformed) => void;--export const handleIssueClosed: HandlerFunction<- "issues.closed",- { octokit: Octokit }-> = async ({ payload }): Promise<void> => {- try {- if (payload.issue.title.startsWith("[Kaneo]")) {- console.log("Skipping Kaneo-created issue to avoid loop");- return;- }-- const integration = await getGithubIntegrationByRepositoryId(- payload.repository.owner.login,- payload.repository.name,- );-- if (!integration || !integration.isActive) {- console.log(- "No active Kaneo integration found for repository:",- payload.repository.full_name,- );- return;- }-- const tasks = await db.query.taskTable.findMany({- where: eq(taskTable.projectId, integration.projectId),- });-- const kaneoTask = tasks.find((task) =>- task.description?.includes(- `Created from GitHub issue: ${payload.issue.html_url}`,- ),- );-- if (!kaneoTask) {- console.log(- "Kaneo task not found for GitHub issue:",- payload.issue.html_url,- );- return;- }-- try {- await db- .update(taskTable)- .set({- status: "done",- })- .where(eq(taskTable.id, kaneoTask.id));-- console.log(`Updated Kaneo task ${kaneoTask.id} status to "done"`);- } catch (error) {- console.error("Failed to update Kaneo task status:", error);- }- } catch (error) {- console.error("Failed to handle GitHub issue closed:", error);- }-};diff --git a/apps/api/src/github-integration/utils/issue-opened.ts b/apps/api/src/github-integration/utils/issue-opened.tsdeleted file mode 100644index a02416667..000000000--- a/apps/api/src/github-integration/utils/issue-opened.ts+++ /dev/null@@ -1,105 +0,0 @@-import type {- EmitterWebhookEvent,- EmitterWebhookEventName,-} from "@octokit/webhooks";-import type { Octokit } from "octokit";-import createTask from "../../task/controllers/create-task";-import getGithubIntegrationByRepositoryId from "../controllers/get-github-integration-by-repository-id";-import { addLabelsToIssue } from "./create-github-labels";-import {- extractIssuePriority,- extractIssueStatus,-} from "./extract-issue-priority";-import { formatGitHubComment } from "./format-github-comment";-import { formatTaskDescription } from "./format-task-description";--export type HandlerFunction<- TName extends EmitterWebhookEventName,- TTransformed = unknown,-> = (event: EmitterWebhookEvent<TName> & TTransformed) => void;--export const handleIssueOpened: HandlerFunction<- "issues.opened",- { octokit: Octokit }-> = async ({ payload, octokit }): Promise<void> => {- try {- if (payload.issue.title.startsWith("[Kaneo]")) {- console.log("Skipping Kaneo-created issue to avoid loop");- return;- }-- const integration = await getGithubIntegrationByRepositoryId(- payload.repository.owner.login,- payload.repository.name,- );-- if (!integration || !integration.isActive) {- console.log(- "No active Kaneo integration found for repository:",- payload.repository.full_name,- );- return;- }-- const taskPriority = extractIssuePriority(payload.issue.labels);- const taskStatus = extractIssueStatus(payload.issue.labels);-- const task = await createTask({- projectId: integration.projectId,- title: payload.issue.title,- description: formatTaskDescription({- number: payload.issue.number,- body: payload.issue.body,- html_url: payload.issue.html_url,- user: payload.issue.user,- repository: payload.repository,- }),- status: taskStatus,- priority: taskPriority,- dueDate: new Date(),- userId: undefined,- });-- const existingLabels =- payload.issue.labels- ?.map((label) => (typeof label === "string" ? label : label.name))- .filter(Boolean) || [];-- const labelsToAdd = [- "kaneo",- `priority:${taskPriority}`,- `status:${taskStatus}`,- ].filter((label) => !existingLabels.includes(label));-- try {- if (labelsToAdd.length > 0) {- await addLabelsToIssue(- octokit,- payload.repository.owner.login,- payload.repository.name,- payload.issue.number,- labelsToAdd,- );- }-- await octokit.rest.issues.createComment({- owner: payload.repository.owner.login,- repo: payload.repository.name,- issue_number: payload.issue.number,- body: formatGitHubComment({- id: task.id,- title: payload.issue.title,- priority: task.priority || "medium",- status: task.status || "to-do",- }),- });- } catch (commentError) {- console.error(- "Failed to add comment or labels to GitHub issue:",- commentError,- );- }- } catch (error) {- console.error("Failed to create Kaneo task from GitHub issue:", error);- }-};diff --git a/apps/api/src/github-integration/utils/task-created.ts b/apps/api/src/github-integration/utils/task-created.tsdeleted file mode 100644index d6a01afd6..000000000--- a/apps/api/src/github-integration/utils/task-created.ts+++ /dev/null@@ -1,113 +0,0 @@-import { eq } from "drizzle-orm";-import db from "../../database";-import { taskTable } from "../../database/schema";-import getGithubIntegration from "../controllers/get-github-integration";-import createGithubApp from "./create-github-app";-import { addLabelsToIssue } from "./create-github-labels";--const githubApp = createGithubApp();--export async function handleTaskCreated(data: {- taskId: string;- userId: string;- title: string;- description: string;- priority: string;- status: string;- number: number;- projectId: string;-}) {- if (!githubApp) {- return;- }-- const { taskId, userId, title, description, priority, status, projectId } =- data;-- if (description?.includes("Created from GitHub issue:")) {- console.log(- "Skipping GitHub issue creation for task created from GitHub issue:",- taskId,- );- return;- }-- try {- const integration = await getGithubIntegration(projectId);-- if (!integration || !integration.isActive) {- console.log("No active GitHub integration found for project:", projectId);- return;- }-- const { repositoryOwner, repositoryName } = integration;- console.log(- "Creating GitHub issue for repository:",- `${repositoryOwner}/${repositoryName}`,- );-- let installationId = integration.installationId;-- if (!installationId) {- const { data: installation } =- await githubApp.octokit.rest.apps.getRepoInstallation({- owner: repositoryOwner,- repo: repositoryName,- });- installationId = installation.id;- }-- const octokit = await githubApp.getInstallationOctokit(installationId);-- const createdIssue = await octokit.rest.issues.create({- owner: repositoryOwner,- repo: repositoryName,- title: `[Kaneo] ${title}`,- body: `**Task created in Kaneo**--**Description:** ${description || "No description provided"}--**Details:**-- Task ID: ${taskId}-- Status: ${status}-- Priority: ${priority || "Not set"}-- Assigned to: ${userId || "Unassigned"}------*This issue was automatically created from Kaneo task management system.*`,- });-- const labelsToAdd = [- "kaneo",- `priority:${priority || "low"}`,- `status:${status}`,- ];- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- createdIssue.data.number,- labelsToAdd,- );-- try {- await db- .update(taskTable)- .set({- description: `${description || ""}-------*Linked to GitHub issue: ${createdIssue.data.html_url}*`,- })- .where(eq(taskTable.id, taskId));- } catch (error) {- console.error(- "Failed to update task description with GitHub issue link:",- error,- );- }- } catch (error) {- console.error("Failed to create GitHub issue:", error);- }-}diff --git a/apps/api/src/github-integration/utils/task-priority-changed.ts b/apps/api/src/github-integration/utils/task-priority-changed.tsdeleted file mode 100644index fb585b338..000000000--- a/apps/api/src/github-integration/utils/task-priority-changed.ts+++ /dev/null@@ -1,131 +0,0 @@-import { eq } from "drizzle-orm";-import db from "../../database";-import { taskTable } from "../../database/schema";-import getGithubIntegration from "../controllers/get-github-integration";-import createGithubApp from "./create-github-app";-import { addLabelsToIssue } from "./create-github-labels";--const githubApp = createGithubApp();--export async function handleTaskPriorityChanged(data: {- taskId: string;- userId: string | null;- oldPriority: string;- newPriority: string;-}) {- if (!githubApp) {- return;- }-- const { taskId, oldPriority, newPriority } = data;-- try {- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, taskId),- });-- if (!task) {- console.log("Task not found for priority change:", taskId);- return;- }-- const integration = await getGithubIntegration(task.projectId);-- if (!integration || !integration.isActive) {- console.log(- "No active GitHub integration found for project:",- task.projectId,- );- return;- }-- const hasKaneoLink = task.description?.includes("Linked to GitHub issue:");- const hasGitHubLink = task.description?.includes(- "Created from GitHub issue:",- );-- if (!hasKaneoLink && !hasGitHubLink) {- console.log(- "Skipping GitHub issue update - task has no GitHub issue link:",- taskId,- );- return;- }-- const { repositoryOwner, repositoryName } = integration;- console.log(- "Updating GitHub issue priority for repository:",- `${repositoryOwner}/${repositoryName}`,- );-- let installationId = integration.installationId;-- if (!installationId) {- const { data: installation } =- await githubApp.octokit.rest.apps.getRepoInstallation({- owner: repositoryOwner,- repo: repositoryName,- });- installationId = installation.id;- }-- const octokit = await githubApp.getInstallationOctokit(installationId);-- let githubIssueUrlMatch = task.description?.match(- /Linked to GitHub issue: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/,- );-- if (!githubIssueUrlMatch) {- githubIssueUrlMatch = task.description?.match(- /Created from GitHub issue: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/,- );- }-- if (!githubIssueUrlMatch) {- console.log("GitHub issue URL not found in task description:", taskId);- return;- }-- const githubIssueUrl = githubIssueUrlMatch[1];- const issueNumber = Number.parseInt(- githubIssueUrl?.split("/").pop() || "0",- 10,- );-- if (!issueNumber) {- console.log("Could not extract issue number from URL:", githubIssueUrl);- return;- }-- const labelsToAdd = [`priority:${newPriority}`];-- try {- await octokit.rest.issues.removeLabel({- owner: repositoryOwner,- repo: repositoryName,- issue_number: issueNumber,- name: `priority:${oldPriority}`,- });- } catch (error) {- console.log("Could not remove old priority label:", error);- }-- try {- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- issueNumber,- labelsToAdd,- );- } catch (error) {- console.error("Failed to add new priority label:", error);- }-- console.log(- `Updated GitHub issue ${issueNumber} priority from ${oldPriority} to ${newPriority}`,- );- } catch (error) {- console.error("Failed to update GitHub issue priority:", error);- }-}diff --git a/apps/api/src/github-integration/utils/task-status-changed.ts b/apps/api/src/github-integration/utils/task-status-changed.tsdeleted file mode 100644index 355f2da6c..000000000--- a/apps/api/src/github-integration/utils/task-status-changed.ts+++ /dev/null@@ -1,157 +0,0 @@-import { eq } from "drizzle-orm";-import db from "../../database";-import { taskTable } from "../../database/schema";-import getGithubIntegration from "../controllers/get-github-integration";-import createGithubApp from "./create-github-app";-import { addLabelsToIssue } from "./create-github-labels";--const githubApp = createGithubApp();--export async function handleTaskStatusChanged(data: {- taskId: string;- userId: string | null;- oldStatus: string;- newStatus: string;-}) {- if (!githubApp) {- return;- }-- const { taskId, oldStatus, newStatus } = data;-- try {- const task = await db.query.taskTable.findFirst({- where: eq(taskTable.id, taskId),- });-- if (!task) {- console.log("Task not found for status change:", taskId);- return;- }-- const integration = await getGithubIntegration(task.projectId);-- if (!integration || !integration.isActive) {- console.log(- "No active GitHub integration found for project:",- task.projectId,- );- return;- }-- const hasKaneoLink = task.description?.includes("Linked to GitHub issue:");- const hasGitHubLink = task.description?.includes(- "Created from GitHub issue:",- );-- if (!hasKaneoLink && !hasGitHubLink) {- console.log(- "Skipping GitHub issue update - task has no GitHub issue link:",- taskId,- );- return;- }-- const { repositoryOwner, repositoryName } = integration;- console.log(- "Updating GitHub issue status for repository:",- `${repositoryOwner}/${repositoryName}`,- );-- let installationId = integration.installationId;-- if (!installationId) {- const { data: installation } =- await githubApp.octokit.rest.apps.getRepoInstallation({- owner: repositoryOwner,- repo: repositoryName,- });- installationId = installation.id;- }-- const octokit = await githubApp.getInstallationOctokit(installationId);-- let githubIssueUrlMatch = task.description?.match(- /Linked to GitHub issue: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/,- );-- if (!githubIssueUrlMatch) {- githubIssueUrlMatch = task.description?.match(- /Created from GitHub issue: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/,- );- }-- if (!githubIssueUrlMatch) {- console.log("GitHub issue URL not found in task description:", taskId);- return;- }-- const githubIssueUrl = githubIssueUrlMatch[1];- const issueNumber = Number.parseInt(- githubIssueUrl?.split("/").pop() || "0",- 10,- );-- if (!issueNumber) {- console.log("Could not extract issue number from URL:", githubIssueUrl);- return;- }-- const labelsToAdd = [`status:${newStatus}`];-- try {- await octokit.rest.issues.removeLabel({- owner: repositoryOwner,- repo: repositoryName,- issue_number: issueNumber,- name: `status:${oldStatus}`,- });- } catch (error) {- console.log("Could not remove old status label:", error);- }-- try {- await addLabelsToIssue(- octokit,- repositoryOwner,- repositoryName,- issueNumber,- labelsToAdd,- );- } catch (error) {- console.error("Failed to add new status label:", error);- }-- if (newStatus === "done") {- try {- await octokit.rest.issues.update({- owner: repositoryOwner,- repo: repositoryName,- issue_number: issueNumber,- state: "closed",- });- console.log(`Closed GitHub issue ${issueNumber}`);- } catch (error) {- console.error("Failed to close GitHub issue:", error);- }- } else if (oldStatus === "done" && newStatus !== "done") {- try {- await octokit.rest.issues.update({- owner: repositoryOwner,- repo: repositoryName,- issue_number: issueNumber,- state: "open",- });- console.log(`Reopened GitHub issue ${issueNumber}`);- } catch (error) {- console.error("Failed to reopen GitHub issue:", error);- }- }-- console.log(- `Updated GitHub issue ${issueNumber} status from ${oldStatus} to ${newStatus}`,- );- } catch (error) {- console.error("Failed to update GitHub issue status:", error);- }-}diff --git a/apps/api/src/index.ts b/apps/api/src/index.tsindex ff6d53309..78cb502db 100644--- a/apps/api/src/index.ts+++ b/apps/api/src/index.ts@@ -9,10 +9,14 @@ import activity from "./activity";import { auth } from "./auth";import config from "./config";import db from "./database";-import githubIntegration, { handleGithubWebhook } from "./github-integration";+import externalLink from "./external-link";+import githubIntegration, {+ handleGithubWebhookRoute,+} from "./github-integration";import label from "./label";-import notification from "./notification";+import { initializePlugins } from "./plugins";+import { migrateGitHubIntegration } from "./plugins/github/migration";import project from "./project";import { getPublicProject } from "./project/controllers/get-public-project";import search from "./search";@@ -79,7 +83,7 @@ api.get("/public-project/:id", async (c) => {return c.json(project);});-api.post("/github-integration/webhook", handleGithubWebhook);+api.post("/github-integration/webhook", handleGithubWebhookRoute);const configApi = api.route("/config", config);@@ -171,6 +175,7 @@ const githubIntegrationApi = api.route("/github-integration",githubIntegration,);+const externalLinkApi = api.route("/external-link", externalLink);app.route("/api", api);@@ -184,6 +189,10 @@ app.route("/api", api);migrationsFolder: `${process.cwd()}/drizzle`,});console.log("✅ Database migrated successfully!");++ await migrateGitHubIntegration();++ initializePlugins();} catch (error) {console.error("❌ Database migration failed!", error);process.exit(1);@@ -211,6 +220,7 @@ export type AppType =| typeof labelApi| typeof notificationApi| typeof searchApi- | typeof githubIntegrationApi;+ | typeof githubIntegrationApi+ | typeof externalLinkApi;export default app;diff --git a/apps/api/src/plugins/github/config.ts b/apps/api/src/plugins/github/config.tsnew file mode 100644index 000000000..c14cbc5e8--- /dev/null+++ b/apps/api/src/plugins/github/config.ts@@ -0,0 +1,73 @@+import * as v from "valibot";++export const branchPatterns = [+ "{slug}-{number}",+ "{slug}-{number}-{title}",+ "{number}",+ "{number}-{title}",+ "feature/{slug}-{number}",+ "feature/{number}-{title}",+ "fix/{slug}-{number}",+ "fix/{number}-{title}",+] as const;++export type BranchPattern = (typeof branchPatterns)[number] | "custom";++export const githubConfigSchema = v.object({+ repositoryOwner: v.string(),+ repositoryName: v.string(),+ installationId: v.nullable(v.number()),+ branchPattern: v.optional(v.string()),+ customBranchRegex: v.optional(v.string()),+ statusTransitions: v.optional(+ v.object({+ onBranchPush: v.optional(v.string()),+ onPROpen: v.optional(v.string()),+ onPRMerge: v.optional(v.string()),+ }),+ ),+});++export type GitHubConfig = v.InferOutput<typeof githubConfigSchema>;++export async function validateGitHubConfig(+ config: unknown,+): Promise<{ valid: boolean; errors?: string[] }> {+ try {+ v.parse(githubConfigSchema, config);+ return { valid: true };+ } catch (error) {+ if (error instanceof v.ValiError) {+ return {+ valid: false,+ errors: error.issues.map((issue) => issue.message),+ };+ }+ return {+ valid: false,+ errors: [error instanceof Error ? error.message : "Invalid config"],+ };+ }+}++export const defaultGitHubConfig: Partial<GitHubConfig> = {+ branchPattern: "{slug}-{number}",+ statusTransitions: {+ onBranchPush: "in-progress",+ onPROpen: "in-review",+ onPRMerge: "done",+ },+};++export function getDefaultConfig(+ repositoryOwner: string,+ repositoryName: string,+ installationId: number | null = null,+): GitHubConfig {+ return {+ repositoryOwner,+ repositoryName,+ installationId,+ ...defaultGitHubConfig,+ };+}diff --git a/apps/api/src/plugins/github/events/task-created.ts b/apps/api/src/plugins/github/events/task-created.tsnew file mode 100644index 000000000..0fb3188b3--- /dev/null+++ b/apps/api/src/plugins/github/events/task-created.ts@@ -0,0 +1,79 @@+import type { PluginContext, TaskCreatedEvent } from "../../types";+import type { GitHubConfig } from "../config";+import {+ createExternalLink,+ findExternalLinkByTaskAndType,+} from "../services/link-manager";+import {+ formatIssueBody,+ formatIssueTitle,+ getLabelsForIssue,+} from "../utils/format";+import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import { addLabelsToIssue } from "../utils/labels";++export async function handleTaskCreated(+ event: TaskCreatedEvent,+ context: PluginContext,+): Promise<void> {+ const githubApp = getGithubApp();+ if (!githubApp) {+ return;+ }++ const config = context.config as GitHubConfig;+ const { repositoryOwner, repositoryName } = config;++ const existingLink = await findExternalLinkByTaskAndType(+ event.taskId,+ context.integrationId,+ "issue",+ );++ if (existingLink) {+ return;+ }++ try {+ let installationId = config.installationId;+ if (!installationId) {+ installationId = await getInstallationIdForRepo(+ repositoryOwner,+ repositoryName,+ );+ }++ const octokit = await githubApp.getInstallationOctokit(installationId);++ const createdIssue = await octokit.rest.issues.create({+ owner: repositoryOwner,+ repo: repositoryName,+ title: formatIssueTitle(event.title),+ body: formatIssueBody(event.description, event.taskId),+ });++ const labels = getLabelsForIssue(event.priority, event.status);+ await addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ createdIssue.data.number,+ labels,+ );++ await createExternalLink({+ taskId: event.taskId,+ integrationId: context.integrationId,+ resourceType: "issue",+ externalId: createdIssue.data.number.toString(),+ url: createdIssue.data.html_url,+ title: createdIssue.data.title,+ metadata: {+ state: createdIssue.data.state,+ createdFrom: "kaneo",+ },+ });+ } catch (error) {+ console.error("Failed to create GitHub issue:", error);+ }+}diff --git a/apps/api/src/plugins/github/events/task-priority-changed.ts b/apps/api/src/plugins/github/events/task-priority-changed.tsnew file mode 100644index 000000000..8f27676bf--- /dev/null+++ b/apps/api/src/plugins/github/events/task-priority-changed.ts@@ -0,0 +1,64 @@+import type { PluginContext, TaskPriorityChangedEvent } from "../../types";+import type { GitHubConfig } from "../config";+import { findExternalLinksByTask } from "../services/link-manager";+import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import { addLabelsToIssue, removeLabel } from "../utils/labels";++export async function handleTaskPriorityChanged(+ event: TaskPriorityChangedEvent,+ context: PluginContext,+): Promise<void> {+ const githubApp = getGithubApp();+ if (!githubApp) {+ return;+ }++ const config = context.config as GitHubConfig;+ const { repositoryOwner, repositoryName } = config;++ try {+ const links = await findExternalLinksByTask(event.taskId);+ const issueLink = links.find(+ (link) =>+ link.integrationId === context.integrationId &&+ link.resourceType === "issue",+ );++ if (!issueLink) {+ return;+ }++ let installationId = config.installationId;+ if (!installationId) {+ installationId = await getInstallationIdForRepo(+ repositoryOwner,+ repositoryName,+ );+ }++ const octokit = await githubApp.getInstallationOctokit(installationId);+ const issueNumber = Number.parseInt(issueLink.externalId, 10);++ if (event.oldPriority && event.oldPriority !== "no-priority") {+ await removeLabel(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ `priority:${event.oldPriority}`,+ );+ }++ if (event.newPriority && event.newPriority !== "no-priority") {+ await addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ [`priority:${event.newPriority}`],+ );+ }+ } catch (error) {+ console.error("Failed to update GitHub issue priority:", error);+ }+}diff --git a/apps/api/src/plugins/github/events/task-status-changed.ts b/apps/api/src/plugins/github/events/task-status-changed.tsnew file mode 100644index 000000000..8650f3264--- /dev/null+++ b/apps/api/src/plugins/github/events/task-status-changed.ts@@ -0,0 +1,93 @@+import type { PluginContext, TaskStatusChangedEvent } from "../../types";+import type { GitHubConfig } from "../config";+import {+ findExternalLinksByTask,+ updateExternalLink,+} from "../services/link-manager";+import { getGithubApp, getInstallationIdForRepo } from "../utils/github-app";+import { addLabelsToIssue, removeLabel } from "../utils/labels";++export async function handleTaskStatusChanged(+ event: TaskStatusChangedEvent,+ context: PluginContext,+): Promise<void> {+ const githubApp = getGithubApp();+ if (!githubApp) {+ return;+ }++ const config = context.config as GitHubConfig;+ const { repositoryOwner, repositoryName } = config;++ try {+ const links = await findExternalLinksByTask(event.taskId);+ const issueLink = links.find(+ (link) =>+ link.integrationId === context.integrationId &&+ link.resourceType === "issue",+ );++ if (!issueLink) {+ return;+ }++ let installationId = config.installationId;+ if (!installationId) {+ installationId = await getInstallationIdForRepo(+ repositoryOwner,+ repositoryName,+ );+ }++ const octokit = await githubApp.getInstallationOctokit(installationId);+ const issueNumber = Number.parseInt(issueLink.externalId, 10);++ await removeLabel(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ `status:${event.oldStatus}`,+ );++ await addLabelsToIssue(+ octokit,+ repositoryOwner,+ repositoryName,+ issueNumber,+ [`status:${event.newStatus}`],+ );++ if (event.newStatus === "done") {+ await octokit.rest.issues.update({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: issueNumber,+ state: "closed",+ });++ await updateExternalLink(issueLink.id, {+ metadata: {+ ...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),+ state: "closed",+ },+ });+ } else if (event.oldStatus === "done" && event.newStatus !== "done") {+ await octokit.rest.issues.update({+ owner: repositoryOwner,+ repo: repositoryName,+ issue_number: issueNumber,+ state: "open",+ });++ await updateExternalLink(issueLink.id, {+ metadata: {+ ...(issueLink.metadata ? JSON.parse(issueLink.metadata) : {}),+ state: "open",+ },+ });+ }+ } catch (error) {+ console.error("Failed to update GitHub issue status:", error);+ }+}diff --git a/apps/api/src/plugins/github/index.ts b/apps/api/src/plugins/github/index.tsnew file mode 100644index 000000000..474c3d57d--- /dev/null+++ b/apps/api/src/plugins/github/index.ts@@ -0,0 +1,19 @@+import type { IntegrationPlugin } from "../types";+import { validateGitHubConfig } from "./config";+import { handleTaskCreated } from "./events/task-created";+import { handleTaskPriorityChanged } from "./events/task-priority-changed";+import { handleTaskStatusChanged } from "./events/task-status-changed";+import { setupWebhookHandlers } from "./webhook-handler";++export const githubPlugin: IntegrationPlugin = {+ type: "github",+ name: "GitHub",+ onTaskCreated: handleTaskCreated,+ onTaskStatusChanged: handleTaskStatusChanged,+ onTaskPriorityChanged: handleTaskPriorityChanged,+ validateConfig: validateGitHubConfig,+};++export function initializeGitHubPlugin() {+ setupWebhookHandlers();+}diff --git a/apps/api/src/plugins/github/migration.ts b/apps/api/src/plugins/github/migration.tsnew file mode 100644index 000000000..1ac88a7dc--- /dev/null+++ b/apps/api/src/plugins/github/migration.ts@@ -0,0 +1,173 @@+import { and, eq, sql } from "drizzle-orm";+import db from "../../database";+import {+ externalLinkTable,+ integrationTable,+ taskTable,+} from "../../database/schema";+import { defaultGitHubConfig } from "./config";++async function tableExists(tableName: string): Promise<boolean> {+ try {+ const result = await db.execute(sql`+ SELECT EXISTS (+ SELECT FROM information_schema.tables+ WHERE table_schema = 'public'+ AND table_name = ${tableName}+ );+ `);+ return (result.rows[0] as { exists: boolean })?.exists === true;+ } catch {+ return false;+ }+}++export async function migrateGitHubIntegration() {+ const oldTableExists = await tableExists("github_integration");++ if (!oldTableExists) {+ console.log("No old github_integration table found, skipping migration");+ return;+ }++ console.log("🔄 Starting GitHub integration migration...");++ try {+ const oldIntegrations = await db.query.githubIntegrationTable.findMany();++ if (oldIntegrations.length === 0) {+ console.log("No old integrations to migrate");+ await dropOldTable();+ return;+ }++ let migratedCount = 0;++ for (const old of oldIntegrations) {+ const existingIntegration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, old.projectId),+ eq(integrationTable.type, "github"),+ ),+ });++ if (existingIntegration) {+ continue;+ }++ await db.insert(integrationTable).values({+ projectId: old.projectId,+ type: "github",+ config: JSON.stringify({+ repositoryOwner: old.repositoryOwner,+ repositoryName: old.repositoryName,+ installationId: old.installationId,+ ...defaultGitHubConfig,+ }),+ isActive: old.isActive ?? true,+ createdAt: old.createdAt,+ updatedAt: old.updatedAt,+ });++ migratedCount++;+ }++ console.log(`✓ Migrated ${migratedCount} integrations`);++ await migrateTaskLinks();++ await dropOldTable();++ console.log("✅ GitHub integration migration complete!");+ } catch (error) {+ console.error("Failed to migrate GitHub integration:", error);+ throw error;+ }+}++async function migrateTaskLinks() {+ console.log("🔄 Migrating task links from descriptions...");++ const tasks = await db.query.taskTable.findMany();++ let linksCreated = 0;+ let descriptionsUpdated = 0;++ for (const task of tasks) {+ if (!task.description) continue;++ const linkMatch = task.description.match(+ /(Linked to|Created from) GitHub issue: (https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues\/(\d+))/,+ );++ if (!linkMatch) continue;++ const linkType = linkMatch[1];+ const url = linkMatch[2];+ const owner = linkMatch[3];+ const repo = linkMatch[4];+ const issueNumber = linkMatch[5];++ if (!url || !owner || !repo || !issueNumber) continue;++ const integration = await db.query.integrationTable.findFirst({+ where: and(+ eq(integrationTable.projectId, task.projectId),+ eq(integrationTable.type, "github"),+ ),+ });++ if (!integration) continue;++ const config = JSON.parse(integration.config);+ if (config.repositoryOwner !== owner || config.repositoryName !== repo) {+ continue;+ }++ const existingLink = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.taskId, task.id),+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ ),+ });++ if (!existingLink) {+ await db.insert(externalLinkTable).values({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: issueNumber,+ url: url,+ title: null,+ metadata: JSON.stringify({+ migrated: true,+ createdFrom: linkType === "Created from" ? "github" : "kaneo",+ }),+ });+ linksCreated++;+ }++ const cleanedDescription = task.description+ .replace(/\n\n---\n\n\*.*GitHub issue:.*\*/g, "")+ .replace(/\n---\n<sub>Task:.*<\/sub>/g, "")+ .trim();++ if (cleanedDescription !== task.description) {+ await db+ .update(taskTable)+ .set({ description: cleanedDescription || null })+ .where(eq(taskTable.id, task.id));+ descriptionsUpdated++;+ }+ }++ console.log(`✓ Created ${linksCreated} external links`);+ console.log(`✓ Cleaned ${descriptionsUpdated} task descriptions`);+}++async function dropOldTable() {+ console.log("🗑️ Dropping old github_integration table...");+ await db.execute(sql`DROP TABLE IF EXISTS github_integration CASCADE`);+ console.log("✓ Dropped github_integration table");+}diff --git a/apps/api/src/plugins/github/services/link-manager.ts b/apps/api/src/plugins/github/services/link-manager.tsnew file mode 100644index 000000000..56bb13bea--- /dev/null+++ b/apps/api/src/plugins/github/services/link-manager.ts@@ -0,0 +1,138 @@+import { and, eq } from "drizzle-orm";+import db from "../../../database";+import { externalLinkTable } from "../../../database/schema";++export type CreateExternalLinkParams = {+ taskId: string;+ integrationId: string;+ resourceType: "issue" | "pull_request" | "branch";+ externalId: string;+ url: string;+ title?: string | null;+ metadata?: Record<string, unknown>;+};++export type UpdateExternalLinkParams = {+ title?: string | null;+ url?: string;+ metadata?: Record<string, unknown>;+};++export async function createExternalLink(+ params: CreateExternalLinkParams,+): Promise<{ id: string }> {+ const result = await db+ .insert(externalLinkTable)+ .values({+ taskId: params.taskId,+ integrationId: params.integrationId,+ resourceType: params.resourceType,+ externalId: params.externalId,+ url: params.url,+ title: params.title ?? null,+ metadata: params.metadata ? JSON.stringify(params.metadata) : null,+ })+ .returning({ id: externalLinkTable.id });++ const link = result[0];+ if (!link) {+ throw new Error("Failed to create external link");+ }++ return link;+}++export async function findExternalLink(+ integrationId: string,+ resourceType: string,+ externalId: string,+) {+ return db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.resourceType, resourceType),+ eq(externalLinkTable.externalId, externalId),+ ),+ });+}++export async function findExternalLinkByTaskAndType(+ taskId: string,+ integrationId: string,+ resourceType: string,+) {+ return db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.taskId, taskId),+ eq(externalLinkTable.integrationId, integrationId),+ eq(externalLinkTable.resourceType, resourceType),+ ),+ });+}++export async function findExternalLinksByTask(taskId: string) {+ return db.query.externalLinkTable.findMany({+ where: eq(externalLinkTable.taskId, taskId),+ with: {+ integration: true,+ },+ });+}++export async function updateExternalLink(+ id: string,+ params: UpdateExternalLinkParams,+) {+ const updateData: Record<string, unknown> = {};++ if (params.title !== undefined) {+ updateData.title = params.title;+ }+ if (params.url !== undefined) {+ updateData.url = params.url;+ }+ if (params.metadata !== undefined) {+ updateData.metadata = JSON.stringify(params.metadata);+ }++ if (Object.keys(updateData).length === 0) {+ return;+ }++ await db+ .update(externalLinkTable)+ .set(updateData)+ .where(eq(externalLinkTable.id, id));+}++export async function createOrUpdateExternalLink(+ params: CreateExternalLinkParams,+): Promise<{ id: string; created: boolean }> {+ const existing = await findExternalLink(+ params.integrationId,+ params.resourceType,+ params.externalId,+ );++ if (existing) {+ await updateExternalLink(existing.id, {+ title: params.title,+ url: params.url,+ metadata: params.metadata,+ });+ return { id: existing.id, created: false };+ }++ const link = await createExternalLink(params);+ return { id: link.id, created: true };+}++export async function deleteExternalLink(id: string) {+ await db.delete(externalLinkTable).where(eq(externalLinkTable.id, id));+}++export async function getExternalLinksByIntegration(integrationId: string) {+ return db.query.externalLinkTable.findMany({+ where: eq(externalLinkTable.integrationId, integrationId),+ });+}diff --git a/apps/api/src/plugins/github/services/task-service.ts b/apps/api/src/plugins/github/services/task-service.tsnew file mode 100644index 000000000..2f6daa853--- /dev/null+++ b/apps/api/src/plugins/github/services/task-service.ts@@ -0,0 +1,55 @@+import { and, eq } from "drizzle-orm";+import db from "../../../database";+import { integrationTable, taskTable } from "../../../database/schema";++export async function findTaskByNumber(projectId: string, taskNumber: number) {+ return db.query.taskTable.findFirst({+ where: and(+ eq(taskTable.projectId, projectId),+ eq(taskTable.number, taskNumber),+ ),+ });+}++export async function findTaskById(taskId: string) {+ return db.query.taskTable.findFirst({+ where: eq(taskTable.id, taskId),+ });+}++export async function updateTaskStatus(taskId: string, newStatus: string) {+ await db+ .update(taskTable)+ .set({ status: newStatus })+ .where(eq(taskTable.id, taskId));+}++export async function getIntegrationWithProject(integrationId: string) {+ return db.query.integrationTable.findFirst({+ where: eq(integrationTable.id, integrationId),+ with: {+ project: true,+ },+ });+}++export async function findIntegrationByRepo(owner: string, repo: string) {+ const integrations = await db.query.integrationTable.findMany({+ where: and(+ eq(integrationTable.type, "github"),+ eq(integrationTable.isActive, true),+ ),+ with: {+ project: true,+ },+ });++ return integrations.find((integration) => {+ try {+ const config = JSON.parse(integration.config);+ return config.repositoryOwner === owner && config.repositoryName === repo;+ } catch {+ return false;+ }+ });+}diff --git a/apps/api/src/plugins/github/utils/branch-matcher.ts b/apps/api/src/plugins/github/utils/branch-matcher.tsnew file mode 100644index 000000000..2aeb1f907--- /dev/null+++ b/apps/api/src/plugins/github/utils/branch-matcher.ts@@ -0,0 +1,132 @@+import type { GitHubConfig } from "../config";++function slugify(text: string): string {+ return text+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "")+ .slice(0, 50);+}++export function generateBranchName(+ pattern: string,+ projectSlug: string,+ taskNumber: number,+ taskTitle: string,+): string {+ return pattern+ .replace("{slug}", projectSlug.toLowerCase())+ .replace("{number}", taskNumber.toString())+ .replace("{title}", slugify(taskTitle));+}++export function createBranchRegex(+ pattern: string,+ projectSlug: string,+): RegExp {+ const escapedPattern = pattern.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++ const regexPattern = escapedPattern+ .replace("\\{slug\\}", projectSlug.toLowerCase())+ .replace("\\{number\\}", "(\\d+)")+ .replace("\\{title\\}", "([a-z0-9-]+)");++ return new RegExp(`^${regexPattern}$`, "i");+}++export function extractTaskNumberFromBranch(+ branchName: string,+ config: GitHubConfig,+ projectSlug: string,+): number | null {+ if (config.customBranchRegex) {+ try {+ const customRegex = new RegExp(config.customBranchRegex, "i");+ const match = branchName.match(customRegex);+ if (match?.[1]) {+ const num = Number.parseInt(match[1], 10);+ if (!Number.isNaN(num)) return num;+ }+ } catch {+ console.error("Invalid custom branch regex:", config.customBranchRegex);+ }+ return null;+ }++ const pattern = config.branchPattern || "{slug}-{number}";+ const regex = createBranchRegex(pattern, projectSlug);+ const match = branchName.match(regex);++ if (match?.[1]) {+ const num = Number.parseInt(match[1], 10);+ if (!Number.isNaN(num)) return num;+ }++ return null;+}++export function extractTaskNumberFromPRTitle(title: string): number | null {+ const patterns = [+ /\[(\d+)\]/,+ /#(\d+)/,+ /\((\d+)\)/,+ /^(\d+)[:\-\s]/,+ /task[:\-\s]*(\d+)/i,+ ];++ for (const pattern of patterns) {+ const match = title.match(pattern);+ if (match?.[1]) {+ const num = Number.parseInt(match[1], 10);+ if (!Number.isNaN(num)) return num;+ }+ }++ return null;+}++export function extractTaskNumberFromPRBody(body: string): number | null {+ const patterns = [+ /task[:\-\s#]*(\d+)/i,+ /closes[:\-\s#]*(\d+)/i,+ /fixes[:\-\s#]*(\d+)/i,+ /resolves[:\-\s#]*(\d+)/i,+ ];++ for (const pattern of patterns) {+ const match = body.match(pattern);+ if (match?.[1]) {+ const num = Number.parseInt(match[1], 10);+ if (!Number.isNaN(num)) return num;+ }+ }++ return null;+}++export function extractTaskNumber(+ branchName: string,+ prTitle: string | undefined,+ prBody: string | undefined,+ config: GitHubConfig,+ projectSlug: string,+): number | null {+ const fromBranch = extractTaskNumberFromBranch(+ branchName,+ config,+ projectSlug,+ );+ if (fromBranch) return fromBranch;++ if (prTitle) {+ const fromTitle = extractTaskNumberFromPRTitle(prTitle);+ if (fromTitle) return fromTitle;+ }++ if (prBody) {+ const fromBody = extractTaskNumberFromPRBody(prBody);+ if (fromBody) return fromBody;+ }++ return null;+}diff --git a/apps/api/src/plugins/github/utils/extract-priority.ts b/apps/api/src/plugins/github/utils/extract-priority.tsnew file mode 100644index 000000000..576e1a59a--- /dev/null+++ b/apps/api/src/plugins/github/utils/extract-priority.ts@@ -0,0 +1,58 @@+type GitHubLabel = string | { name?: string };++const VALID_PRIORITIES = ["low", "medium", "high", "urgent"] as const;+const VALID_STATUSES = [+ "to-do",+ "in-progress",+ "in-review",+ "done",+ "planned",+ "archived",+] as const;++export type ValidPriority = (typeof VALID_PRIORITIES)[number];+export type ValidStatus = (typeof VALID_STATUSES)[number];++/**+ * Extract priority from GitHub issue labels.+ * Returns null if no valid priority label found (lets Kaneo use its defaults).+ */+export function extractIssuePriority(+ labels: GitHubLabel[] | undefined,+): ValidPriority | null {+ if (!labels) return null;++ const priorityLabels = labels+ .map((label) => (typeof label === "string" ? label : label?.name))+ .filter((name) => name?.startsWith("priority:"));++ const firstPriorityLabel = priorityLabels[0];+ if (!firstPriorityLabel) return null;++ const priority = firstPriorityLabel.replace("priority:", "");+ return VALID_PRIORITIES.includes(priority as ValidPriority)+ ? (priority as ValidPriority)+ : null;+}++/**+ * Extract status from GitHub issue labels.+ * Returns null if no valid status label found (lets Kaneo use its defaults).+ */+export function extractIssueStatus(+ labels: GitHubLabel[] | undefined,+): ValidStatus | null {+ if (!labels) return null;++ const statusLabels = labels+ .map((label) => (typeof label === "string" ? label : label?.name))+ .filter((name) => name?.startsWith("status:"));++ const firstStatusLabel = statusLabels[0];+ if (!firstStatusLabel) return null;++ const status = firstStatusLabel.replace("status:", "");+ return VALID_STATUSES.includes(status as ValidStatus)+ ? (status as ValidStatus)+ : null;+}diff --git a/apps/api/src/plugins/github/utils/format.ts b/apps/api/src/plugins/github/utils/format.tsnew file mode 100644index 000000000..a3f8aa329--- /dev/null+++ b/apps/api/src/plugins/github/utils/format.ts@@ -0,0 +1,44 @@+export function formatIssueTitle(taskTitle: string): string {+ return taskTitle;+}++export function formatIssueBody(+ taskDescription: string | null,+ taskId: string,+): string {+ const description = taskDescription || "";++ if (!description.trim()) {+ return `<sub>Task: ${taskId}</sub>`;+ }++ return `${description}++---+<sub>Task: ${taskId}</sub>`;+}++export function formatSyncComment(taskId: string): string {+ return `Task: ${taskId}`;+}++export function getLabelsForIssue(+ priority: string | null,+ status: string,+): string[] {+ const labels: string[] = [];++ if (priority && priority !== "no-priority") {+ labels.push(`priority:${priority}`);+ }++ labels.push(`status:${status}`);++ return labels;+}++export function formatTaskDescriptionFromIssue(+ issueBody: string | null,+): string {+ return issueBody || "";+}diff --git a/apps/api/src/plugins/github/utils/github-app.ts b/apps/api/src/plugins/github/utils/github-app.tsnew file mode 100644index 000000000..ee86b734b--- /dev/null+++ b/apps/api/src/plugins/github/utils/github-app.ts@@ -0,0 +1,56 @@+import { config } from "dotenv-mono";+import { App } from "octokit";++config();++let githubAppInstance: App | null = null;++export function getGithubApp(): App | null {+ if (githubAppInstance) {+ return githubAppInstance;+ }++ if (+ !process.env.GITHUB_WEBHOOK_SECRET ||+ !process.env.GITHUB_APP_ID ||+ !process.env.GITHUB_PRIVATE_KEY+ ) {+ return null;+ }++ githubAppInstance = new App({+ appId: process.env.GITHUB_APP_ID ?? "",+ privateKey: process.env.GITHUB_PRIVATE_KEY ?? "",+ webhooks: {+ secret: process.env.GITHUB_WEBHOOK_SECRET ?? "",+ },+ });++ return githubAppInstance;+}++export async function getInstallationOctokit(installationId: number) {+ const app = getGithubApp();+ if (!app) {+ throw new Error("GitHub App not configured");+ }+ return app.getInstallationOctokit(installationId);+}++export async function getInstallationIdForRepo(+ owner: string,+ repo: string,+): Promise<number> {+ const app = getGithubApp();+ if (!app) {+ throw new Error("GitHub App not configured");+ }++ const { data: installation } =+ await app.octokit.rest.apps.getRepoInstallation({+ owner,+ repo,+ });++ return installation.id;+}diff --git a/apps/api/src/plugins/github/utils/labels.ts b/apps/api/src/plugins/github/utils/labels.tsnew file mode 100644index 000000000..dd2343b08--- /dev/null+++ b/apps/api/src/plugins/github/utils/labels.ts@@ -0,0 +1,85 @@+import type { Octokit } from "octokit";++const labelColors: Record<string, string> = {+ "priority:low": "0EA5E9",+ "priority:medium": "EAB308",+ "priority:high": "F97316",+ "priority:urgent": "EF4444",+ "status:to-do": "6B7280",+ "status:in-progress": "3B82F6",+ "status:in-review": "8B5CF6",+ "status:done": "10B981",+ "status:planned": "8B5CF6",+ "status:archived": "6B7280",+};++export function getLabelColor(labelName: string): string {+ return labelColors[labelName] || "6B7280";+}++export async function ensureLabelsExist(+ octokit: Octokit,+ owner: string,+ repo: string,+ labels: string[],+) {+ for (const labelName of labels) {+ try {+ await octokit.rest.issues.getLabel({+ owner,+ repo,+ name: labelName,+ });+ } catch {+ try {+ const color = getLabelColor(labelName);+ await octokit.rest.issues.createLabel({+ owner,+ repo,+ name: labelName,+ color,+ });+ } catch (createError) {+ console.error(`Failed to create label "${labelName}":`, createError);+ }+ }+ }+}++export async function addLabelsToIssue(+ octokit: Octokit,+ owner: string,+ repo: string,+ issueNumber: number,+ labels: string[],+) {+ try {+ await ensureLabelsExist(octokit, owner, repo, labels);++ await octokit.rest.issues.addLabels({+ owner,+ repo,+ issue_number: issueNumber,+ labels,+ });+ } catch (error) {+ console.error("Failed to add labels to issue:", error);+ }+}++export async function removeLabel(+ octokit: Octokit,+ owner: string,+ repo: string,+ issueNumber: number,+ labelName: string,+) {+ try {+ await octokit.rest.issues.removeLabel({+ owner,+ repo,+ issue_number: issueNumber,+ name: labelName,+ });+ } catch {}+}diff --git a/apps/api/src/plugins/github/webhook-handler.ts b/apps/api/src/plugins/github/webhook-handler.tsnew file mode 100644index 000000000..ff22ca0d8--- /dev/null+++ b/apps/api/src/plugins/github/webhook-handler.ts@@ -0,0 +1,78 @@+import { getGithubApp } from "./utils/github-app";+import { handleIssueClosed } from "./webhooks/issue-closed";+import { handleIssueOpened } from "./webhooks/issue-opened";+import { handlePullRequestClosed } from "./webhooks/pull-request-closed";+import { handlePullRequestOpened } from "./webhooks/pull-request-opened";+import { handlePush } from "./webhooks/push";++export async function handleGitHubWebhook(+ body: string,+ signature: string,+ eventName: string,+ deliveryId: string,+): Promise<{ success: boolean; error?: string }> {+ const githubApp = getGithubApp();++ if (!githubApp) {+ return { success: false, error: "GitHub integration not configured" };+ }++ try {+ await githubApp.webhooks.verifyAndReceive({+ id: deliveryId,+ name: eventName as "issues" | "pull_request" | "push",+ signature,+ payload: body,+ });++ return { success: true };+ } catch (error) {+ console.error("Webhook verification failed:", error);+ return {+ success: false,+ error:+ error instanceof Error ? error.message : "Webhook verification failed",+ };+ }+}++export function setupWebhookHandlers() {+ const githubApp = getGithubApp();++ if (!githubApp) {+ console.log("GitHub App not configured, skipping webhook handlers");+ return;+ }++ githubApp.webhooks.on("issues.opened", async ({ payload }) => {+ await handleIssueOpened(payload as Parameters<typeof handleIssueOpened>[0]);+ });++ githubApp.webhooks.on("issues.closed", async ({ payload }) => {+ await handleIssueClosed(payload as Parameters<typeof handleIssueClosed>[0]);+ });++ githubApp.webhooks.on("push", async ({ payload }) => {+ await handlePush(payload as Parameters<typeof handlePush>[0]);+ });++ githubApp.webhooks.on("pull_request.opened", async ({ payload }) => {+ await handlePullRequestOpened(+ payload as Parameters<typeof handlePullRequestOpened>[0],+ );+ });++ githubApp.webhooks.on("pull_request.closed", async ({ payload }) => {+ await handlePullRequestClosed(+ payload as Parameters<typeof handlePullRequestClosed>[0],+ );+ });++ githubApp.webhooks.on("pull_request.reopened", async ({ payload }) => {+ await handlePullRequestOpened(+ payload as Parameters<typeof handlePullRequestOpened>[0],+ );+ });++ console.log("✓ GitHub webhook handlers registered");+}diff --git a/apps/api/src/plugins/github/webhooks/issue-closed.ts b/apps/api/src/plugins/github/webhooks/issue-closed.tsnew file mode 100644index 000000000..15c2bd14b--- /dev/null+++ b/apps/api/src/plugins/github/webhooks/issue-closed.ts@@ -0,0 +1,73 @@+import { and, eq } from "drizzle-orm";+import db from "../../../database";+import { externalLinkTable, taskTable } from "../../../database/schema";+import { updateExternalLink } from "../services/link-manager";+import { findIntegrationByRepo } from "../services/task-service";++type IssueClosedPayload = {+ action: string;+ issue: {+ number: number;+ title: string;+ html_url: string;+ state: string;+ };+ repository: {+ owner: { login: string };+ name: string;+ full_name: string;+ };+};++export async function handleIssueClosed(payload: IssueClosedPayload) {+ const { issue, repository } = payload;++ const integration = await findIntegrationByRepo(+ repository.owner.login,+ repository.name,+ );++ if (!integration) {+ return;+ }++ const externalLink = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "issue"),+ eq(externalLinkTable.externalId, issue.number.toString()),+ ),+ });++ if (!externalLink) {+ return;+ }++ const task = await db.query.taskTable.findFirst({+ where: eq(taskTable.id, externalLink.taskId),+ });++ if (!task) {+ return;+ }++ const existingMetadata = externalLink.metadata+ ? JSON.parse(externalLink.metadata)+ : {};++ if (existingMetadata.createdFrom === "kaneo") {+ return;+ }++ await db+ .update(taskTable)+ .set({ status: "done" })+ .where(eq(taskTable.id, task.id));++ await updateExternalLink(externalLink.id, {+ metadata: {+ ...existingMetadata,+ state: "closed",+ },+ });+}diff --git a/apps/api/src/plugins/github/webhooks/issue-opened.ts b/apps/api/src/plugins/github/webhooks/issue-opened.tsnew file mode 100644index 000000000..08560f384--- /dev/null+++ b/apps/api/src/plugins/github/webhooks/issue-opened.ts@@ -0,0 +1,147 @@+import db from "../../../database";+import { taskTable } from "../../../database/schema";+import getNextTaskNumber from "../../../task/controllers/get-next-task-number";+import type { GitHubConfig } from "../config";+import { createExternalLink, findExternalLink } from "../services/link-manager";+import { findIntegrationByRepo } from "../services/task-service";+import {+ extractIssuePriority,+ extractIssueStatus,+} from "../utils/extract-priority";+import { formatTaskDescriptionFromIssue } from "../utils/format";+import { getGithubApp } from "../utils/github-app";+import { addLabelsToIssue } from "../utils/labels";++type IssueOpenedPayload = {+ action: string;+ issue: {+ number: number;+ title: string;+ body: string | null;+ html_url: string;+ labels?: Array<string | { name?: string }>;+ user: { login: string } | null;+ };+ repository: {+ owner: { login: string };+ name: string;+ full_name: string;+ };+};++export async function handleIssueOpened(payload: IssueOpenedPayload) {+ const githubApp = getGithubApp();+ if (!githubApp) {+ return;+ }++ const { issue, repository } = payload;++ const integration = await findIntegrationByRepo(+ repository.owner.login,+ repository.name,+ );++ if (!integration) {+ return;+ }++ const config = JSON.parse(integration.config) as GitHubConfig;+ const projectId = integration.projectId;++ const priority = extractIssuePriority(issue.labels);+ const status = extractIssueStatus(issue.labels);++ const existingLink = await findExternalLink(+ integration.id,+ "issue",+ issue.number.toString(),+ );++ if (existingLink) {+ console.log(+ `Issue #${issue.number} already linked to task ${existingLink.taskId}, skipping creation`,+ );+ return;+ }++ const nextTaskNumber = await getNextTaskNumber(projectId);++ const taskValues: typeof taskTable.$inferInsert = {+ projectId,+ userId: null,+ title: issue.title,+ description: formatTaskDescriptionFromIssue(issue.body),+ status: "to-do",+ priority: null,+ number: nextTaskNumber + 1,+ };++ if (priority) taskValues.priority = priority;+ if (status) taskValues.status = status;++ const [createdTask] = await db+ .insert(taskTable)+ .values(taskValues)+ .returning();++ if (!createdTask) {+ console.error("Failed to create task from GitHub issue");+ return;+ }++ await createExternalLink({+ taskId: createdTask.id,+ integrationId: integration.id,+ resourceType: "issue",+ externalId: issue.number.toString(),+ url: issue.html_url,+ title: issue.title,+ metadata: {+ state: "open",+ createdFrom: "github",+ author: issue.user?.login,+ },+ });++ try {+ let installationId = config.installationId;+ if (!installationId) {+ const { data: installation } =+ await githubApp.octokit.rest.apps.getRepoInstallation({+ owner: repository.owner.login,+ repo: repository.name,+ });+ installationId = installation.id;+ }++ const octokit = await githubApp.getInstallationOctokit(installationId);++ const existingLabels =+ issue.labels+ ?.map((label) => (typeof label === "string" ? label : label.name))+ .filter(Boolean) || [];++ const labelsToAdd: string[] = [];++ if (priority && !existingLabels.includes(`priority:${priority}`)) {+ labelsToAdd.push(`priority:${priority}`);+ }++ if (status && !existingLabels.includes(`status:${status}`)) {+ labelsToAdd.push(`status:${status}`);+ }++ if (labelsToAdd.length > 0) {+ await addLabelsToIssue(+ octokit,+ repository.owner.login,+ repository.name,+ issue.number,+ labelsToAdd,+ );+ }+ } catch (error) {+ console.error("Failed to add labels to GitHub issue:", error);+ }+}diff --git a/apps/api/src/plugins/github/webhooks/pull-request-closed.ts b/apps/api/src/plugins/github/webhooks/pull-request-closed.tsnew file mode 100644index 000000000..c0a834730--- /dev/null+++ b/apps/api/src/plugins/github/webhooks/pull-request-closed.ts@@ -0,0 +1,80 @@+import { and, eq } from "drizzle-orm";+import db from "../../../database";+import { externalLinkTable } from "../../../database/schema";+import type { GitHubConfig } from "../config";+import { updateExternalLink } from "../services/link-manager";+import {+ findIntegrationByRepo,+ findTaskById,+ updateTaskStatus,+} from "../services/task-service";++type PRClosedPayload = {+ action: string;+ pull_request: {+ number: number;+ title: string;+ html_url: string;+ state: string;+ merged: boolean;+ merged_at: string | null;+ head: {+ ref: string;+ };+ };+ repository: {+ owner: { login: string };+ name: string;+ };+};++export async function handlePullRequestClosed(payload: PRClosedPayload) {+ const { pull_request, repository } = payload;++ const integration = await findIntegrationByRepo(+ repository.owner.login,+ repository.name,+ );++ if (!integration) {+ return;+ }++ const config = JSON.parse(integration.config) as GitHubConfig;++ const externalLink = await db.query.externalLinkTable.findFirst({+ where: and(+ eq(externalLinkTable.integrationId, integration.id),+ eq(externalLinkTable.resourceType, "pull_request"),+ eq(externalLinkTable.externalId, pull_request.number.toString()),+ ),+ });++ if (!externalLink) {+ return;+ }++ const task = await findTaskById(externalLink.taskId);++ if (!task) {+ return;+ }++ const existingMetadata = externalLink.metadata+ ? JSON.parse(externalLink.metadata)+ : {};++ await updateExternalLink(externalLink.id, {+ metadata: {+ ...existingMetadata,+ state: "closed",+ merged: pull_request.merged,+ mergedAt: pull_request.merged_at,+ },+ });++ if (pull_request.merged) {+ const targetStatus = config.statusTransitions?.onPRMerge || "done";+ await updateTaskStatus(task.id, targetStatus);+ }+}diff --git a/apps/api/src/plugins/github/webhooks/pull-request-opened.ts b/apps/api/src/plugins/github/webhooks/pull-request-opened.tsnew file mode 100644index 000000000..6b437f348--- /dev/null+++ b/apps/api/src/plugins/github/webhooks/pull-request-opened.ts@@ -0,0 +1,96 @@+import type { GitHubConfig } from "../config";+import { createExternalLink, findExternalLink } from "../services/link-manager";+import {+ findIntegrationByRepo,+ findTaskByNumber,+ updateTaskStatus,+} from "../services/task-service";+import { extractTaskNumber } from "../utils/branch-matcher";++type PROpenedPayload = {+ action: string;+ pull_request: {+ number: number;+ title: string;+ body: string | null;+ html_url: string;+ state: string;+ draft: boolean;+ merged: boolean;+ head: {+ ref: string;+ };+ user: { login: string } | null;+ };+ repository: {+ owner: { login: string };+ name: string;+ };+};++export async function handlePullRequestOpened(payload: PROpenedPayload) {+ const { pull_request, repository } = payload;++ const integration = await findIntegrationByRepo(+ repository.owner.login,+ repository.name,+ );++ if (!integration || !integration.project) {+ return;+ }++ const config = JSON.parse(integration.config) as GitHubConfig;+ const projectSlug = integration.project.slug;+ const branchName = pull_request.head.ref;++ const taskNumber = extractTaskNumber(+ branchName,+ pull_request.title,+ pull_request.body ?? undefined,+ config,+ projectSlug,+ );++ if (!taskNumber) {+ return;+ }++ const task = await findTaskByNumber(integration.projectId, taskNumber);++ if (!task) {+ return;+ }++ const existingLink = await findExternalLink(+ integration.id,+ "pull_request",+ pull_request.number.toString(),+ );++ if (existingLink) {+ return;+ }++ await createExternalLink({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "pull_request",+ externalId: pull_request.number.toString(),+ url: pull_request.html_url,+ title: pull_request.title,+ metadata: {+ state: pull_request.state,+ draft: pull_request.draft,+ merged: pull_request.merged,+ branch: branchName,+ author: pull_request.user?.login,+ },+ });++ const targetStatus = config.statusTransitions?.onPROpen || "in-review";++ if (task.status !== targetStatus && task.status !== "done") {+ await updateTaskStatus(task.id, targetStatus);+ }+}diff --git a/apps/api/src/plugins/github/webhooks/push.ts b/apps/api/src/plugins/github/webhooks/push.tsnew file mode 100644index 000000000..e0f54f1aa--- /dev/null+++ b/apps/api/src/plugins/github/webhooks/push.ts@@ -0,0 +1,94 @@+import type { GitHubConfig } from "../config";+import { createOrUpdateExternalLink } from "../services/link-manager";+import {+ findIntegrationByRepo,+ findTaskByNumber,+ updateTaskStatus,+} from "../services/task-service";+import { extractTaskNumberFromBranch } from "../utils/branch-matcher";++type PushPayload = {+ ref: string;+ head_commit?: {+ id: string;+ message: string;+ author?: { name: string };+ timestamp: string;+ };+ repository: {+ owner: { login: string };+ name: string;+ html_url: string;+ };+};++const PROTECTED_BRANCHES = [+ "main",+ "master",+ "develop",+ "staging",+ "production",+];++export async function handlePush(payload: PushPayload) {+ const { ref, repository, head_commit } = payload;++ const branchName = ref.replace("refs/heads/", "");++ if (PROTECTED_BRANCHES.includes(branchName)) {+ return;+ }++ const integration = await findIntegrationByRepo(+ repository.owner.login,+ repository.name,+ );++ if (!integration || !integration.project) {+ return;+ }++ const config = JSON.parse(integration.config) as GitHubConfig;+ const projectSlug = integration.project.slug;++ const taskNumber = extractTaskNumberFromBranch(+ branchName,+ config,+ projectSlug,+ );++ if (!taskNumber) {+ return;+ }++ const task = await findTaskByNumber(integration.projectId, taskNumber);++ if (!task) {+ return;+ }++ await createOrUpdateExternalLink({+ taskId: task.id,+ integrationId: integration.id,+ resourceType: "branch",+ externalId: branchName,+ url: `${repository.html_url}/tree/${branchName}`,+ title: branchName,+ metadata: {+ lastCommit: head_commit+ ? {+ sha: head_commit.id,+ message: head_commit.message,+ author: head_commit.author?.name,+ timestamp: head_commit.timestamp,+ }+ : null,+ },+ });++ const targetStatus = config.statusTransitions?.onBranchPush || "in-progress";++ if (task.status !== targetStatus && task.status !== "done") {+ await updateTaskStatus(task.id, targetStatus);+ }+}diff --git a/apps/api/src/plugins/index.ts b/apps/api/src/plugins/index.tsnew file mode 100644index 000000000..552b86ce8--- /dev/null+++ b/apps/api/src/plugins/index.ts@@ -0,0 +1,15 @@+import { githubPlugin, initializeGitHubPlugin } from "./github";+import { initializeEventSubscriptions, registerPlugin } from "./registry";++export function initializePlugins() {+ console.log("Initializing plugins...");++ registerPlugin(githubPlugin);+ initializeGitHubPlugin();+ initializeEventSubscriptions();++ console.log("✅ Plugins initialized");+}++export * from "./registry";+export * from "./types";diff --git a/apps/api/src/plugins/registry.ts b/apps/api/src/plugins/registry.tsnew file mode 100644index 000000000..c225977f7--- /dev/null+++ b/apps/api/src/plugins/registry.ts@@ -0,0 +1,184 @@+import { and, eq } from "drizzle-orm";+import db from "../database";+import { integrationTable } from "../database/schema";+import { subscribeToEvent } from "../events";+import type {+ IntegrationPlugin,+ PluginContext,+ TaskCreatedEvent,+ TaskPriorityChangedEvent,+ TaskStatusChangedEvent,+} from "./types";++const plugins = new Map<string, IntegrationPlugin>();+let eventSubscriptionsInitialized = false;++export function registerPlugin(plugin: IntegrationPlugin): void {+ if (plugins.has(plugin.type)) {+ throw new Error(`Plugin ${plugin.type} already registered`);+ }+ plugins.set(plugin.type, plugin);+ console.log(`✓ Registered plugin: ${plugin.name}`);+}++export function initializeEventSubscriptions(): void {+ if (eventSubscriptionsInitialized) {+ return;+ }++ subscribeToEvent<{+ taskId: string;+ userId: string;+ title: string;+ description: string;+ priority: string;+ status: string;+ number: number;+ projectId: string;+ }>("task.created", async (data) => {+ await broadcastTaskCreated({+ taskId: data.taskId,+ projectId: data.projectId,+ userId: data.userId,+ title: data.title,+ description: data.description,+ priority: data.priority,+ status: data.status,+ number: data.number,+ });+ });++ subscribeToEvent<{+ taskId: string;+ userId: string | null;+ oldStatus: string;+ newStatus: string;+ title: string;+ projectId: string;+ }>("task.status_changed", async (data) => {+ await broadcastTaskStatusChanged({+ taskId: data.taskId,+ projectId: data.projectId,+ userId: data.userId,+ oldStatus: data.oldStatus,+ newStatus: data.newStatus,+ title: data.title,+ });+ });++ subscribeToEvent<{+ taskId: string;+ userId: string | null;+ oldPriority: string;+ newPriority: string;+ title: string;+ projectId: string;+ }>("task.priority_changed", async (data) => {+ await broadcastTaskPriorityChanged({+ taskId: data.taskId,+ projectId: data.projectId,+ userId: data.userId,+ oldPriority: data.oldPriority,+ newPriority: data.newPriority,+ title: data.title,+ });+ });++ eventSubscriptionsInitialized = true;+ console.log("✓ Plugin event subscriptions initialized");+}++export function getPlugin(type: string): IntegrationPlugin | undefined {+ return plugins.get(type);+}++export function listPlugins(): IntegrationPlugin[] {+ return Array.from(plugins.values());+}++async function getActiveIntegrations(projectId: string) {+ return db.query.integrationTable.findMany({+ where: and(+ eq(integrationTable.projectId, projectId),+ eq(integrationTable.isActive, true),+ ),+ with: {+ project: true,+ },+ });+}++function createContext(integration: {+ id: string;+ projectId: string;+ config: string;+}): PluginContext {+ return {+ integrationId: integration.id,+ projectId: integration.projectId,+ config: JSON.parse(integration.config) as Record<string, unknown>,+ };+}++export async function broadcastTaskCreated(+ event: TaskCreatedEvent,+): Promise<void> {+ const integrations = await getActiveIntegrations(event.projectId);++ for (const integration of integrations) {+ const plugin = getPlugin(integration.type);+ if (!plugin?.onTaskCreated) continue;++ const context = createContext(integration);++ try {+ await plugin.onTaskCreated(event, context);+ } catch (error) {+ console.error(`Plugin ${plugin.type} error on task.created:`, error);+ }+ }+}++export async function broadcastTaskStatusChanged(+ event: TaskStatusChangedEvent,+): Promise<void> {+ const integrations = await getActiveIntegrations(event.projectId);++ for (const integration of integrations) {+ const plugin = getPlugin(integration.type);+ if (!plugin?.onTaskStatusChanged) continue;++ const context = createContext(integration);++ try {+ await plugin.onTaskStatusChanged(event, context);+ } catch (error) {+ console.error(+ `Plugin ${plugin.type} error on task.status_changed:`,+ error,+ );+ }+ }+}++export async function broadcastTaskPriorityChanged(+ event: TaskPriorityChangedEvent,+): Promise<void> {+ const integrations = await getActiveIntegrations(event.projectId);++ for (const integration of integrations) {+ const plugin = getPlugin(integration.type);+ if (!plugin?.onTaskPriorityChanged) continue;++ const context = createContext(integration);++ try {+ await plugin.onTaskPriorityChanged(event, context);+ } catch (error) {+ console.error(+ `Plugin ${plugin.type} error on task.priority_changed:`,+ error,+ );+ }+ }+}diff --git a/apps/api/src/plugins/types.ts b/apps/api/src/plugins/types.tsnew file mode 100644index 000000000..b2854696a--- /dev/null+++ b/apps/api/src/plugins/types.ts@@ -0,0 +1,81 @@+export type PluginContext = {+ integrationId: string;+ projectId: string;+ config: Record<string, unknown>;+};++export type TaskCreatedEvent = {+ taskId: string;+ projectId: string;+ userId: string;+ title: string;+ description: string | null;+ priority: string | null;+ status: string;+ number: number;+};++export type TaskStatusChangedEvent = {+ taskId: string;+ projectId: string;+ userId: string | null;+ oldStatus: string;+ newStatus: string;+ title: string;+};++export type TaskPriorityChangedEvent = {+ taskId: string;+ projectId: string;+ userId: string | null;+ oldPriority: string;+ newPriority: string;+ title: string;+};++export type TaskEvent =+ | TaskCreatedEvent+ | TaskStatusChangedEvent+ | TaskPriorityChangedEvent;++export type ExternalMetadata = {+ type: "issue" | "pull_request" | "branch";+ id: string;+ externalId: string;+ title: string | null;+ url: string;+ status: string;+ metadata: Record<string, unknown>;+};++export type TaskEventHandler<T extends TaskEvent = TaskEvent> = (+ event: T,+ context: PluginContext,+) => Promise<void>;++export type WebhookHandler = (+ payload: unknown,+ headers: Record<string, string>,+) => Promise<void>;++export type MetadataProvider = (+ taskId: string,+ context: PluginContext,+) => Promise<ExternalMetadata[]>;++export type ConfigValidator = (+ config: unknown,+) => Promise<{ valid: boolean; errors?: string[] }>;++export type IntegrationPlugin = {+ type: string;+ name: string;++ onTaskCreated?: TaskEventHandler<TaskCreatedEvent>;+ onTaskStatusChanged?: TaskEventHandler<TaskStatusChangedEvent>;+ onTaskPriorityChanged?: TaskEventHandler<TaskPriorityChangedEvent>;++ handleWebhook?: WebhookHandler;+ getTaskMetadata?: MetadataProvider;+ validateConfig: ConfigValidator;+};diff --git a/apps/api/src/task/index.ts b/apps/api/src/task/index.tsindex 51e9bb9a3..df34e7ce3 100644--- a/apps/api/src/task/index.ts+++ b/apps/api/src/task/index.ts@@ -178,6 +178,7 @@ const task = new Hono<{const user = c.get("userId");await publishEvent("task.status_changed", {taskId: task.id,+ projectId: task.projectId,userId: user,oldStatus: task.status,newStatus: status,@@ -308,6 +309,7 @@ const task = new Hono<{await publishEvent("task.status_changed", {taskId: task.id,+ projectId: task.projectId,userId: user,oldStatus: task.status,newStatus: status,@@ -346,6 +348,7 @@ const task = new Hono<{await publishEvent("task.priority_changed", {taskId: task.id,+ projectId: task.projectId,userId: user,oldPriority: task.priority,newPriority: priority,diff --git a/apps/docs/next-env.d.ts b/apps/docs/next-env.d.tsindex 9edff1c7c..c4b7818fb 100644--- a/apps/docs/next-env.d.ts+++ b/apps/docs/next-env.d.ts@@ -1,6 +1,6 @@/// <reference types="next" />/// <reference types="next/image-types/global" />-import "./.next/types/routes.d.ts";+import "./.next/dev/types/routes.d.ts";// NOTE: This file should not be edited// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.diff --git a/apps/web/src/components/kanban-board/task-card.tsx b/apps/web/src/components/kanban-board/task-card.tsxindex 7f52e0028..4c9ce5957 100644--- a/apps/web/src/components/kanban-board/task-card.tsx+++ b/apps/web/src/components/kanban-board/task-card.tsx@@ -2,7 +2,12 @@ import { useSortable } from "@dnd-kit/sortable";import { CSS } from "@dnd-kit/utilities";import { useNavigate } from "@tanstack/react-router";import { format } from "date-fns";-import { Calendar, CalendarClock, CalendarX } from "lucide-react";+import {+ Calendar,+ CalendarClock,+ CalendarX,+ GitPullRequest,+} from "lucide-react";import { type CSSProperties, useMemo, useState } from "react";import { toast } from "sonner";import {@@ -17,6 +22,7 @@ import {} from "@/components/ui/alert-dialog";import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";import { useDeleteTask } from "@/hooks/mutations/task/use-delete-task";+import useExternalLinks from "@/hooks/queries/external-link/use-external-links";import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";import { dueDateStatusColors, getDueDateStatus } from "@/lib/due-date-status";@@ -54,6 +60,15 @@ function TaskCard({ task }: TaskCardProps) {} = useUserPreferencesStore();const [isDeleteTaskModalOpen, setIsDeleteTaskModalOpen] = useState(false);const { mutateAsync: deleteTask } = useDeleteTask();+ const { data: externalLinks } = useExternalLinks(task.id);++ const activePullRequest = useMemo(() => {+ if (!externalLinks) return null;+ return externalLinks.find(+ (link) =>+ link.resourceType === "pull_request" && link.metadata?.merged !== true,+ );+ }, [externalLinks]);const style: CSSProperties = {transform: CSS.Transform.toString(transform),@@ -194,6 +209,21 @@ function TaskCard({ task }: TaskCardProps) {<span>{format(new Date(task.dueDate), "MMM d")}</span></div>)}++ {activePullRequest && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ window.open(activePullRequest.url, "_blank");+ }}+ className="inline-flex items-center gap-1 px-2 py-1 rounded border border-violet-200 bg-violet-50 text-[10px] font-medium text-violet-700 hover:bg-violet-100 hover:border-violet-300 transition-colors dark:bg-violet-950/50 dark:border-violet-800 dark:text-violet-300 dark:hover:bg-violet-900/50"+ title={activePullRequest.title || "Open Pull Request"}+ >+ <GitPullRequest className="w-3 h-3" />+ <span>#{activePullRequest.externalId}</span>+ </button>+ )}</div></div></ContextMenuTrigger>diff --git a/apps/web/src/fetchers/external-link/get-external-links.ts b/apps/web/src/fetchers/external-link/get-external-links.tsnew file mode 100644index 000000000..5ca6f02d4--- /dev/null+++ b/apps/web/src/fetchers/external-link/get-external-links.ts@@ -0,0 +1,18 @@+import type { ExternalLink } from "@/types/external-link";++async function getExternalLinks(taskId: string): Promise<ExternalLink[]> {+ const response = await fetch(+ `${import.meta.env.VITE_API_URL || "http://localhost:1337"}/api/external-link/task/${taskId}`,+ {+ credentials: "include",+ },+ );++ if (!response.ok) {+ throw new Error("Failed to fetch external links");+ }++ return response.json();+}++export default getExternalLinks;diff --git a/apps/web/src/hooks/queries/external-link/use-external-links.ts b/apps/web/src/hooks/queries/external-link/use-external-links.tsnew file mode 100644index 000000000..b12fc7ef3--- /dev/null+++ b/apps/web/src/hooks/queries/external-link/use-external-links.ts@@ -0,0 +1,12 @@+import { useQuery } from "@tanstack/react-query";+import getExternalLinks from "@/fetchers/external-link/get-external-links";++function useExternalLinks(taskId: string) {+ return useQuery({+ queryKey: ["external-links", taskId],+ queryFn: () => getExternalLinks(taskId),+ enabled: !!taskId,+ });+}++export default useExternalLinks;diff --git a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId_.tsx b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId_.tsxindex 881dab139..907dbd97b 100644--- a/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId_.tsx+++ b/apps/web/src/routes/_layout/_authenticated/dashboard/workspace/$workspaceId/project/$projectId/task/$taskId_.tsx@@ -4,8 +4,10 @@ import {Calendar,CalendarClock,CalendarX,+ CircleDot,Copy,GitBranch,+ GitPullRequest,Plus,} from "lucide-react";import { toast } from "sonner";@@ -33,10 +35,11 @@ import {} from "@/components/ui/tooltip";import labelColors from "@/constants/label-colors";import useGetActivitiesByTaskId from "@/hooks/queries/activity/use-get-activities-by-task-id";+import useExternalLinks from "@/hooks/queries/external-link/use-external-links";+import useGetGithubIntegration from "@/hooks/queries/github-integration/use-get-github-integration";import useGetLabelsByTask from "@/hooks/queries/label/use-get-labels-by-task";import useGetProject from "@/hooks/queries/project/use-get-project";import useGetTask from "@/hooks/queries/task/use-get-task";-import useActiveWorkspace from "@/hooks/queries/workspace/use-active-workspace";import { useGetActiveWorkspaceUsers } from "@/hooks/queries/workspace-users/use-get-active-workspace-users";import { getColumnIcon } from "@/lib/column";import { dueDateStatusColors, getDueDateStatus } from "@/lib/due-date-status";@@ -48,8 +51,26 @@ export const Route = createFileRoute(component: RouteComponent,});-function toKebabCase(str: string | undefined) {- return str?.replace(/ /g, "-").toLowerCase().replace(/^-|-$/g, "");+function slugify(text: string | undefined): string {+ if (!text) return "";+ return text+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-|-$/g, "")+ .slice(0, 50);+}++function generateBranchName(+ pattern: string,+ projectSlug: string | undefined,+ taskNumber: number | undefined,+ taskTitle: string | undefined,+): string {+ if (!projectSlug || !taskNumber) return "";+ return pattern+ .replace("{slug}", projectSlug.toLowerCase())+ .replace("{number}", taskNumber.toString())+ .replace("{title}", slugify(taskTitle));}function toNormalCase(str: string | undefined) {@@ -65,14 +86,16 @@ function RouteComponent() {const { projectId, workspaceId, taskId } = Route.useParams();const { data: task } = useGetTask(taskId);const { data: project } = useGetProject({ id: projectId, workspaceId });- const { data: workspace } = useActiveWorkspace();const { data: workspaceUsers } = useGetActiveWorkspaceUsers(workspaceId);const { data: taskLabels = [] } = useGetLabelsByTask(taskId);const { data: activities = [] } = useGetActivitiesByTaskId(taskId);+ const { data: externalLinks = [], isLoading: isLoadingExternalLinks } =+ useExternalLinks(taskId);+ const { data: githubIntegration } = useGetGithubIntegration(projectId);const { user } = useAuth();- const workspaceName = workspace?.name;const projectSlug = project?.slug;const taskNumber = task?.number;+ const branchPattern = githubIntegration?.branchPattern || "{slug}-{number}";const assignee = workspaceUsers?.members?.find((member) => member.userId === task?.userId,@@ -86,9 +109,13 @@ function RouteComponent() {};const handleCopyTaskBranch = () => {- navigator.clipboard.writeText(- `${toKebabCase(workspaceName)}/${toKebabCase(projectSlug)}-${taskNumber}`,+ const branchName = generateBranchName(+ branchPattern,+ projectSlug,+ taskNumber,+ task?.title,);+ navigator.clipboard.writeText(branchName);toast.message("Task branch copied to clipboard");};@@ -300,6 +327,73 @@ function RouteComponent() {)}</div></div>+ {!isLoadingExternalLinks && (+ <div className="flex flex-col gap-1">+ <div className="flex items-center justify-between">+ <span className="text-xs font-medium text-muted-foreground pl-2">+ External Links+ </span>+ </div>+ <div className="flex flex-col gap-1.5 px-2">+ {externalLinks.length === 0 ? (+ <span className="text-xs text-muted-foreground/70 py-1">+ No linked resources+ </span>+ ) : (+ externalLinks.map((link) => {+ const isMerged = link.metadata?.merged === true;+ const isPR = link.resourceType === "pull_request";+ const isBranch = link.resourceType === "branch";+ const isIssue = link.resourceType === "issue";++ const getIcon = () => {+ if (isPR)+ return (+ <GitPullRequest+ className={`size-3.5 flex-shrink-0 ${isMerged ? "text-emerald-500" : "text-violet-500"}`}+ />+ );+ if (isBranch)+ return (+ <GitBranch className="size-3.5 flex-shrink-0 text-sky-500" />+ );+ return (+ <CircleDot className="size-3.5 flex-shrink-0 text-muted-foreground" />+ );+ };++ const getLabel = () => {+ if (link.title) return link.title;+ if (isPR) return `PR #${link.externalId}`;+ if (isIssue) return `Issue #${link.externalId}`;+ if (isBranch) return link.externalId;+ return link.externalId;+ };++ return (+ <a+ key={link.id}+ href={link.url}+ target="_blank"+ rel="noopener noreferrer"+ className="group flex items-center gap-2 py-1.5 px-2 -mx-2 rounded-md hover:bg-accent/50 transition-colors"+ >+ {getIcon()}+ <span className="text-xs truncate flex-1 text-foreground/80 group-hover:text-foreground">+ {getLabel()}+ </span>+ {isPR && isMerged && (+ <span className="text-[10px] font-medium text-emerald-500/80 bg-emerald-500/10 px-1.5 py-0.5 rounded">+ merged+ </span>+ )}+ </a>+ );+ })+ )}+ </div>+ </div>+ )}</div></div>}diff --git a/apps/web/src/types/external-link/index.ts b/apps/web/src/types/external-link/index.tsnew file mode 100644index 000000000..9f3ed949e--- /dev/null+++ b/apps/web/src/types/external-link/index.ts@@ -0,0 +1,33 @@+export type ExternalLinkMetadata = {+ state?: string;+ merged?: boolean;+ mergedAt?: string;+ draft?: boolean;+ branch?: string;+ author?: string;+ createdFrom?: "github" | "kaneo";+ lastCommit?: {+ sha: string;+ message: string;+ author?: string;+ timestamp: string;+ };+};++export type ExternalLink = {+ id: string;+ taskId: string;+ integrationId: string;+ resourceType: "issue" | "pull_request" | "branch";+ externalId: string;+ url: string;+ title: string | null;+ metadata: ExternalLinkMetadata | null;+ createdAt: string;+ updatedAt: string;+ integration?: {+ id: string;+ type: string;+ config: string;+ };+};