All files / src/utils schema-utils.ts

99.06% Statements 211/213
90.68% Branches 146/161
100% Functions 24/24
99.49% Lines 197/198

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                                46x             46x                                                                                       46x             35118x 35118x 1777x                       46x         11532x                   11534x 10656x       878x     878x 878x   4205x 4205x     4204x 4201x 4201x 1089x   4201x       3x 2x 2x 1x   2x     1x       878x 1x 1x       877x                           46x   627x 1x       626x 626x 626x 626x     626x 626x   626x 2508x   2508x   2508x   14429x 2508x 2506x 2x 2x   2508x       11921x 6656x 6656x   5265x   5265x 5265x 268x         11921x 4564x 1235x       7357x 3777x         2508x       626x                           626x 6656x   5883x 5883x 28013x 9445x 9445x 9444x 1x 1x           5883x 5883x 5883x 5883x 9379x 5863x               626x 623x     626x                         6x   6x 25x 25x 25x 6x 6x       25x 6x 6x 6x 1x 1x                           46x 14052x 14052x     14052x 14052x 5x     14052x 14047x       5x     5x 1x 2x 2x     1x       4x 4x     4x                       46x 500x 27x     473x                                   46x           14047x     14047x 11522x 2525x   9x       14047x     14047x 64x     14047x                       9x                 10x 7x       3x   3x 3x 3x 10x     3x 1x 2x 2x 2x 2x           3x                                   46x       829x 1x       828x 828x   828x   817x 4263x       11x     828x             4274x 4271x 10860x 3415x         4274x 11750x                       46x         23577x 23577x 22660x     4406x 917x             46x         7x 7x 7x 8x 3x             8x   8x 4x 2x               46x         17x 15x 15x 14x   15x 30x 5x 12x 9x     15x           46x   14656x 11x       14645x 11951x 11951x 49080x 49080x 49079x 1x 1x     11951x     2694x    
/**
 * Schema Utilities for Discriminated Union Transformation
 *
 * Provides functions to:
 * 1. Filter actions from discriminated union schemas
 * 2. Flatten discriminated unions to flat schemas (for AI clients)
 * 3. Apply description overrides at all levels
 *
 * Schema Pipeline:
 *   Discriminated Union (source)
 *     → Filter denied actions (remove branches)
 *     → Apply description overrides
 *     → Flatten to single object (for current AI clients)
 *     → Output JSON Schema
 */
 
import {
  GITLAB_DENIED_ACTIONS,
  GITLAB_SCHEMA_MODE,
  detectSchemaMode,
  getActionDescriptionOverrides,
  getParamDescriptionOverrides,
} from '../config';
import { logDebug, logWarn } from '../logger';
 
// ============================================================================
// Per-Session Schema Mode (for GITLAB_SCHEMA_MODE=auto)
// ============================================================================
 
export type ClientSchemaMode = 'flat' | 'discriminated';
 
// ============================================================================
// Types
// ============================================================================
 
interface JSONSchemaProperty {
  type?: string;
  enum?: string[];
  const?: string;
  description?: string;
  [key: string]: unknown;
}
 
interface JSONSchema {
  type?: string;
  properties?: Record<string, JSONSchemaProperty>;
  required?: string[];
  description?: string;
  oneOf?: JSONSchema[];
  anyOf?: JSONSchema[];
  allOf?: JSONSchema[];
  discriminator?: { propertyName: string };
  $schema?: string;
  [key: string]: unknown;
}
 
// ============================================================================
// Core Transformation Functions
// ============================================================================
 
/** Lowercase action names; satisfied by a Set and by a Map keyed by action. */
export interface ActionNames {
  readonly size: number;
  has(action: string): boolean;
  keys(): Iterable<string>;
}
 
const NO_ACTIONS: ActionNames = new Set<string>();
 
/**
 * Lowercase actions removed from a tool: denied by configuration, plus those the
 * connected instance cannot serve.
 */
function removedActions(toolName: string, unavailable: ActionNames): ActionNames {
  const denied = GITLAB_DENIED_ACTIONS.get(toolName.toLowerCase());
  if (unavailable.size === 0) return denied ?? NO_ACTIONS;
  Eif (!denied || denied.size === 0) return unavailable;
  return new Set([...denied, ...unavailable.keys()]);
}
 
