Repository Public License
1import Foundation2import NavigatorCore34/// The sources read in one run. Ids are handed out here and nowhere else, so a citation to something the agent did5/// not read cannot be constructed: the verifier resolves ids against this registry only.6struct SourceRegistry: Sendable {7 struct Source: Sendable {8 var citation: Citation9 /// The text as it was made available to the model (redacted, hidden text excluded), kept to check quotes.10 var text: String11 }1213 static let maxStoredCharacters = 400_00014 let excerptLimit: Int15 private(set) var sources: [Int: Source] = [:]16 private var idByKey: [String: Int] = [:]1718 init(excerptLimit: Int) { self.excerptLimit = max(0, excerptLimit) }1920 var citations: [Citation] { sources.values.map(\.citation).sorted { $0.id < $1.id } }21 func text(of id: Int) -> String? { sources[id]?.text }2223 /// Registers a read of `url`. Reading the same address again keeps its id and adds the new text.24 /// Returns the citation and whether it is new.25 mutating func register(url: URL, title: String, text: String, at date: Date) -> (citation: Citation, isNew: Bool) {26 var components = URLComponents(url: url, resolvingAgainstBaseURL: false)27 components?.fragment = nil28 let key = components?.string ?? url.absoluteString29 if let id = idByKey[key], var source = sources[id] {30 if !source.text.contains(text) {31 source.text = String((source.text + "\n" + text).prefix(Self.maxStoredCharacters))32 }33 source.citation.accessedAt = date34 sources[id] = source35 return (source.citation, false)36 }37 let id = (sources.keys.max() ?? 0) + 138 let excerpt = String(text.split(whereSeparator: { $0.isNewline }).joined(separator: " ").prefix(excerptLimit))39 let citation = Citation(id: id, url: url, title: AgentText.singleLine(title, limit: 200), accessedAt: date, excerpt: excerpt)40 sources[id] = Source(citation: citation, text: String(text.prefix(Self.maxStoredCharacters)))41 idByKey[key] = id42 return (citation, true)43 }44}4546public struct VerifiedSentence: Sendable, Hashable {47 public enum Status: String, Sendable, Hashable, Codable {48 /// Cites at least one source read in this run, and every quotation was found in a cited source.49 case cited50 /// Makes a claim without citing any source read in this run.51 case uncited52 /// A quotation in the sentence does not appear in the sources it cites.53 case quoteNotFound54 /// Not a claim (a question, a heading, a statement that nothing was found).55 case notAClaim56 }5758 public var text: String59 /// Ids that resolve to a source read in this run.60 public var citationIDs: [Int]61 /// Ids the model wrote that do not exist. They are removed from the answer.62 public var unknownCitationIDs: [Int]63 public var status: Status64 public var wasDropped: Bool65}6667/// The final answer after the deterministic check.68public struct VerifiedAnswer: Sendable, Hashable {69 /// The text to show: unknown citation markers removed, uncited claims flagged or dropped.70 public var text: String71 public var sentences: [VerifiedSentence]72 /// The sources the answer actually cites.73 public var citations: [Citation]7475 public var flaggedCount: Int { sentences.filter { $0.status == .uncited || $0.status == .quoteNotFound }.count }76 public var droppedCount: Int { sentences.filter(\.wasDropped).count }77 public var unknownCitationIDs: [Int] { Array(Set(sentences.flatMap(\.unknownCitationIDs))).sorted() }78 /// Every claim cites a source read in this run and every quotation was found.79 public var isFullyVerified: Bool { flaggedCount == 0 && unknownCitationIDs.isEmpty }80}8182/// Checks an answer against the sources of the run using citation ids and quoted excerpts only. No model is involved.83///84/// What it proves: each kept claim names a source that was read, and quoted text exists in a named source.85/// What it does not prove: that the source supports the claim. A sentence can cite a real source and still be wrong.86enum AnswerVerifier {87 static let uncitedMarker = "[uncited]"88 static let quoteMarker = "[quote not found in the cited source]"8990 private static let citationPattern = try? NSRegularExpression(pattern: #"\s*\[\s*(\d{1,6}(?:\s*,\s*\d{1,6})*)\s*\]"#)91 private static let quotePattern = try? NSRegularExpression(pattern: #""([^"\n]{12,600})"|“([^”\n]{12,600})”|«\s*([^»\n]{12,600}?)\s*»"#)92 private static let nonClaim = try? NSRegularExpression(93 pattern: #"^(i (could not|couldn't|was unable to|was not able to|did not find|didn't find|cannot|can't|found no)|no (source|information|result)|"#94 + #"(the|this) (page|site|source)s? (does|do|did) not (say|mention|state|contain)|sources?\s*:|note\s*:|summary\s*:|"#95 + #"je n'ai pas (pu|trouve)|je ne peux pas|aucune? (source|information|resultat)|impossible de|resume\s*:|remarque\s*:)"#,96 options: [.caseInsensitive])9798 static func verify(answer: String, sources: [Int: SourceRegistry.Source], handling: AgentPermissionPolicy.UncitedClaims) -> VerifiedAnswer {99 var sentences: [VerifiedSentence] = []100 var output = ""101 var used = Set<Int>()102 for segment in split(answer) {103 let (clean, ids) = stripCitations(segment.body)104 let known = ids.filter { sources[$0] != nil }, unknown = ids.filter { sources[$0] == nil }105 var status: VerifiedSentence.Status106 if !isClaim(clean) { status = .notAClaim }107 else if known.isEmpty { status = .uncited }108 else if quotes(in: clean).allSatisfy({ quote in known.contains { contains(sources[$0]?.text ?? "", quote: quote) } }) { status = .cited }109 else { status = .quoteNotFound }110 let flagged = status == .uncited || status == .quoteNotFound111 let dropped = flagged && handling == .drop112 sentences.append(VerifiedSentence(text: clean, citationIDs: known, unknownCitationIDs: unknown, status: status, wasDropped: dropped))113 guard !dropped else { continue }114 used.formUnion(known)115 // The model's own wording and marker placement are kept unless a marker has to be removed.116 var rendered = segment.body117 for marker in [uncitedMarker, quoteMarker] { rendered = rendered.replacingOccurrences(of: marker, with: "") }118 rendered = rendered.trimmingCharacters(in: .whitespaces)119 if !unknown.isEmpty {120 rendered = clean121 if !known.isEmpty { rendered += " " + known.map { "[\($0)]" }.joined() }122 }123 if status == .uncited { rendered += " " + uncitedMarker }124 if status == .quoteNotFound { rendered += " " + quoteMarker }125 output += rendered + segment.trailing126 }127 let citations = used.sorted().compactMap { sources[$0]?.citation }128 return VerifiedAnswer(text: output.trimmingCharacters(in: .whitespacesAndNewlines), sentences: sentences, citations: citations)129 }130131 /// What is sent back to the model when its answer is handed back once for revision.132 static func revisionRequest(for answer: VerifiedAnswer, knownIDs: [Int]) -> String {133 var lines = ["The answer was not accepted yet. The runtime checked it against the sources read in this run:"]134 for sentence in answer.sentences where sentence.status == .uncited {135 lines.append("- No valid citation: “\(AgentText.singleLine(sentence.text, limit: 110))”")136 }137 for sentence in answer.sentences where sentence.status == .quoteNotFound {138 lines.append("- A quotation is not in the cited source: “\(AgentText.singleLine(sentence.text, limit: 110))”")139 }140 if !answer.unknownCitationIDs.isEmpty {141 lines.append("- These source ids do not exist: \(answer.unknownCitationIDs.map(String.init).joined(separator: ", ")).")142 }143 lines.append(knownIDs.isEmpty ? "No source has been read in this run." : "Existing source ids: \(knownIDs.map(String.init).joined(separator: ", ")).")144 lines.append("Call finish again: cite a source id after every factual sentence, quote exactly, and remove what no source supports. "145 + "Anything still unsupported will be marked or removed by the runtime.")146 return lines.joined(separator: "\n")147 }148149 // MARK: Parsing150151 struct Segment: Hashable { var body: String; var trailing: String }152153 /// Splits into sentences. A terminator counts only before whitespace, a citation marker or the end, so "3.5" and154 /// "example.com" stay whole; citation markers written after the terminator stay with their sentence.155 static func split(_ text: String) -> [Segment] {156 let characters = Array(text)157 var segments: [Segment] = []158 var body = "", index = 0159 func flush(trailing: String) {160 let trimmed = body.trimmingCharacters(in: .whitespaces)161 if !trimmed.isEmpty { segments.append(Segment(body: trimmed, trailing: trailing)) }162 else if var last = segments.popLast() { last.trailing += trailing; segments.append(last) }163 body = ""164 }165 while index < characters.count {166 let character = characters[index]167 if character.isNewline {168 var trailing = ""169 while index < characters.count, characters[index].isWhitespace { trailing.append(characters[index]); index += 1 }170 flush(trailing: trailing)171 continue172 }173 body.append(character)174 index += 1175 guard ".!?".contains(character) else { continue }176 while index < characters.count, ".!?\"”»)".contains(characters[index]) { body.append(characters[index]); index += 1 }177 // Look ahead: spaces, then any citation markers, belong to this sentence.178 var cursor = index, absorbed = ""179 while true {180 var probe = cursor, spaces = ""181 while probe < characters.count, characters[probe] == " " { spaces.append(" "); probe += 1 }182 guard probe < characters.count, characters[probe] == "[",183 let close = characters[probe...].firstIndex(of: "]"), close - probe <= 40,184 characters[(probe + 1)..<close].allSatisfy({ $0.isNumber || $0 == "," || $0 == " " }), close > probe + 1 else { break }185 absorbed += spaces + String(characters[probe...close])186 cursor = close + 1187 }188 let atBoundary = cursor >= characters.count || characters[cursor].isWhitespace189 guard atBoundary || !absorbed.isEmpty else { continue }190 body += absorbed191 index = cursor192 var trailing = ""193 while index < characters.count, characters[index] == " " { trailing.append(" "); index += 1 }194 if index < characters.count, characters[index].isNewline { continue } // the newline branch flushes195 flush(trailing: trailing)196 }197 flush(trailing: "")198 return segments199 }200201 static func stripCitations(_ sentence: String) -> (text: String, ids: [Int]) {202 guard let citationPattern else { return (sentence, []) }203 let range = NSRange(sentence.startIndex..., in: sentence)204 var ids: [Int] = []205 for match in citationPattern.matches(in: sentence, range: range) {206 guard let group = Range(match.range(at: 1), in: sentence) else { continue }207 for part in sentence[group].split(separator: ",") {208 if let id = Int(part.trimmingCharacters(in: .whitespaces)), !ids.contains(id) { ids.append(id) }209 }210 }211 var clean = citationPattern.stringByReplacingMatches(in: sentence, range: range, withTemplate: "")212 for marker in [uncitedMarker, quoteMarker] { clean = clean.replacingOccurrences(of: marker, with: "") }213 return (clean.trimmingCharacters(in: .whitespaces), ids)214 }215216 /// A sentence that asserts something: at least three words with letters or digits, not a question, not a217 /// heading, not a statement that nothing was found. When in doubt it is a claim.218 static func isClaim(_ sentence: String) -> Bool {219 var text = sentence.trimmingCharacters(in: .whitespaces)220 while let first = text.first, "#-*•>".contains(first) || first == " " { text.removeFirst() }221 let words = text.split(whereSeparator: { $0.isWhitespace }).filter { $0.contains { $0.isLetter || $0.isNumber } }222 guard words.count >= 3 else { return false }223 if text.hasSuffix("?") || text.hasSuffix(":") { return false }224 let folded = AgentText.fold(text)225 if let nonClaim, nonClaim.firstMatch(in: folded, range: NSRange(folded.startIndex..., in: folded)) != nil { return false }226 return true227 }228229 static func quotes(in sentence: String) -> [String] {230 guard let quotePattern else { return [] }231 return quotePattern.matches(in: sentence, range: NSRange(sentence.startIndex..., in: sentence)).compactMap { match in232 (1...3).compactMap { Range(match.range(at: $0), in: sentence) }.first.map { String(sentence[$0]) }233 }234 }235236 static func contains(_ source: String, quote: String) -> Bool {237 var needle = AgentText.fold(quote)238 // An ellipsis or closing punctuation inside the quotation marks is the writer's, not the source's.239 while let last = needle.last, ".,;:!?… ".contains(last) { needle.removeLast() }240 return !needle.isEmpty && AgentText.fold(source).contains(needle)241 }242}243