/// Detects repetition loops in a streaming translation (`docs/TRANSLATION_OUTPUT.md` ยง7). public struct RepetitionDetector: Sendable { /// The repeated-line threshold. public static let minimumLineLength = 8 /// How many identical consecutive lines count as a loop. public static let lineRepeatThreshold = 6 /// The repeated-window length. public static let windowLength = 64 /// How many identical windows count as a loop. public static let windowRepeatThreshold = 8 /// How much trailing text is inspected for window loops. public static let windowSearchLength = 2048 private var buffer = "" /// Creates a detector. public init() {} /// Appends a delta and returns true when a loop is detected. public mutating func append(_ delta: String) -> Bool { buffer += delta if buffer.count > Self.windowSearchLength * 2 { buffer = String(buffer.suffix(Self.windowSearchLength)) } return Self.detectsLoop(in: buffer) } /// Checks a complete or partial output for a loop. public static func detectsLoop(in text: String) -> Bool { hasRepeatedLine(in: text) || hasRepeatedWindow(in: text) } private static func hasRepeatedLine(in text: String) -> Bool { let lines = text .components(separatedBy: "\n") .suffix(12) .map { $0.trimmingCharacters(in: .whitespaces) } guard !lines.isEmpty else { return false } var run = 1 for index in 1 ..< lines.count { if !lines[index].isEmpty, lines[index].count >= minimumLineLength, lines[index] == lines[index - 1] { run += 1 if run >= lineRepeatThreshold { return true } } else { run = 1 } } return false } private static func hasRepeatedWindow(in text: String) -> Bool { guard text.count >= windowLength else { return false } let search = String(text.suffix(windowSearchLength)) let window = String(text.suffix(windowLength)) guard search.count >= windowLength * windowRepeatThreshold else { return false } var count = 0 var range = search.startIndex ..< search.endIndex while let found = search.range(of: window, range: range) { count += 1 if count >= windowRepeatThreshold { return true } range = found.upperBound ..< search.endIndex } return false } }