/**
 * Filter branches from a discriminated union JSON schema based on denied actions
 *
 * @param schema - JSON schema with oneOf (discriminated union)
 * @param toolName - Tool name for looking up denied actions
 * @param unavailable - Lowercase actions the instance cannot serve
 * @returns Filtered schema with denied action branches removed
 */
export function filterDiscriminatedUnionActions(
  schema: JSONSchema,
  toolName: string,
  unavailable: ActionNames = NO_ACTIONS,
): JSONSchema {
  return dropUnionActions(schema, toolName, removedActions(toolName, unavailable));
}
 
/** The union without the branches of the given lowercase actions. */
function dropUnionActions(
  schema: JSONSchema,
  toolName: string,
  deniedActions: ActionNames,
): JSONSchema {
  // If no oneOf, this isn't a discriminated union - return as-is
  if (!schema.oneOf || deniedActions.size === 0) {
    return schema;
  }
 
  // Deep clone to avoid mutating original
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
 
  // Filter oneOf branches - keep only allowed actions
  const originalOneOf = result.oneOf ?? [];
  result.oneOf = originalOneOf.filter((branch) => {
    // Find the action value in this branch
    const actionProp = branch.properties?.action;
    if (!actionProp) return true; // Keep branches without action
 
    // Check if action is a const (literal)
    if (actionProp.const) {
      const isAllowed = !deniedActions.has(actionProp.const.toLowerCase());
      if (!isAllowed) {
        logDebug(`Tool '${toolName}': filtered out action '${actionProp.const}' from schema`);
      }
      return isAllowed;
    }
 
    // Check if action is an enum with single value
    if (actionProp.enum?.[0]) {
      const isAllowed = !deniedActions.has(actionProp.enum[0].toLowerCase());
      if (!isAllowed) {
        logDebug(`Tool '${toolName}': filtered out action '${actionProp.enum[0]}' from schema`);
      }
      return isAllowed;
    }
 
    return true; // Keep if we can't determine action
  });
 
  // If all branches filtered out, return empty schema
  if (result.oneOf.length === 0) {
    logWarn(`Tool '${toolName}': all actions filtered out!`);
    return { type: 'object', properties: {} };
  }
 
  // If only one branch left, we could simplify but keep oneOf for consistency
  return result;
}
 
/**
 * Flatten a discriminated union JSON schema to a flat object schema
 *
 * This is needed because Claude API doesn't support oneOf/anyOf at root level.
 * We merge all branches into a single object with:
 * - action: enum of all allowed actions
 * - All parameters from all branches (made optional except shared required ones)
 *
 * @param schema - JSON schema with oneOf (discriminated union)
 * @returns Flat JSON schema compatible with Claude API
 */
