| 156 | * keeps the contract is the no-card sentence. |
| 157 | */ |
| 158 | export function checkCitations( |
| 159 | answer: string, |
| 160 | cardIds: readonly string[], |
| 161 | options: CitationOptions = {}, |
| 162 | ): CitationCheck { |
| 163 | const known = new Set(cardIds); |
| 164 | const all = claimLines(answer); |
| 165 | const lines = options.truncated === true && all.length > 0 ? all.slice(0, -1) : all; |
| 166 | const violations: CitationViolation[] = []; |
| 167 | const cited: string[] = []; |
| 168 | const unknown: string[] = []; |
| 169 | const seenCited = new Set<string>(); |
| 170 | const seenUnknown = new Set<string>(); |
| 171 | |
| 172 | for (const line of lines) { |
| 173 | const ids = citationsIn(line); |
| 174 | if (ids.length === 0) { |
| 175 | violations.push({ line, reason: 'no-citation' }); |
| 176 | continue; |
| 177 | } |
| 178 | const bad = ids.filter((id) => !known.has(id)); |
| 179 | for (const id of ids) { |
| 180 | if (known.has(id) && !seenCited.has(id)) { |
| 181 | seenCited.add(id); |
| 182 | cited.push(id); |
| 183 | } |
| 184 | } |
| 185 | for (const id of bad) { |
| 186 | if (!seenUnknown.has(id)) { |
| 187 | seenUnknown.add(id); |
| 188 | unknown.push(id); |
| 189 | } |
| 190 | } |
| 191 | if (bad.length > 0) { |
| 192 | violations.push({ line, reason: 'unknown-card', unknown: bad }); |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | const trimmed = answer.trim(); |
| 197 | const noCardOnly = trimmed.length > 0 |
| 198 | && all.length === 0 |
| 199 | && isNoCardLine(trimmed); |
| 200 | |
| 201 | /* |
| 202 | * Whether anything was looked at. See {@link CitationCheck.measured}. |
| 203 | * |
| 204 | * The condition is the same one `ok` already carried; it is named here |
| 205 | * because the two questions it answered were never the same question. "Are |
| 206 | * there violations" and "was there anything to violate" only look alike |
| 207 | * while every answer has at least two lines. |
| 208 | */ |
| 209 | const measured = lines.length > 0 || noCardOnly; |
| 210 | |
| 211 | return { |
| 212 | ok: violations.length === 0 && measured, |
| 213 | cited, |
| 214 | unknown, |
| 215 | violations, |