  // Two-stage Loop detection (Fix 4 update)
  // Sliding window of 10
  const window = toolFingerprints.slice(-10);
  const counts = new Map<string, number>();
  for (const fp of window) counts.set(fp, (counts.get(fp) ?? 0) + 1);
  
  // Find highest repeating tool call
  let maxRepeats = 0;
  let repeatedCmd = "";
  for (const [fp, n] of counts.entries()) {
    if (n > maxRepeats) {
      maxRepeats = n;
      repeatedCmd = fp.split("|")[0];
    }
  }

  // Stage 1: Warning at 3 repeats
  if (maxRepeats === 3) {
    extraSystem += `\n\n[WARNING] You have called ${repeatedCmd} 3 times recently. Please wrap up this approach or try a completely different tool.`;
  }
  
  // Stage 2: Hard Break at 5 repeats
  if (maxRepeats >= 5) {
    loopBreakReason = `Repeated ${repeatedCmd} ${maxRepeats}× in last 10 calls`;
  }