export function flattenDiscriminatedUnion(schema: JSONSchema): JSONSchema {
  // If no oneOf, already flat
  if (!schema.oneOf || schema.oneOf.length === 0) {
    return schema;
  }
 
  // Collect all properties and track which are shared vs branch-specific
  const allProperties: Record<string, JSONSchemaProperty> = {};
  const propertyBranches: Map<string, number> = new Map(); // prop -> count of branches using it
  const actionValues: string[] = [];
  const totalBranches = schema.oneOf.length;
 
  // Collect required properties that are required in ALL branches
  const requiredInAllBranches: Set<string> = new Set();
  let firstBranch = true;
 
  for (const branch of schema.oneOf) {
    Iif (!branch.properties) continue;
 
    const branchRequired = new Set(branch.required ?? []);
 
    for (const [propName, propDef] of Object.entries(branch.properties)) {
      // Track action values
      if (propName === 'action') {
        if (propDef.const) {
          actionValues.push(propDef.const);
        } else Eif (propDef.enum) {
          actionValues.push(...propDef.enum);
        }
        continue; // Handle action separately
      }
 
      // Merge property definition
      if (!allProperties[propName]) {
        allProperties[propName] = { ...propDef };
        propertyBranches.set(propName, 1);
      } else {
        propertyBranches.set(propName, (propertyBranches.get(propName) ?? 0) + 1);
        // Merge descriptions if different (take longest)
        const existingDesc = allProperties[propName].description ?? '';
        if (propDef.description && propDef.description.length > existingDesc.length) {
          allProperties[propName].description = propDef.description;
        }
      }
 
      // Track shared required properties
      if (firstBranch) {
        if (branchRequired.has(propName)) {
          requiredInAllBranches.add(propName);
        }
      } else {
        // Remove from shared required if not required in this branch
        if (!branchRequired.has(propName)) {
          requiredInAllBranches.delete(propName);
        }
      }
    }
 
    firstBranch = false;
  }
 
  // Build flat schema
  const flatSchema: JSONSchema = {
    type: 'object',
    properties: {
      action: {
        type: 'string',
        enum: [...new Set(actionValues)], // Deduplicate
        description: `Action to perform: ${[...new Set(actionValues)].join(', ')}`,
      },
      ...allProperties,
    },
    required: ['action', ...Array.from(requiredInAllBranches)],
  };
 
  // Add descriptions for parameters that are only used by specific actions
  for (const [propName, count] of propertyBranches) {
    if (count < totalBranches && allProperties[propName]) {
      // This property is not in all branches - find which actions use it
      const actionsUsingProp: string[] = [];
      for (const branch of schema.oneOf) {
        if (branch.properties?.[propName]) {
          const actionProp = branch.properties.action;
          if (actionProp?.const) {
            actionsUsingProp.push(actionProp.const);
          } else Eif (actionProp?.enum?.[0]) {
            actionsUsingProp.push(actionProp.enum[0]);
          }
        }
      }
 
      // Append "Used by: action1, action2" to description if not already mentioned
      const propRef = flatSchema.properties?.[propName];
      Eif (propRef) {
        const currentDesc = propRef.description ?? '';
        if (actionsUsingProp.length > 0 && !currentDesc.includes('Required for')) {
          const actionList = actionsUsingProp.map((a) => `'${a}'`).join(', ');
          propRef.description =
            currentDesc + (currentDesc ? ' ' : '') + `Required for ${actionList} action(s).`;
        }
      }
    }
  }
 
  // Copy over $schema if present
  if (schema.$schema) {
    flatSchema.$schema = schema.$schema;
  }
 
  return flatSchema;
}
 
/**
 * Apply description overrides to properties in a schema branch
 * Helper function for applyDescriptionOverrides
 */
function applyOverridesToProperties(
  properties: Record<string, JSONSchemaProperty>,
  toolName: string,
  paramOverrides: Map<string, string>,
  actionOverrides: Map<string, string>,
): void {
  const lowerToolName = toolName.toLowerCase();
 
  for (const [propName, prop] of Object.entries(properties)) {
    const paramKey = `${lowerToolName}:${propName.toLowerCase()}`;
    const override = paramOverrides.get(paramKey);
    if (override) {
      prop.description = override;
      logDebug(`Applied param override for '${toolName}.${propName}': "${override}"`);
    }
 
    // For action property, also check action-level overrides
    if (propName === 'action') {
      const actionKey = `${lowerToolName}:action`;
      const actionOverride = actionOverrides.get(actionKey);
      if (actionOverride) {
        prop.description = actionOverride;
        logDebug(`Applied action override for '${toolName}': "${actionOverride}"`);
      }
    }
  }
}
 
/**
 * Apply description overrides to a JSON schema
 * Works with both flat schemas and discriminated unions (oneOf)
 *
 * @param schema - JSON schema to modify (flat or discriminated union)
 * @param toolName - Tool name for looking up overrides
 * @returns Schema with description overrides applied
 */
export function applyDescriptionOverrides(schema: JSONSchema, toolName: string): JSONSchema {
  const actionOverrides = getActionDescriptionOverrides();
  const paramOverrides = getParamDescriptionOverrides();
 
  // Check if any overrides exist for this tool
  const lowerToolName = toolName.toLowerCase();
  const hasOverrides = [...paramOverrides.keys(), ...actionOverrides.keys()].some((key) =>
    key.startsWith(`${lowerToolName}:`),
  );
 
  if (!hasOverrides) {
    return schema;
  }
 
  // Deep clone
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
 
  // Handle discriminated union (oneOf) - apply overrides to each branch
  if (result.oneOf) {
    for (const branch of result.oneOf) {
      Eif (branch.properties) {
        applyOverridesToProperties(branch.properties, toolName, paramOverrides, actionOverrides);
      }
    }
    return result;
  }
 
  // Handle flat schema
  Eif (result.properties) {
    applyOverridesToProperties(result.properties, toolName, paramOverrides, actionOverrides);
  }
 
  return result;
}
 
