All files / src/entities/workitems registry.ts

94.66% Statements 284/300
84.98% Branches 249/293
100% Functions 18/18
94.79% Lines 273/288

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 114115x 15x 15x   15x 15x 15x 15x           15x 15x                       15x                                                                                                                                                                             15x       12x   11x                             11x 2x             11x 11x   11x   8x   8x   1x 1x   1x             1x   1x 1x   1x             1x   1x 1x                 1x   2x 2x                         2x   3x 2x           3x       11x 6x       11x                 15x                           29x     21x       21x     15x 15x   15x                   15x 15x     15x     15x               14x 14x 14x       14x   14x     14x 13x     14x         14x 12x 12x     14x     14x                 6x     6x 6x     6x   4x         4x         4x 2x         2x     2x   2x     2x     2x   2x 1x     1x                                                           65x     59x       59x                                         22x 22x 22x 22x     22x                             22x 1x   22x 1x   22x 22x 1x                             21x 21x     21x 21x   35x       21x 1x 3x         20x             20x 1x       20x 1x     20x 1x     20x 1x       20x 1x 1x 1x 1x       20x 2x 2x 1x   2x 1x                 20x 1x       20x 1x           20x 1x       20x 1x       20x 1x       20x       20x       1x         19x 1x     18x         18x 4x 4x         4x       3x         1x     1x                             2x   1x           1x     1x                             1x     1x                                     14x                                                           27x 27x     27x             27x       2x               25x                                           25x 25x 1x                             24x 24x     24x     24x     24x 24x     24x 1x     24x 1x             24x     1x   1x           1x 2x   1x       2x 2x     1x 1x 1x 1x   1x 1x     23x   4x 4x 3x   4x 3x           24x 3x 3x 5x   3x 1x           23x 1x       23x 2x 2x 2x 2x       23x 2x 2x   1x     2x 1x         23x       2x           21x 1x 1x 1x   1x 1x                 21x 1x       21x 1x           21x 1x       21x 1x       21x 1x       21x   21x       1x         20x 1x     19x         19x                                                                                                                                                                 19x       4x     4x 4x     4x     4x   3x       1x           2x       3x   3x 3x   3x               3x       1x         2x 1x     1x           3x   3x 3x       3x             3x       1x         2x 1x     1x                                 15x 23x           15x 7x           15x 6x 4x 4x 8x     2x    
import * as z from "zod";
import { BrowseWorkItemsSchema } from "./schema-readonly";
import { ManageWorkItemSchema } from "./schema";
import { ToolRegistry, EnhancedToolDefinition } from "../../types";
import { ConnectionManager } from "../../services/ConnectionManager";
import { isActionDenied } from "../../config";
import { getWorkItemTypes } from "../../utils/workItemTypes";
import {
  cleanWorkItemResponse,
  toGid,
  toGids,
  type GitLabWorkItem,
} from "../../utils/idConversion";
import { WidgetAvailability } from "../../services/WidgetAvailability";
import {
  createVersionRestrictedError,
  normalizeTier,
  StructuredToolError,
} from "../../utils/error-handler";
 
// Define interface for work item type objects
interface WorkItemType {
  id: string;
  name: string;
}
 
import {
  CREATE_WORK_ITEM_WITH_WIDGETS,
  WorkItemCreateInput,
  GET_NAMESPACE_WORK_ITEMS,
  GET_WORK_ITEM,
  GET_WORK_ITEM_BY_IID,
  UPDATE_WORK_ITEM,
  DELETE_WORK_ITEM,
  WORK_ITEM_ADD_LINKED_ITEMS,
  WORK_ITEM_REMOVE_LINKED_ITEMS,
  WorkItemUpdateInput,
  WorkItem as GraphQLWorkItem,
} from "../../graphql/workItems";
 
// Types for work item structure - flexible widget interface for runtime processing
interface FlexibleWorkItemWidget {
  type: string;
  assignees?: {
    nodes?: Array<{
      id: string;
      username: string;
      name: string;
    }>;
  };
  labels?: {
    nodes?: Array<{
      id: string;
      title: string;
      color: string;
    }>;
  };
  milestone?: {
    id: string;
    title: string;
    state: string;
  };
  parent?: {
    id: string;
    iid: string;
    title: string;
    workItemType: string;
  };
  hasChildren?: boolean;
  timeEstimate?: number;
  totalTimeSpent?: number;
}
 
interface SimplifiedWorkItem {
  id: string;
  iid: string;
  title: string;
  state: string;
  workItemType: string;
  webUrl: string;
  createdAt: string;
  updatedAt: string;
  description?: string;
  widgets?: Array<{
    type: string;
    assignees?: Array<{
      id: string;
      username: string;
      name: string;
    }>;
    labels?: Array<{
      id: string;
      title: string;
      color: string;
    }>;
    milestone?: {
      id: string;
      title: string;
      state: string;
    };
    parent?: {
      id: string;
      iid: string;
      title: string;
      workItemType: string;
    } | null;
    hasChildren?: boolean;
    timeEstimate?: number;
    totalTimeSpent?: number;
  }>;
}
 
