diff --git a/supacode/Infrastructure/AgentDetection/AgentSessionResolver.swift b/supacode/Infrastructure/AgentDetection/AgentSessionResolver.swift index 68884831..a4caf94e 100644 --- a/supacode/Infrastructure/AgentDetection/AgentSessionResolver.swift +++ b/supacode/Infrastructure/AgentDetection/AgentSessionResolver.swift @@ -640,8 +640,16 @@ nonisolated enum AgentSessionFingerprintMatcher { /// Reference implementation. `normalize` must agree with it for every input; /// `AgentSessionFingerprintNormalizeTests` asserts that over a corpus. static func normalizeGeneral(_ value: String) -> String { - value - .replacing(#/\u{001B}\[[0-?]*[ -\/]*[@-~]/#, with: " ") + // A pattern anchored on ESC cannot match a string with no ESC byte, and + // nearly every transcript fragment has none. Proving absence with a byte + // scan is several times cheaper than letting the regex engine walk the + // whole string to reach the same conclusion. + let stripped = + value.utf8.contains(0x1B) + ? value.replacing(#/\u{001B}\[[0-?]*[ -\/]*[@-~]/#, with: " ") + : value + return + stripped .lowercased() .split(whereSeparator: \Character.isWhitespace) .joined(separator: " ") diff --git a/supacodeTests/AgentSessionFingerprintNormalizeTests.swift b/supacodeTests/AgentSessionFingerprintNormalizeTests.swift index c87ca26a..c8ee1462 100644 --- a/supacodeTests/AgentSessionFingerprintNormalizeTests.swift +++ b/supacodeTests/AgentSessionFingerprintNormalizeTests.swift @@ -47,12 +47,26 @@ struct AgentSessionFingerprintNormalizeTests { "mixed ascii and ünicode with spacing", ] - @Test func fastPathMatchesReferenceForEveryCorpusInput() { + /// The original formulation, before either the ASCII fast path or the + /// escape-absence guard. Both shipped paths must reproduce it exactly. + private static func pristine(_ value: String) -> String { + value + .replacing(#/\u{001B}\[[0-?]*[ -\/]*[@-~]/#, with: " ") + .lowercased() + .split(whereSeparator: \Character.isWhitespace) + .joined(separator: " ") + } + + @Test func bothPathsMatchTheOriginalForEveryCorpusInput() { for input in Self.corpus { + let expected = Self.pristine(input) + #expect( + AgentSessionFingerprintMatcher.normalize(input) == expected, + "normalize diverged for \(String(reflecting: input))" + ) #expect( - AgentSessionFingerprintMatcher.normalize(input) - == AgentSessionFingerprintMatcher.normalizeGeneral(input), - "normalize diverged from the reference for \(String(reflecting: input))" + AgentSessionFingerprintMatcher.normalizeGeneral(input) == expected, + "normalizeGeneral diverged for \(String(reflecting: input))" ) } } @@ -65,10 +79,14 @@ struct AgentSessionFingerprintNormalizeTests { for _ in 0..<2000 { let length = Int.random(in: 0...40, using: &generator) let input = String((0..