// ============================================================================
// Schema Format Configuration
// ============================================================================
 
/**
 * Get the effective schema mode
 * - If GITLAB_SCHEMA_MODE is 'flat' or 'discriminated': use that directly
 * - If GITLAB_SCHEMA_MODE is 'auto': use detected mode from clientInfo, or 'flat' as fallback
 */
export function getSchemaMode(clientName?: string): ClientSchemaMode {
  if (GITLAB_SCHEMA_MODE === 'auto') {
    return detectSchemaMode(clientName);
  }
  // Explicit mode configured
  return GITLAB_SCHEMA_MODE;
}
 
// ============================================================================
// Main Pipeline Function
// ============================================================================
 
/**
 * Transform a tool's input schema through the full pipeline:
 * 1. Filter denied actions (removes oneOf branches or enum values)
 * 2. Apply description overrides (works on oneOf branches or flat properties)
 * 3. Conditional flatten (based on GITLAB_SCHEMA_MODE config)
 *
 * @param toolName - Tool name
 * @param inputSchema - Original JSON schema (may be discriminated union or flat)
 * @param unavailableActions - Lowercase actions the connected instance cannot serve
 * @returns Transformed JSON schema ready for clients
 */
export function transformToolSchema(
  toolName: string,
  inputSchema: JSONSchema,
  unavailableActions: ActionNames = NO_ACTIONS,
  schemaMode: ClientSchemaMode = getSchemaMode(),
): JSONSchema {
  let schema = inputSchema;
 
  // Step 1: Filter denied and unavailable actions
  if (schema.oneOf) {
    schema = filterDiscriminatedUnionActions(schema, toolName, unavailableActions);
  } else if (schema.properties?.action?.enum) {
    // Flat schema with action enum - filter the enum directly
    schema = filterFlatSchemaActions(schema, toolName, unavailableActions);
  }
 
  // Step 2: Apply description overrides (works on oneOf or flat)
  schema = applyDescriptionOverrides(schema, toolName);
 
  // Step 3: Conditional flatten based on config
  if (schemaMode === 'flat' && schema.oneOf) {
    schema = flattenDiscriminatedUnion(schema);
  }
 
  return schema;
}
 
/**
 * Filter actions from a flat schema (legacy support)
 * Used for schemas that haven't been migrated to discriminated union yet
 */
function filterFlatSchemaActions(
  schema: JSONSchema,
  toolName: string,
  unavailable: ActionNames,
): JSONSchema {
  return dropFlatActions(schema, toolName, removedActions(toolName, unavailable));
}
 
/** The flat schema without the given lowercase actions in its action enum. */
function dropFlatActions(
  schema: JSONSchema,
  toolName: string,
  deniedActions: ActionNames,
): JSONSchema {
  if (deniedActions.size === 0) {
    return schema;
  }
 
  // Deep clone
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
 
  Eif (result.properties?.action?.enum) {
    const originalActions = result.properties.action.enum;
    const filteredActions = originalActions.filter(
      (action) => !deniedActions.has(action.toLowerCase()),
    );
 
    if (filteredActions.length === 0) {
      logWarn(`Tool '${toolName}': all actions filtered out from flat schema!`);
    } else Eif (filteredActions.length < originalActions.length) {
      result.properties.action.enum = filteredActions;
      result.properties.action.description = `Action to perform: ${filteredActions.join(', ')}`;
      logDebug(
        `Tool '${toolName}': filtered flat schema actions [${originalActions.join(', ')}] -> [${filteredActions.join(', ')}]`,
      );
    }
  }
 
  return result;
}
 
// ============================================================================
// Parameter-Level Tier Filtering
// ============================================================================
 
/**
 * Strip tier-restricted parameters from a JSON Schema.
 * Removes properties and their required entries for parameters that are
 * unavailable at the current GitLab instance tier/version.
 *
 * Works with both flat schemas and discriminated unions (oneOf).
 *
 * @param schema - JSON schema (already transformed by the main pipeline)
 * @param restrictedParams - Parameter names to remove from the schema
 * @returns Schema with restricted parameters removed
 */
