All files / api/src/middlewares/optimizer system-prompt.ts

32.22% Statements 185/574
72.09% Branches 31/43
40% Functions 4/10
32.22% Lines 185/574

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 8111x           1x 1x 1x 1x 1x 1x           1x   1x 1x           9x 9x       9x 9x     9x 1x 1x 1x 1x     9x             9x 1x 1x 1x 1x   9x             9x           9x                 9x 2x 7x 9x                     8x 8x 8x 8x 8x 8x   8x 8x 8x 8x   8x 1x 1x   7x     7x 8x 3x 3x   3x 2x 2x 3x     5x 5x 5x 5x 5x 5x 5x 5x 5x 8x 1x 1x     4x 4x 4x 4x   8x 1x 1x   3x     3x 3x   8x   8x 1x 1x   2x 2x                                                                                                                                                                                                                                                                                                                                                 10x 10x 10x 10x 10x 10x     10x                   10x 10x     10x   10x 31x 31x 31x 10x   10x 10x   10x 27x 27x 27x   27x   10x 10x   27x   9x 9x 9x 9x 9x 9x 9x 9x   9x 9x 9x 9x 9x 27x   8x 8x 8x 8x 8x 8x 8x 8x   8x 8x 8x 8x 8x 8x 27x   10x     10x 10x 10x     10x 10x 10x 10x 10x 10x 10x     10x 10x 10x 10x 10x 10x         1x 9x 9x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   17x 17x       17x 17x 17x       17x 17x       17x   17x 17x 8x 8x 8x 8x 8x 8x 9x 9x 9x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
import { generateReflectiveSystemPromptForSkill } from '@api/optimization/utils/system-prompt';
import type {
  LogsStorageConnector,
  UserDataStorageConnector,
} from '@api/types/connector';
import type { AppContext } from '@api/types/hono';
import { formatMessagesForExtraction } from '@api/utils/messages';
import { emitSSEEvent } from '@api/utils/sse-event-manager';
import { extractMessagesFromRequestData } from '@api/utils/super-agents/requests';
import { extractOutputFromResponseBody } from '@api/utils/super-agents/responses';
import { error } from '@shared/console-logging';
import {
  type ChatCompletionRequestData,
  FunctionName,
  type ResponsesRequestData,
  type StreamChatCompletionRequestData,
} from '@shared/types/api/request';
import { SuperAgentsResponseBody } from '@shared/types/api/response';
import type { Log, Skill, SkillOptimizationCluster } from '@shared/types/data';
import { SkillEventType } from '@shared/types/data/skill-event';
import { produceSuperAgentsRequestData } from '@shared/utils/sa-request-data';
 
/**
 * Extracts relevant request parameters that affect the output format and constraints.
 * This includes structured output requirements, tool definitions, and sampling parameters.
 */
function extractRequestConstraints(
  saRequestData:
    | ChatCompletionRequestData
    | StreamChatCompletionRequestData
    | ResponsesRequestData,
): string {
  const constraints: string[] = [];
 
  // Extract response format (JSON schema, structured output)
  if ('response_format' in saRequestData && saRequestData.response_format) {
    constraints.push(
      `Response Format: ${JSON.stringify(saRequestData.response_format, null, 2)}`,
    );
  }
 
  // Extract text config for Responses API
  if ('text' in saRequestData && saRequestData.text) {
    constraints.push(
      `Text Config: ${JSON.stringify(saRequestData.text, null, 2)}`,
    );
  }
 
  // Extract tools/functions
  if ('tools' in saRequestData && saRequestData.tools) {
    constraints.push(
      `Available Tools: ${JSON.stringify(saRequestData.tools, null, 2)}`,
    );
  }
 
  if ('functions' in saRequestData && saRequestData.functions) {
    constraints.push(
      `Available Functions: ${JSON.stringify(saRequestData.functions, null, 2)}`,
    );
  }
 
  // Extract tool choice constraints
  if ('tool_choice' in saRequestData && saRequestData.tool_choice) {
    constraints.push(
      `Tool Choice: ${JSON.stringify(saRequestData.tool_choice)}`,
    );
  }
 
  if ('function_call' in saRequestData && saRequestData.function_call) {
    constraints.push(
      `Function Call: ${JSON.stringify(saRequestData.function_call)}`,
    );
  }
 
  // Note: We intentionally skip sampling parameters like temperature, max_tokens, reasoning_effort
  // as they don't affect the task structure or requirements for the system prompt
 
  return constraints.length > 0
    ? `\n\nRequest Constraints:\n${constraints.join('\n')}`
    : '';
}
 