// Function to simplify work item structure for agent consumption
const simplifyWorkItem = (
  workItem: GraphQLWorkItem,
  simple: boolean
): GraphQLWorkItem | SimplifiedWorkItem => {
  if (!simple) return workItem;
 
  const simplified: SimplifiedWorkItem = {
    id: workItem.id,
    iid: workItem.iid,
    title: workItem.title,
    state: workItem.state,
    workItemType:
      typeof workItem.workItemType === "string"
        ? workItem.workItemType
        : workItem.workItemType?.name || "Unknown",
    webUrl: workItem.webUrl,
    createdAt: workItem.createdAt,
    updatedAt: workItem.updatedAt,
  };
 
  // Add description if it exists and is not too long
  if (workItem.description && typeof workItem.description === "string") {
    simplified.description =
      workItem.description.length > 200
        ? workItem.description.substring(0, 200) + "..."
        : workItem.description;
  }
 
  // Extract essential widgets only
  Eif (workItem.widgets && Array.isArray(workItem.widgets)) {
    const essentialWidgets: SimplifiedWorkItem["widgets"] = [];
 
    for (const widget of workItem.widgets) {
      // Use type assertion to access widget properties dynamically
      const flexWidget = widget as unknown as FlexibleWorkItemWidget;
 
      switch (flexWidget.type) {
        case "ASSIGNEES":
          Eif (flexWidget.assignees?.nodes && flexWidget.assignees.nodes.length > 0) {
            essentialWidgets.push({
              type: "ASSIGNEES",
              assignees: flexWidget.assignees.nodes.map(assignee => ({
                id: assignee.id,
                username: assignee.username,
                name: assignee.name,
              })),
            });
          }
          break;
        case "LABELS":
          Eif (flexWidget.labels?.nodes && flexWidget.labels.nodes.length > 0) {
            essentialWidgets.push({
              type: "LABELS",
              labels: flexWidget.labels.nodes.map(label => ({
                id: label.id,
                title: label.title,
                color: label.color,
              })),
            });
          }
          break;
        case "MILESTONE":
          Eif (flexWidget.milestone) {
            essentialWidgets.push({
              type: "MILESTONE",
              milestone: {
                id: flexWidget.milestone.id,
                title: flexWidget.milestone.title,
                state: flexWidget.milestone.state,
              },
            });
          }
          break;
        case "HIERARCHY":
          Eif (flexWidget.parent || flexWidget.hasChildren) {
            essentialWidgets.push({
              type: "HIERARCHY",
              parent: flexWidget.parent
                ? {
                    id: flexWidget.parent.id,
                    iid: flexWidget.parent.iid,
                    title: flexWidget.parent.title,
                    workItemType: flexWidget.parent.workItemType,
                  }
                : null,
              hasChildren: flexWidget.hasChildren,
            });
          }
          break;
        case "TIME_TRACKING":
          if (flexWidget.timeEstimate !== undefined || flexWidget.totalTimeSpent !== undefined) {
            essentialWidgets.push({
              type: "TIME_TRACKING",
              timeEstimate: flexWidget.timeEstimate,
              totalTimeSpent: flexWidget.totalTimeSpent,
            });
          }
          break;
      }
    }
 
    if (essentialWidgets && essentialWidgets.length > 0) {
      simplified.widgets = essentialWidgets;
    }
  }
 
  return simplified;
};
 
/**
 * Work items tools registry - 2 CQRS tools replacing 5 individual tools
 *
 * browse_work_items (Query): list, get
 * manage_work_item (Command): create, update, delete
 */