export function stripTierRestrictedParameters(
  schema: JSONSchema,
  restrictedParams: string[],
): JSONSchema {
  if (restrictedParams.length === 0) {
    return schema;
  }
 
  // Deep clone to avoid mutating original
  const result = JSON.parse(JSON.stringify(schema)) as JSONSchema;
  const restrictedSet = new Set(restrictedParams);
 
  if (result.oneOf) {
    // Discriminated union: strip from each branch
    for (const branch of result.oneOf) {
      stripFromProperties(branch, restrictedSet);
    }
  } else {
    // Flat schema: strip from top-level properties
    stripFromProperties(result, restrictedSet);
  }
 
  return result;
}
 
/**
 * Remove restricted parameters from a schema object's properties and required array
 */
function stripFromProperties(schema: JSONSchema, restrictedParams: Set<string>): void {
  if (schema.properties) {
    for (const paramName of restrictedParams) {
      if (paramName in schema.properties) {
        delete schema.properties[paramName];
      }
    }
  }
 
  if (schema.required) {
    schema.required = schema.required.filter((name) => !restrictedParams.has(name));
  }
}
 
// ============================================================================
// Utility Functions
// ============================================================================
 
/**
 * Check if all actions of a tool are denied by configuration or, when given,
 * unavailable on the connected instance
 */
export function shouldRemoveTool(
  toolName: string,
  allActions: string[],
  unavailable: ActionNames = NO_ACTIONS,
): boolean {
  const deniedActions = removedActions(toolName, unavailable);
  if (deniedActions.size === 0) {
    return false;
  }
 
  const allowedActions = allActions.filter((action) => !deniedActions.has(action.toLowerCase()));
  return allowedActions.length === 0;
}
 
/**
 * A client schema, discriminated or flat, without the given lowercase actions; undefined when
 * no action is left. The operator's denials were already applied when the schema was built.
 */
export function withoutSchemaActions(
  toolName: string,
  schema: Record<string, unknown>,
  actions: ActionNames,
): Record<string, unknown> | undefined {
  const json = schema as JSONSchema;
  const offered = extractActionsFromSchema(json);
  if (actions.size === 0 || offered.length === 0) return schema;
  if (offered.every((action) => actions.has(action.toLowerCase()))) return undefined;
  return json.oneOf
    ? dropUnionActions(json, toolName, actions)
    : dropFlatActions(json, toolName, actions);
}
 
/** Whether a union branch serves `action`: true for a branch without an action literal. */
function branchServesAction(branch: unknown, action: string): boolean {
  const property = (branch as { properties?: { action?: { const?: unknown; enum?: unknown } } })
    ?.properties?.action;
  if (property?.const !== undefined) return property.const === action;
  if (Array.isArray(property?.enum)) return property.enum.includes(action);
  return true;
}
 
/**
 * Property names a JSON schema declares. With `action`, a discriminated union contributes
 * only the branches of that action, as its parse keeps only their fields; without it, every
 * branch.
 */
export function declaredArgumentNames(
  schema: unknown,
  action?: string,
  names = new Set<string>(),
): Set<string> {
  if (typeof schema !== 'object' || schema === null) return names;
  const node = schema as { properties?: unknown; oneOf?: unknown; anyOf?: unknown };
  if (typeof node.properties === 'object' && node.properties !== null) {
    for (const name of Object.keys(node.properties)) names.add(name);
  }
  for (const branches of [node.oneOf, node.anyOf]) {
    if (!Array.isArray(branches)) continue;
    for (const branch of branches) {
      if (action === undefined || branchServesAction(branch, action))
        declaredArgumentNames(branch, action, names);
    }
  }
  return names;
}
 
/**
 * Extract action list from a JSON schema
 */
export function extractActionsFromSchema(inputSchema: JSONSchema): string[] {
  // Check flat schema
  if (inputSchema.properties?.action?.enum) {
    return inputSchema.properties.action.enum;
  }
 
  // Check discriminated union
  if (inputSchema.oneOf) {
    const actions: string[] = [];
    for (const branch of inputSchema.oneOf) {
      const actionProp = branch.properties?.action;
      if (actionProp?.const) {
        actions.push(actionProp.const);
      } else Eif (actionProp?.enum?.[0]) {
        actions.push(actionProp.enum[0]);
      }
    }
    return actions;
  }
 
  return [];
}