/**
 * Attempts to acquire a reflection lock for a cluster
 * Returns the lock timestamp if successful, null otherwise
 */
/**
 * Exported for tests. Reached only from inside a regeneration cycle that needs
 * a database, a model and a live cluster before it gets here, so the locking
 * behaviour itself is only reachable directly.
 */
export async function acquireReflectionLock(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  _skill: Skill,
  clusterId: string,
): Promise<string | null> {
  // Re-fetch cluster to get latest state (critical for lock check)
  const latestClusters =
    await userDataStorageConnector.getSkillOptimizationClusters(c, {
      id: clusterId,
    });
 
  if (latestClusters.length === 0) {
    return null;
  }
 
  const latestCluster = latestClusters[0];
 
  // Check if reflection lock exists and is recent (< 10 minutes old)
  const lockTimestamp = latestCluster.reflection_lock_acquired_at;
  if (lockTimestamp) {
    const lockAge = Date.now() - new Date(lockTimestamp).getTime();
    const LOCK_TIMEOUT_MS = 10 * 60 * 1000; // 10 minutes
 
    if (lockAge < LOCK_TIMEOUT_MS) {
      return null;
    }
  }
 
  // Try to acquire lock by updating the cluster
  const lockTime = new Date().toISOString();
  try {
    await userDataStorageConnector.updateSkillOptimizationCluster(
      c,
      clusterId,
      {
        reflection_lock_acquired_at: lockTime,
      },
    );
  } catch (_error) {
    return null;
  }
 
  // CRITICAL: Double-check the lock after acquisition to detect race conditions
  const postLockClusters =
    await userDataStorageConnector.getSkillOptimizationClusters(c, {
      id: clusterId,
    });
 
  if (postLockClusters.length === 0) {
    return null;
  }
 
  const postLockCluster = postLockClusters[0];
 
  // Check if our lock is still there (not overwritten by another process)
  const postLockTime = postLockCluster.reflection_lock_acquired_at
    ? new Date(postLockCluster.reflection_lock_acquired_at).getTime()
    : null;
  const expectedLockTime = new Date(lockTime).getTime();
 
  if (postLockTime !== expectedLockTime) {
    return null;
  }
 
  return lockTime;
}
 
/**
 * Releases the reflection lock for a cluster
 */
async function releaseReflectionLock(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  clusterId: string,
) {
  await userDataStorageConnector.updateSkillOptimizationCluster(c, clusterId, {
    reflection_lock_acquired_at: null,
  });
}
 
/**
 * Calculates weighted stats for all arms in a cluster efficiently
 */
async function calculateClusterArmStats(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  cluster: SkillOptimizationCluster,
  clusterArms: Awaited<
    ReturnType<UserDataStorageConnector['getSkillOptimizationArms']>
  >,
) {
  // Fetch evaluations to get weights (once for the whole cluster)
  const evaluations =
    await userDataStorageConnector.getSkillOptimizationEvaluations(c, {
      skill_id: cluster.skill_id,
    });
 
  // Create a map of evaluation_id -> weight
  const evaluationWeights = new Map<string, number>();
  for (const evaluation of evaluations) {
    evaluationWeights.set(evaluation.id, evaluation.weight);
  }
 
  // Fetch ALL arm_stats for the cluster in one query (efficient!)
  const allArmStats =
    await userDataStorageConnector.getSkillOptimizationArmStats(c, {
      cluster_id: cluster.id,
    });
 
  // Group arm_stats by arm_id
  const armStatsGrouped = new Map<string, typeof allArmStats>();
  for (const stat of allArmStats) {
    const existing = armStatsGrouped.get(stat.arm_id) || [];
    existing.push(stat);
    armStatsGrouped.set(stat.arm_id, existing);
  }
 
  // Calculate weighted stats for all arms
  const armStatsMap = new Map<
    string,
    { n: number; weighted_mean: number; arm: (typeof clusterArms)[0] }
  >();
 
  for (const arm of clusterArms) {
    const armStats = armStatsGrouped.get(arm.id) || [];
 
    // Calculate weighted average mean
    let weightedMeanSum = 0;
    let totalWeight = 0;
    let totalRequests = 0;
 
    for (const stat of armStats) {
      const weight = evaluationWeights.get(stat.evaluation_id) || 1.0;
      weightedMeanSum += stat.mean * weight;
      totalWeight += weight;
      // Use max n across all evaluations as the request count
      if (stat.n > totalRequests) {
        totalRequests = stat.n;
      }
    }
 
    // Calculate weighted mean (0 if no stats yet)
    const weightedMean = totalWeight > 0 ? weightedMeanSum / totalWeight : 0;
 
    armStatsMap.set(arm.id, {
      n: totalRequests,
      weighted_mean: weightedMean,
      arm,
    });
  }
 
  return { armStatsMap, evaluationWeights };
}
 