export const workitemsToolRegistry: ToolRegistry = new Map<string, EnhancedToolDefinition>([
  // ============================================================================
  // browse_work_items - CQRS Query Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "browse_work_items",
    {
      name: "browse_work_items",
      description:
        "Find and inspect issues, epics, tasks, and other work items. Actions: list (groups return epics, projects return issues/tasks, filter by type/state/labels), get (by numeric ID or namespace+iid from URL path). Related: manage_work_item to create/update/delete.",
      inputSchema: z.toJSONSchema(BrowseWorkItemsSchema),
      gate: { envVar: "USE_WORKITEMS", defaultValue: true },
      handler: async (args: unknown): Promise<unknown> => {
        const input = BrowseWorkItemsSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("browse_work_items", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for browse_work_items tool`);
        }
 
        switch (input.action) {
          case "list": {
            // TypeScript knows: input has namespace (required), types, state, first, after, simple (optional)
            const { namespace, types, state, first, after, simple } = input;
            const namespacePath = namespace;
 
            console.log("browse_work_items list called with:", {
              namespace: namespacePath,
              types,
              state,
              first,
              after,
              simple,
            });
 
            // Get GraphQL client from ConnectionManager
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            // For the work items GraphQL query, use type names as-is (GraphQL expects enum values)
            const resolvedTypes: string[] | undefined = types;
 
            // Query the namespace (works for both groups and projects)
            const workItemsResponse = await client.request(GET_NAMESPACE_WORK_ITEMS, {
              namespacePath,
              types: resolvedTypes,
              first: first || 20,
              after: after,
            });
 
            // Extract work items and pagination info from namespace response
            const workItemsData = workItemsResponse.namespace?.workItems;
            const allItems = workItemsData?.nodes ?? [];
            const pageInfo = {
              hasNextPage: workItemsData?.pageInfo?.hasNextPage ?? false,
              endCursor: workItemsData?.pageInfo?.endCursor ?? null,
            };
            const namespaceType = workItemsResponse.namespace?.__typename ?? "Unknown";
 
            console.log(`Found ${allItems.length} work items from ${namespaceType} query`);
 
            // Apply state filtering (client-side since GitLab API doesn't support it reliably)
            const filteredItems = allItems.filter((item: GraphQLWorkItem) => {
              return state.includes(item.state as "OPEN" | "CLOSED");
            });
 
            console.log(
              `State filtering: ${allItems.length} -> ${filteredItems.length} items (keeping: ${state.join(", ")})`
            );
 
            // Apply simplification if requested and clean GIDs
            const finalResults = filteredItems.map((item: GraphQLWorkItem) => {
              const cleanedItem = cleanWorkItemResponse(item as unknown as GitLabWorkItem);
              return simplifyWorkItem(cleanedItem as GraphQLWorkItem, simple);
            });
 
            console.log("Final result - total work items found:", finalResults.length);
 
            // Return object with items and server-side pagination info
            return {
              items: finalResults,
              hasMore: pageInfo.hasNextPage ?? false,
              endCursor: pageInfo.endCursor ?? null,
            };
          }
 
          case "get": {
            // TypeScript knows: input has either (namespace + iid) or (id)
            const { namespace, iid, id } = input;
 
            // Get GraphQL client from ConnectionManager
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            // Route to appropriate query based on input
            if (namespace !== undefined && iid !== undefined) {
              // Lookup by namespace + IID (preferred for URL-based requests)
              console.log("browse_work_items get by IID called with:", {
                namespace,
                iid,
              });
 
              const response = await client.request(GET_WORK_ITEM_BY_IID, {
                namespacePath: namespace,
                iid: iid,
              });
 
              if (!response.namespace?.workItem) {
                throw new Error(
                  `Work item with IID "${iid}" not found in namespace "${namespace}"`
                );
              }
 
              return cleanWorkItemResponse(
                response.namespace.workItem as unknown as GitLabWorkItem
              );
            } else if (id !== undefined) {
              // Lookup by global ID (backward compatible)
              console.log("browse_work_items get by ID called with:", { id });
 
              // Convert simple ID to GID for API call
              const workItemGid = toGid(id, "WorkItem");
 
              // Use GraphQL query for getting work item details
              const response = await client.request(GET_WORK_ITEM, { id: workItemGid });
 
              if (!response.workItem) {
                throw new Error(`Work item with ID "${id}" not found`);
              }
 
              return cleanWorkItemResponse(response.workItem as unknown as GitLabWorkItem);
            } else E{
              // This should never happen due to schema validation
              throw new Error(
                "Either 'id' (global ID) or both 'namespace' and 'iid' (from URL) must be provided"
              );
            }
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
 
  // ============================================================================
  // manage_work_item - CQRS Command Tool (discriminated union schema)
  // TypeScript automatically narrows types in each switch case
  // ============================================================================
  [
    "manage_work_item",
    {
      name: "manage_work_item",
      description:
        "Create, update, delete, or link work items (issues, epics, tasks). Actions: create (epics need GROUP namespace, issues/tasks need PROJECT), update (widgets: dates, time tracking, weight, iterations, health, progress, hierarchy), delete (permanent), add_link/remove_link (BLOCKS/BLOCKED_BY/RELATED). Related: browse_work_items for discovery.",
      inputSchema: z.toJSONSchema(ManageWorkItemSchema),
      gate: { envVar: "USE_WORKITEMS", defaultValue: true },
      handler: async (args: unknown): Promise<unknown> => {
        const input = ManageWorkItemSchema.parse(args);
 
        // Runtime validation: reject denied actions even if they bypass schema filtering
        Iif (isActionDenied("manage_work_item", input.action)) {
          throw new Error(`Action '${input.action}' is not allowed for manage_work_item tool`);
        }
 
        switch (input.action) {
          case "create": {
            const {
              namespace,
              title,
              workItemType,
              description,
              assigneeIds,
              labelIds,
              milestoneId,
              startDate,
              dueDate,
              parentId,
              childrenIds,
              timeEstimate,
              isFixed,
              weight,
              iterationId,
              progressCurrentValue,
              healthStatus,
              color,
            } = input;
            const namespacePath = namespace;
            const workItemTitle = title;
            const workItemTypeName = workItemType;
 
            // Validate widget parameters against instance version/tier.
            const widgetParams: Record<string, unknown> = {
              description,
              milestoneId,
              startDate,
              dueDate,
              parentId,
              childrenIds,
              timeEstimate,
              isFixed,
              weight,
              iterationId,
              progressCurrentValue,
              healthStatus,
              color,
            };
            if (assigneeIds && assigneeIds.length > 0) {
              widgetParams.assigneeIds = assigneeIds;
            }
            if (labelIds && labelIds.length > 0) {
              widgetParams.labelIds = labelIds;
            }
            const validationFailure = WidgetAvailability.validateWidgetParams(widgetParams);
            if (validationFailure) {
              throw new StructuredToolError(
                createVersionRestrictedError(
                  "manage_work_item",
                  "create",
                  validationFailure.widget,
                  validationFailure.parameter,
                  validationFailure.requiredVersion,
                  validationFailure.detectedVersion,
                  normalizeTier(validationFailure.requiredTier),
                  normalizeTier(validationFailure.currentTier)
                )
              );
            }
 
            // Get GraphQL client from ConnectionManager
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            // Convert simple type name to work item type GID
            const workItemTypes = await getWorkItemTypes(namespacePath);
            const workItemTypeObj = workItemTypes.find(
              (t: WorkItemType) =>
                t.name.toUpperCase().replace(/\s+/g, "_") ===
                workItemTypeName.toUpperCase().replace(/\s+/g, "_")
            );
 
            if (!workItemTypeObj) {
              throw new Error(
                `Work item type "${workItemTypeName}" not found in namespace "${namespacePath}". Available types: ${workItemTypes.map(t => t.name).join(", ")}`
              );
            }
 
            // Build input with widgets support for GitLab 18.3 API
            const createInput: WorkItemCreateInput = {
              namespacePath,
              title: workItemTitle,
              workItemTypeId: workItemTypeObj.id,
            };
 
            // Add optional description
            if (description !== undefined) {
              createInput.description = description;
            }
 
            // Add widgets only if data is provided
            if (assigneeIds !== undefined && assigneeIds.length > 0) {
              createInput.assigneesWidget = { assigneeIds: toGids(assigneeIds, "User") };
            }
 
            if (labelIds !== undefined && labelIds.length > 0) {
              createInput.labelsWidget = { labelIds: toGids(labelIds, "Label") };
            }
 
            if (milestoneId !== undefined) {
              createInput.milestoneWidget = { milestoneId: toGid(milestoneId, "Milestone") };
            }
 
            // Start and due date widget
            if (startDate !== undefined || dueDate !== undefined || isFixed !== undefined) {
              createInput.startAndDueDateWidget = {};
              Eif (startDate !== undefined) createInput.startAndDueDateWidget.startDate = startDate;
              Eif (dueDate !== undefined) createInput.startAndDueDateWidget.dueDate = dueDate;
              Iif (isFixed !== undefined) createInput.startAndDueDateWidget.isFixed = isFixed;
            }
 
            // Hierarchy widget
            if (parentId !== undefined || (childrenIds !== undefined && childrenIds.length > 0)) {
              createInput.hierarchyWidget = {};
              if (parentId !== undefined) {
                createInput.hierarchyWidget.parentId = toGid(parentId, "WorkItem");
              }
              if (childrenIds !== undefined && childrenIds.length > 0) {
                createInput.hierarchyWidget.childrenIds = toGids(childrenIds, "WorkItem");
              }
            }
 
            // NOTE: timeTrackingWidget is NOT supported on WorkItemCreateInput by GitLab API
            // Time estimate will be applied via a follow-up update call after creation
            // See: https://gitlab.com/gitlab-org/gitlab/-/merge_requests/143507
 
            // Weight widget (Premium)
            if (weight !== undefined) {
              createInput.weightWidget = { weight };
            }
 
            // Iteration widget (Premium)
            if (iterationId !== undefined) {
              createInput.iterationWidget = {
                iterationId: toGid(iterationId, "Iteration"),
              };
            }
 
            // Health status widget (Ultimate)
            if (healthStatus !== undefined) {
              createInput.healthStatusWidget = { healthStatus };
            }
 
            // Progress widget (Premium, OKR)
            if (progressCurrentValue !== undefined) {
              createInput.progressWidget = { currentValue: progressCurrentValue };
            }
 
            // Color widget (Ultimate, epics)
            if (color !== undefined) {
              createInput.colorWidget = { color };
            }
 
            // Use comprehensive mutation with widgets support
            const response = await client.request(CREATE_WORK_ITEM_WITH_WIDGETS, {
              input: createInput,
            });
 
            if (
              response.workItemCreate?.errors?.length &&
              response.workItemCreate.errors.length > 0
            ) {
              throw new Error(
                `GitLab GraphQL errors: ${response.workItemCreate.errors.join(", ")}`
              );
            }
 
            if (!response.workItemCreate?.workItem) {
              throw new Error("Work item creation failed - no work item returned");
            }
 
            const createdWorkItem = response.workItemCreate.workItem;
 
            // Step 2: Apply timeEstimate via update if requested
            // GitLab API does NOT support timeTrackingWidget on WorkItemCreateInput
            // so we must apply it via a follow-up update call
            if (timeEstimate !== undefined) {
              try {
                const updateInput: WorkItemUpdateInput = {
                  id: createdWorkItem.id,
                  timeTrackingWidget: { timeEstimate },
                };
 
                const updateResponse = await client.request(UPDATE_WORK_ITEM, {
                  input: updateInput,
                });
 
                if (
                  updateResponse.workItemUpdate?.errors?.length &&
                  updateResponse.workItemUpdate.errors.length > 0
                ) {
                  // Update failed - return create result with warning
                  const cleanedResult = cleanWorkItemResponse(
                    createdWorkItem as unknown as GitLabWorkItem
                  );
                  return {
                    ...cleanedResult,
                    _warning: {
                      message:
                        "Work item created successfully, but some properties could not be applied",
                      failedProperties: {
                        timeEstimate: {
                          requestedValue: timeEstimate,
                          error: updateResponse.workItemUpdate.errors.join(", "),
                        },
                      },
                    },
                  };
                }
 
                if (updateResponse.workItemUpdate?.workItem) {
                  // Return updated work item with time estimate applied
                  return cleanWorkItemResponse(
                    updateResponse.workItemUpdate.workItem as unknown as GitLabWorkItem
                  );
                }
 
                // Update returned no work item but also no errors - return create result with warning
                const cleanedResult = cleanWorkItemResponse(
                  createdWorkItem as unknown as GitLabWorkItem
                );
                return {
                  ...cleanedResult,
                  _warning: {
                    message:
                      "Work item created successfully, but some properties could not be applied",
                    failedProperties: {
                      timeEstimate: {
                        requestedValue: timeEstimate,
                        error: "Time estimate update returned no work item",
                      },
                    },
                  },
                };
              } catch (updateError) {
                // Update failed with exception - return create result with warning
                const cleanedResult = cleanWorkItemResponse(
                  createdWorkItem as unknown as GitLabWorkItem
                );
                return {
                  ...cleanedResult,
                  _warning: {
                    message:
                      "Work item created successfully, but some properties could not be applied",
                    failedProperties: {
                      timeEstimate: {
                        requestedValue: timeEstimate,
                        error:
                          updateError instanceof Error
                            ? updateError.message
                            : "Unknown error applying time estimate",
                      },
                    },
                  },
                };
              }
            }
 
            return cleanWorkItemResponse(createdWorkItem as unknown as GitLabWorkItem);
          }
 
          case "update": {
            const {
              id,
              title,
              description,
              state,
              assigneeIds,
              labelIds,
              addLabelIds,
              removeLabelIds,
              milestoneId,
              startDate,
              dueDate,
              parentId,
              childrenIds,
              timeEstimate,
              timeSpent,
              timeSpentAt,
              timeSpentSummary,
              isFixed,
              weight,
              iterationId,
              progressCurrentValue,
              healthStatus,
              color,
              linkType,
              targetId,
            } = input;
            const workItemId = id;
 
            // Validate linked items params: both must be provided together
            Iif ((linkType !== undefined) !== (targetId !== undefined)) {
              throw new Error(
                "Both linkType and targetId must be provided together to create a linked item relationship"
              );
            }
 
            // Validate label params: labelIds cannot be used with addLabelIds/removeLabelIds
            if (
              labelIds !== undefined &&
              (addLabelIds !== undefined || removeLabelIds !== undefined)
            ) {
              throw new Error(
                "labelIds (replace all) cannot be used together with addLabelIds or removeLabelIds. " +
                  "Use labelIds to set exact labels, or use addLabelIds/removeLabelIds for incremental changes."
              );
            }
 
            // Validate widget parameters against instance version/tier.
            // For labels, any of labelIds/addLabelIds/removeLabelIds triggers LABELS widget validation
            const widgetParams: Record<string, unknown> = {
              description,
              assigneeIds,
              labelIds,
              addLabelIds,
              removeLabelIds,
              milestoneId,
              startDate,
              dueDate,
              parentId,
              childrenIds,
              timeEstimate,
              timeSpent,
              isFixed,
              weight,
              iterationId,
              progressCurrentValue,
              healthStatus,
              color,
              linkType,
              targetId,
            };
            const validationFailure = WidgetAvailability.validateWidgetParams(widgetParams);
            if (validationFailure) {
              throw new StructuredToolError(
                createVersionRestrictedError(
                  "manage_work_item",
                  "update",
                  validationFailure.widget,
                  validationFailure.parameter,
                  validationFailure.requiredVersion,
                  validationFailure.detectedVersion,
                  normalizeTier(validationFailure.requiredTier),
                  normalizeTier(validationFailure.currentTier)
                )
              );
            }
 
            // Get GraphQL client from ConnectionManager
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            // Convert simple ID to GID for API call
            const workItemGid = toGid(workItemId, "WorkItem");
 
            // Build dynamic input object based on provided values
            const updateInput: WorkItemUpdateInput = { id: workItemGid };
 
            // Add basic properties if provided
            if (title !== undefined) updateInput.title = title;
            if (state !== undefined) updateInput.stateEvent = state;
 
            // Add widget objects only if data is provided
            if (description !== undefined) {
              updateInput.descriptionWidget = { description };
            }
 
            if (assigneeIds !== undefined) {
              updateInput.assigneesWidget = { assigneeIds: toGids(assigneeIds, "User") };
            }
 
            // Labels widget: labelIds replaces all, addLabelIds/removeLabelIds are incremental
            // Note: labelIds and addLabelIds/removeLabelIds are mutually exclusive (validated above)
            // GitLab API does NOT support labelIds directly - only addLabelIds/removeLabelIds
            // For replace mode, we calculate diff to avoid conflicts
            if (labelIds !== undefined) {
              // Replace mode: calculate diff between current and desired state
              // First, fetch current labels from the work item
              const currentWorkItem = await client.request(GET_WORK_ITEM, { id: workItemGid });
              const currentLabels =
                (
                  (currentWorkItem.workItem?.widgets as Array<{
                    type: string;
                    labels?: { nodes?: Array<{ id: string }> };
                  }>) || []
                )
                  .find(w => w.type === "LABELS")
                  ?.labels?.nodes?.map(l => l.id) ?? [];
 
              const newLabelGids = toGids(labelIds, "Label");
 
              // Calculate diff: remove only labels NOT in new set, add only labels NOT in current set
              // This ensures no label appears in both removeLabelIds and addLabelIds
              const labelsToRemove = currentLabels.filter(id => !newLabelGids.includes(id));
              const labelsToAdd = newLabelGids.filter(id => !currentLabels.includes(id));
 
              // Build labelsWidget with calculated diff only if changes are needed
              Eif (labelsToRemove.length > 0 || labelsToAdd.length > 0) {
                updateInput.labelsWidget = {};
                Eif (labelsToRemove.length > 0) {
                  updateInput.labelsWidget.removeLabelIds = labelsToRemove;
                }
                Eif (labelsToAdd.length > 0) {
                  updateInput.labelsWidget.addLabelIds = labelsToAdd;
                }
              }
            } else if (addLabelIds !== undefined || removeLabelIds !== undefined) {
              // Incremental mode: add and/or remove labels
              updateInput.labelsWidget = {};
              if (addLabelIds !== undefined && addLabelIds.length > 0) {
                updateInput.labelsWidget.addLabelIds = toGids(addLabelIds, "Label");
              }
              if (removeLabelIds !== undefined && removeLabelIds.length > 0) {
                updateInput.labelsWidget.removeLabelIds = toGids(removeLabelIds, "Label");
              }
            }
 
            // VALIDATION: Ensure no label appears in both add and remove lists
            // This catches both user errors (incremental mode) and logic bugs (replace mode)
            if (updateInput.labelsWidget?.addLabelIds && updateInput.labelsWidget?.removeLabelIds) {
              const addSet = new Set(updateInput.labelsWidget.addLabelIds);
              const removeSet = new Set(updateInput.labelsWidget.removeLabelIds);
              const intersection = [...addSet].filter(id => removeSet.has(id));
 
              if (intersection.length > 0) {
                throw new Error(
                  `Invalid label operation: cannot add and remove the same labels simultaneously: ${intersection.join(", ")}`
                );
              }
            }
 
            if (milestoneId !== undefined) {
              updateInput.milestoneWidget = { milestoneId: toGid(milestoneId, "Milestone") };
            }
 
            // Start and due date widget
            if (startDate !== undefined || dueDate !== undefined || isFixed !== undefined) {
              updateInput.startAndDueDateWidget = {};
              Eif (startDate !== undefined) updateInput.startAndDueDateWidget.startDate = startDate;
              Eif (dueDate !== undefined) updateInput.startAndDueDateWidget.dueDate = dueDate;
              if (isFixed !== undefined) updateInput.startAndDueDateWidget.isFixed = isFixed;
            }
 
            // Hierarchy widget
            if (parentId !== undefined || (childrenIds !== undefined && childrenIds.length > 0)) {
              updateInput.hierarchyWidget = {};
              if (parentId !== undefined) {
                // null means unlink parent, string means set parent
                updateInput.hierarchyWidget.parentId =
                  parentId === null ? null : toGid(parentId, "WorkItem");
              }
              if (childrenIds !== undefined && childrenIds.length > 0) {
                updateInput.hierarchyWidget.childrenIds = toGids(childrenIds, "WorkItem");
              }
            }
 
            // Validate timelog-related params require timeSpent
            if (
              (timeSpentAt !== undefined || timeSpentSummary !== undefined) &&
              timeSpent === undefined
            ) {
              throw new Error(
                "timeSpentAt and timeSpentSummary require timeSpent to be specified (they are timelog entry properties)"
              );
            }
 
            // Time tracking widget
            if (timeEstimate !== undefined || timeSpent !== undefined) {
              updateInput.timeTrackingWidget = {};
              Eif (timeEstimate !== undefined) {
                updateInput.timeTrackingWidget.timeEstimate = timeEstimate;
              }
              Eif (timeSpent !== undefined) {
                updateInput.timeTrackingWidget.timelog = {
                  timeSpent,
                  ...(timeSpentAt !== undefined && { spentAt: timeSpentAt }),
                  ...(timeSpentSummary !== undefined && { summary: timeSpentSummary }),
                };
              }
            }
 
            // Weight widget (Premium)
            if (weight !== undefined) {
              updateInput.weightWidget = { weight };
            }
 
            // Iteration widget (Premium)
            if (iterationId !== undefined) {
              updateInput.iterationWidget = {
                iterationId: iterationId === null ? null : toGid(iterationId, "Iteration"),
              };
            }
 
            // Health status widget (Ultimate)
            if (healthStatus !== undefined) {
              updateInput.healthStatusWidget = { healthStatus };
            }
 
            // Progress widget (Premium, OKR)
            if (progressCurrentValue !== undefined) {
              updateInput.progressWidget = { currentValue: progressCurrentValue };
            }
 
            // Color widget (Ultimate, epics)
            if (color !== undefined) {
              updateInput.colorWidget = { color };
            }
 
            // Use single GraphQL mutation with dynamic input
            const response = await client.request(UPDATE_WORK_ITEM, { input: updateInput });
 
            if (
              response.workItemUpdate?.errors?.length &&
              response.workItemUpdate.errors.length > 0
            ) {
              throw new Error(
                `GitLab GraphQL errors: ${response.workItemUpdate.errors.join(", ")}`
              );
            }
 
            if (!response.workItemUpdate?.workItem) {
              throw new Error("Work item update failed - no work item returned");
            }
 
            const updatedWorkItem = response.workItemUpdate.workItem;
 
            // Step 2: Apply linked items via follow-up mutation if requested
            // GitLab API does NOT support linkedItemsWidget on WorkItemUpdateInput
            // so we must apply it via a separate workItemAddLinkedItems mutation
            Iif (linkType !== undefined && targetId !== undefined) {
              try {
                const linkResponse = await client.request(WORK_ITEM_ADD_LINKED_ITEMS, {
                  input: {
                    id: workItemGid,
                    workItemsIds: [toGid(targetId, "WorkItem")],
                    linkType,
                  },
                });
 
                if (
                  linkResponse.workItemAddLinkedItems?.errors?.length &&
                  linkResponse.workItemAddLinkedItems.errors.length > 0
                ) {
                  // Link failed - return update result with warning
                  const cleanedResult = cleanWorkItemResponse(
                    updatedWorkItem as unknown as GitLabWorkItem
                  );
                  return {
                    ...cleanedResult,
                    _warning: {
                      message: "Work item updated successfully, but linked item could not be added",
                      failedProperties: {
                        linkedItem: {
                          targetId,
                          linkType,
                          error: linkResponse.workItemAddLinkedItems.errors.join(", "),
                        },
                      },
                    },
                  };
                }
 
                if (linkResponse.workItemAddLinkedItems?.workItem) {
                  // Return work item with linked items applied
                  return cleanWorkItemResponse(
                    linkResponse.workItemAddLinkedItems.workItem as unknown as GitLabWorkItem
                  );
                }
 
                // Link returned no work item but also no errors - return update result with warning
                const cleanedResult = cleanWorkItemResponse(
                  updatedWorkItem as unknown as GitLabWorkItem
                );
                return {
                  ...cleanedResult,
                  _warning: {
                    message: "Work item updated successfully, but linked item could not be added",
                    failedProperties: {
                      linkedItem: {
                        targetId,
                        linkType,
                        error: "Add linked item returned no work item",
                      },
                    },
                  },
                };
              } catch (linkError) {
                // Link failed with exception - return update result with warning
                const cleanedResult = cleanWorkItemResponse(
                  updatedWorkItem as unknown as GitLabWorkItem
                );
                return {
                  ...cleanedResult,
                  _warning: {
                    message: "Work item updated successfully, but linked item could not be added",
                    failedProperties: {
                      linkedItem: {
                        targetId,
                        linkType,
                        error:
                          linkError instanceof Error
                            ? linkError.message
                            : "Unknown error adding linked item",
                      },
                    },
                  },
                };
              }
            }
 
            return cleanWorkItemResponse(updatedWorkItem as unknown as GitLabWorkItem);
          }
 
          case "delete": {
            const workItemId = input.id;
 
            // Get GraphQL client from ConnectionManager
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            // Convert simple ID to GID for API call
            const workItemGid = toGid(workItemId, "WorkItem");
 
            // Use GraphQL mutation for deleting work item
            const response = await client.request(DELETE_WORK_ITEM, { id: workItemGid });
 
            if (
              response.workItemDelete?.errors?.length &&
              response.workItemDelete.errors.length > 0
            ) {
              throw new Error(
                `GitLab GraphQL errors: ${response.workItemDelete.errors.join(", ")}`
              );
            }
 
            // Return success indicator for deletion
            return { deleted: true };
          }
 
          case "add_link": {
            const { id, targetId, linkType } = input;
 
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            const response = await client.request(WORK_ITEM_ADD_LINKED_ITEMS, {
              input: {
                id: toGid(id, "WorkItem"),
                workItemsIds: [toGid(targetId, "WorkItem")],
                linkType,
              },
            });
 
            if (
              response.workItemAddLinkedItems?.errors?.length &&
              response.workItemAddLinkedItems.errors.length > 0
            ) {
              throw new Error(
                `GitLab GraphQL errors: ${response.workItemAddLinkedItems.errors.join(", ")}`
              );
            }
 
            if (!response.workItemAddLinkedItems?.workItem) {
              throw new Error("Add linked item failed - no work item returned");
            }
 
            return cleanWorkItemResponse(
              response.workItemAddLinkedItems.workItem as unknown as GitLabWorkItem
            );
          }
 
          case "remove_link": {
            const { id, targetId } = input;
 
            const connectionManager = ConnectionManager.getInstance();
            const client = connectionManager.getClient();
 
            // Note: GitLab API does NOT accept linkType for remove operation
            // Links are identified by source+target IDs only
            const response = await client.request(WORK_ITEM_REMOVE_LINKED_ITEMS, {
              input: {
                id: toGid(id, "WorkItem"),
                workItemsIds: [toGid(targetId, "WorkItem")],
              },
            });
 
            if (
              response.workItemRemoveLinkedItems?.errors?.length &&
              response.workItemRemoveLinkedItems.errors.length > 0
            ) {
              throw new Error(
                `GitLab GraphQL errors: ${response.workItemRemoveLinkedItems.errors.join(", ")}`
              );
            }
 
            if (!response.workItemRemoveLinkedItems?.workItem) {
              throw new Error("Remove linked item failed - no work item returned");
            }
 
            return cleanWorkItemResponse(
              response.workItemRemoveLinkedItems.workItem as unknown as GitLabWorkItem
            );
          }
 
          /* istanbul ignore next -- unreachable with Zod discriminatedUnion */
          default:
            throw new Error(`Unknown action: ${(input as { action: string }).action}`);
        }
      },
    },
  ],
]);
 
/**
 * Get read-only tool names from the registry
 */
export function getWorkitemsReadOnlyToolNames(): string[] {
  return ["browse_work_items"];
}
 
/**
 * Get all tool definitions from the registry
 */
export function getWorkitemsToolDefinitions(): EnhancedToolDefinition[] {
  return Array.from(workitemsToolRegistry.values());
}
 
/**
 * Get filtered tools based on read-only mode
 */
export function getFilteredWorkitemsTools(readOnlyMode: boolean = false): EnhancedToolDefinition[] {
  if (readOnlyMode) {
    const readOnlyNames = getWorkitemsReadOnlyToolNames();
    return Array.from(workitemsToolRegistry.values()).filter(tool =>
      readOnlyNames.includes(tool.name)
    );
  }
  return getWorkitemsToolDefinitions();
}