/**
 * Fetches example logs for reflection (best and worst performing)
 * - Best: Single best log from all time
 * - Worst: Worst logs since last reflection only
 */
async function fetchReflectionExamples(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  logsStorageConnector: LogsStorageConnector,
  cluster: SkillOptimizationCluster,
) {
  // Find the last reflection event for this cluster
  const lastReflectionEvents = await userDataStorageConnector.getSkillEvents(
    c,
    {
      cluster_id: cluster.id,
      event_type: SkillEventType.REFLECTION,
      limit: 1,
    },
  );
 
  const lastReflectionTime = lastReflectionEvents[0]?.created_at;
 
  // Fetch best log from all time (no time filter)
  const allTimeLogs = await logsStorageConnector.getLogs(c, {
    skill_id: cluster.skill_id,
    cluster_id: cluster.id,
    embedding_not_null: true,
    limit: 50, // Get more logs to find the absolute best
  });
 
  // Sort by score and take the single best log from all time
  const bestLog = allTimeLogs
    .map((log) => ({
      log,
      score: log.avg_eval_score ?? 0,
    }))
    .sort((a, b) => b.score - a.score)[0]?.log;
 
  const bestExamples = bestLog ? generateExampleConversations([bestLog]) : [];
 
  // Fetch worst logs since last reflection (or all time if no reflection yet)
  const recentLogs = await logsStorageConnector.getLogs(c, {
    skill_id: cluster.skill_id,
    cluster_id: cluster.id,
    embedding_not_null: true,
    after: lastReflectionTime
      ? new Date(lastReflectionTime).getTime()
      : undefined, // Will be undefined if no reflection yet, which fetches all logs
    limit: 15, // Get enough logs to find worst ones
  });
 
  // Sort by score and take bottom 5 worst logs
  const worstLogs = recentLogs
    .map((log) => ({
      log,
      score: log.avg_eval_score ?? 0,
    }))
    .sort((a, b) => b.score - a.score)
    .slice(-5)
    .map((l) => l.log);
 
  // For worst examples, include evaluation information
  const worstExamples = await generateExampleConversationsWithEvaluations(
    c,
    userDataStorageConnector,
    worstLogs,
  );
 
  return { bestExamples, worstExamples };
}
 
/**
 * Performs reflection: updates arms with new prompt and resets stats
 */
/**
 * Exported for tests. This is the conservative update the whole optimizer rests
 * on -- the best arm is deliberately left alone -- and it is otherwise reachable
 * only after a model call has produced a new prompt.
 */
export async function performReflection(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  cluster: SkillOptimizationCluster,
  skill: Skill,
  clusterArms: Awaited<
    ReturnType<UserDataStorageConnector['getSkillOptimizationArms']>
  >,
  armStatsMap: Map<
    string,
    {
      n: number;
      weighted_mean: number;
      arm: Awaited<
        ReturnType<UserDataStorageConnector['getSkillOptimizationArms']>
      >[0];
    }
  >,
  newPrompt: string,
  bestArm: Awaited<
    ReturnType<UserDataStorageConnector['getSkillOptimizationArms']>
  >[0],
) {
  // Sort arms by performance (weighted mean reward, descending)
  const sortedArms = [...clusterArms].sort((a, b) => {
    const aStats = armStatsMap.get(a.id);
    const bStats = armStatsMap.get(b.id);
    return (bStats?.weighted_mean ?? 0) - (aStats?.weighted_mean ?? 0);
  });
 
  const bestArmStats = armStatsMap.get(bestArm.id);
  const updatePromises = [];
 
  for (let i = 0; i < sortedArms.length; i++) {
    const arm = sortedArms[i];
    const isBest = i === 0;
    const isWorst = i === sortedArms.length - 1;
 
    if (isBest) {
      // Best arm: Keep completely intact (no update)
      continue;
    }
 
    if (isWorst) {
      // Worst arm: Gets best config + new prompt
      updatePromises.push(
        userDataStorageConnector.updateSkillOptimizationArm(c, arm.id, {
          params: {
            ...bestArm.params,
            system_prompt: newPrompt,
          },
        }),
      );
      // Delete all arm_stats for this arm to reset its performance history
      updatePromises.push(
        userDataStorageConnector.deleteSkillOptimizationArmStats(c, {
          arm_id: arm.id,
        }),
      );
    } else {
      // Middle arms: Get new prompt only
      updatePromises.push(
        userDataStorageConnector.updateSkillOptimizationArm(c, arm.id, {
          params: {
            ...arm.params,
            system_prompt: newPrompt,
          },
        }),
      );
      // Delete all arm_stats for this arm to reset its performance history
      updatePromises.push(
        userDataStorageConnector.deleteSkillOptimizationArmStats(c, {
          arm_id: arm.id,
        }),
      );
    }
  }
 
  await Promise.all(updatePromises);
 
  // Reset cluster total_steps to match the best arm's request count
  await userDataStorageConnector.updateSkillOptimizationCluster(c, cluster.id, {
    total_steps: bestArmStats?.n ?? 0,
  });
 
  // Create skill event for reflection
  await userDataStorageConnector.createSkillEvent(c, {
    agent_id: skill.agent_id,
    skill_id: skill.id,
    cluster_id: cluster.id,
    event_type: SkillEventType.REFLECTION,
    metadata: {},
  });
 
  // Emit SSE event for real-time updates
  emitSSEEvent('skill-optimization:event-created', {
    skillId: skill.id,
    clusterId: cluster.id,
    bestArmId: bestArm.id,
  });
}
 
/**
 * Converts a log into a conversation string with input, output, and request constraints
 */
export function generateExampleConversations(logs: Log[]): string[] {
  return logs
    .map((log) => {
      try {
        const saRequestData = produceSuperAgentsRequestData(
          log.ai_provider_request_log.method,
          log.ai_provider_request_log.request_url,
          {},
          log.ai_provider_request_log.request_body,
        );
        const responseBody = SuperAgentsResponseBody.parse(
          log.ai_provider_request_log.response_body,
        );
 
        const messages = extractMessagesFromRequestData(
          saRequestData as
            | ChatCompletionRequestData
            | StreamChatCompletionRequestData
            | ResponsesRequestData,
        );
        const input = formatMessagesForExtraction(messages);
        const output = extractOutputFromResponseBody(responseBody);
 
        // Extract constraints from the AI provider's request body directly
        // This includes response_format with full JSON schema
        const constraints = extractRequestConstraints(
          log.ai_provider_request_log.request_body as
            | ChatCompletionRequestData
            | StreamChatCompletionRequestData
            | ResponsesRequestData,
        );
 
        return `${input}${constraints}\n\nAssistant: ${output}`;
      } catch (e) {
        error(
          `[REFLECTION] Failed to extract conversation from log ${log.id}:`,
          e,
        );
        return '';
      }
    })
    .filter((conversation) => conversation !== '');
}
 
/**
 * Converts logs into conversation strings with evaluation information appended
 */
async function generateExampleConversationsWithEvaluations(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  logs: Log[],
): Promise<string[]> {
  const conversations: string[] = [];
 
  for (const log of logs) {
    try {
      const saRequestData = produceSuperAgentsRequestData(
        log.ai_provider_request_log.method,
        log.ai_provider_request_log.request_url,
        {},
        log.ai_provider_request_log.request_body,
      );
      const responseBody = SuperAgentsResponseBody.parse(
        log.ai_provider_request_log.response_body,
      );
 
      const messages = extractMessagesFromRequestData(
        saRequestData as
          | ChatCompletionRequestData
          | StreamChatCompletionRequestData
          | ResponsesRequestData,
      );
      const input = formatMessagesForExtraction(messages);
      const output = extractOutputFromResponseBody(responseBody);
 
      const constraints = extractRequestConstraints(
        log.ai_provider_request_log.request_body as
          | ChatCompletionRequestData
          | StreamChatCompletionRequestData
          | ResponsesRequestData,
      );
 
      let conversation = `${input}${constraints}\n\nAssistant: ${output}`;
 
      // Fetch evaluation runs for this log
      const evaluationRuns =
        await userDataStorageConnector.getSkillOptimizationEvaluationRuns(c, {
          log_id: log.id,
        });
 
      if (evaluationRuns.length > 0) {
        const evaluationRun = evaluationRuns[0];
 
        const evaluationInfo: string[] = [];
 
        for (const result of evaluationRun.results) {
          evaluationInfo.push(`\n## Evaluation: ${result.method}`);
          evaluationInfo.push(`Score: ${result.score.toFixed(2)}`);
 
          if (result.display_info && result.display_info.length > 0) {
            for (const displayItem of result.display_info) {
              evaluationInfo.push(
                `${displayItem.label}: ${displayItem.content}`,
              );
            }
          }
        }
 
        if (evaluationInfo.length > 0) {
          conversation += `\n\n---\n## Evaluation Results:${evaluationInfo.join('\n')}`;
        }
      }
 
      conversations.push(conversation);
    } catch (e) {
      error(
        `[REFLECTION] Failed to extract conversation with evaluations from log ${log.id}:`,
        e,
      );
    }
  }
 
  return conversations.filter((conversation) => conversation !== '');
}
 
async function autoGenerateSystemPromptsForCluster(
  c: AppContext,
  userDataStorageConnector: UserDataStorageConnector,
  logsStorageConnector: LogsStorageConnector,
  cluster: SkillOptimizationCluster,
  minRequestsPerArm: number,
  _numberOfSystemPrompts: number,
  skill: Skill,
  agentDescription: string,
) {
  // Attempt to acquire reflection lock
  const lockTime = await acquireReflectionLock(
    c,
    userDataStorageConnector,
    skill,
    cluster.id,
  );
 
  if (!lockTime) {
    return; // Lock acquisition failed, skip reflection
  }
 
  try {
    // Fetch cluster arms
    const clusterArms = await userDataStorageConnector.getSkillOptimizationArms(
      c,
      {
        skill_id: cluster.skill_id,
        cluster_id: cluster.id,
      },
    );
 
    // Early exit conditions
    if (clusterArms.length === 0) {
      console.warn(
        `[REFLECTION] No arms found for cluster ${cluster.id}. Skipping reflection and releasing lock.`,
      );
      await releaseReflectionLock(c, userDataStorageConnector, cluster.id);
      return;
    }
 
    if (clusterArms.length === 1) {
      await releaseReflectionLock(c, userDataStorageConnector, cluster.id);
      return;
    }
 
    // Calculate weighted stats for all arms
    const { armStatsMap, evaluationWeights } = await calculateClusterArmStats(
      c,
      userDataStorageConnector,
      cluster,
      clusterArms,
    );
 
    // Check threshold
    const thresholdMetArms = Array.from(armStatsMap.values()).every(
      (armData) => armData.n >= minRequestsPerArm,
    );
    if (!thresholdMetArms) {
      await releaseReflectionLock(c, userDataStorageConnector, cluster.id);
      return;
    }
 
    // Find best and worst performing arms
    let bestArm = clusterArms[0];
    let bestMean = -Infinity;
    let worstArm = clusterArms[0];
    let worstMean = Infinity;
 
    for (const [_armId, armData] of armStatsMap) {
      if (armData.weighted_mean > bestMean) {
        bestMean = armData.weighted_mean;
        bestArm = armData.arm;
      }
      if (armData.weighted_mean < worstMean) {
        worstMean = armData.weighted_mean;
        worstArm = armData.arm;
      }
    }
 
    // Fetch reflection examples (best and worst logs)
    const { bestExamples, worstExamples } = await fetchReflectionExamples(
      c,
      userDataStorageConnector,
      logsStorageConnector,
      cluster,
    );
 
    // SAFETY CHECK: Revalidate arms haven't changed during reflection
    const revalidatedArms =
      await userDataStorageConnector.getSkillOptimizationArms(c, {
        skill_id: cluster.skill_id,
        cluster_id: cluster.id,
      });
 
    const revalidatedBestArm = revalidatedArms.find(
      (arm) => arm.id === bestArm.id,
    );
    const revalidatedWorstArm = revalidatedArms.find(
      (arm) => arm.id === worstArm.id,
    );
 
    // Re-fetch arm stats for revalidation
    const revalidatedArmStats =
      await userDataStorageConnector.getSkillOptimizationArmStats(c, {
        cluster_id: cluster.id,
      });
 
    const revalidatedStatsGrouped = new Map<
      string,
      typeof revalidatedArmStats
    >();
    for (const stat of revalidatedArmStats) {
      const existing = revalidatedStatsGrouped.get(stat.arm_id) || [];
      existing.push(stat);
      revalidatedStatsGrouped.set(stat.arm_id, existing);
    }
 
    const calculateArmWeightedStats = (armId: string) => {
      const armStats = revalidatedStatsGrouped.get(armId) || [];
      let weightedMeanSum = 0;
      let totalWeight = 0;
      let totalRequests = 0;
 
      for (const stat of armStats) {
        const weight = evaluationWeights.get(stat.evaluation_id) || 1.0;
        weightedMeanSum += stat.mean * weight;
        totalWeight += weight;
        if (stat.n > totalRequests) {
          totalRequests = stat.n;
        }
      }
 
      return {
        n: totalRequests,
        weighted_mean: totalWeight > 0 ? weightedMeanSum / totalWeight : 0,
      };
    };
 
    const revalidatedBestStats = revalidatedBestArm
      ? calculateArmWeightedStats(revalidatedBestArm.id)
      : null;
    const revalidatedWorstStats = revalidatedWorstArm
      ? calculateArmWeightedStats(revalidatedWorstArm.id)
      : null;
 
    if (
      !revalidatedBestArm ||
      !revalidatedWorstArm ||
      !revalidatedBestStats ||
      !revalidatedWorstStats ||
      revalidatedBestStats.n < minRequestsPerArm ||
      revalidatedWorstStats.n < minRequestsPerArm
    ) {
      await releaseReflectionLock(c, userDataStorageConnector, cluster.id);
      return;
    }
 
    // Generate new prompt based on reflection
 
    const newPrompt = await generateReflectiveSystemPromptForSkill(
      c,
      bestArm.params.system_prompt,
      bestExamples,
      worstExamples,
      agentDescription,
      skill.description,
      skill.allowed_template_variables,
      userDataStorageConnector,
    );
 
    // Perform reflection: update arms with new prompt and reset stats
    await performReflection(
      c,
      userDataStorageConnector,
      cluster,
      skill,
      clusterArms,
      armStatsMap,
      newPrompt,
      bestArm,
    );
 
    // Release lock on successful completion
    await releaseReflectionLock(c, userDataStorageConnector, cluster.id);
  } catch (reflectionError) {
    console.error(
      `[REFLECTION] Error during reflection for skill ${skill.id}, cluster ${cluster.id}:`,
      reflectionError,
    );
    // Release lock on error
    try {
      await releaseReflectionLock(c, userDataStorageConnector, cluster.id);
    } catch (unlockError) {
      console.error('[REFLECTION] Failed to release lock:', unlockError);
    }
    // Re-throw to allow caller to handle
    throw reflectionError;
  }
}
 
export async function autoGenerateSystemPromptsForSkill(
  c: AppContext,
  functionName: FunctionName,
  userDataStorageConnector: UserDataStorageConnector,
  logsStorageConnector: LogsStorageConnector,
  skill: Skill,
) {
  // Only attempt to optimize for specific endpoints
  if (
    !(
      functionName === FunctionName.CHAT_COMPLETE ||
      functionName === FunctionName.STREAM_CHAT_COMPLETE ||
      functionName === FunctionName.CREATE_MODEL_RESPONSE
    )
  ) {
    return;
  }
 
  const skillClusters =
    await userDataStorageConnector.getSkillOptimizationClusters(c, {
      skill_id: skill.id,
    });
 
  if (!skillClusters) {
    throw new Error('Skill clusters not found');
  }
 
  const minRequestsPerArm = skill.reflection_min_requests_per_arm;
 
  // Fetch the agent information for context
  const agents = await userDataStorageConnector.getAgents(c, {
    id: skill.agent_id,
  });
 
  if (agents.length === 0) {
    throw new Error(`Agent with id ${skill.agent_id} not found`);
  }
 
  const agent = agents[0];
 
  for (const cluster of skillClusters) {
    await autoGenerateSystemPromptsForCluster(
      c,
      userDataStorageConnector,
      logsStorageConnector,
      cluster,
      minRequestsPerArm,
      1, // Always use 1 system prompt
      skill,
      agent.description,
    );
  }
}