Coverage for app / agents / source_ledger.py: 99%

467 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2What a run actually retrieved, and whether a draft's citations point at it. 

3 

4The evaluator is told to strike any citation it cannot trace to a source. It 

5used to trace them against ``<tool_calls>`` alone, which misses most of what a 

6run reads: 

7 

8* **Pipeline retrieval** — the knowledge lanes search the knowledge bases 

9 before any skill node runs, and ``__retrieval_join__`` records their 

10 passages in ``state.retrieval_citations``. No tool call is ever made, so every 

11 knowledge-base citation looked invented and was removed. That included a 

12 website source's pages, cited correctly by their title and URL. 

13* **Knowledge tools** append their sources as a ``__SOURCES__`` trailer at the 

14 *end* of the result, which the evaluator's 800-character preview cut off. 

15 The same cut hid every ``web_search`` result after the first few. 

16* **``url_fetch``** was not recognised as a source at all. 

17 

18So the ledger is built in code from the complete record — the pipeline's 

19structured citations plus every tool message, read in full — and each entry 

20of the draft's Sources section is checked against it here. The evaluator is 

21handed the ledger and the per-citation verdicts; deciding whether a citation 

22is real is no longer left to a model reading truncated text. 

23 

24Matching: a citation with a URL is verified only when that URL is one the run 

25retrieved (scheme, ``www.``, fragment and trailing slash aside). One without a 

26URL is verified when its text names, as whole words, a retrieved document 

27(with or without its extension), page title, graph entity, knowledge base or 

28pipeline id (``S3``). Nothing is verified by resembling a source the run did 

29not retrieve. 

30""" 

31 

32from __future__ import annotations 

33 

34import re 

35from dataclasses import dataclass 

36from typing import Any, Callable, Iterable, Literal, get_args 

37 

38from app import prompts 

39from app.tools.registry import ( 

40 EXPLORE_GRAPH_TOOL, 

41 READ_DOCUMENT_TOOL, 

42 SEARCH_KNOWLEDGE_TOOL, 

43) 

44from app.util import source_trailers 

45from app.util.attachments import READ_TOOL as READ_ATTACHMENT_TOOL 

46from app.util.attachments import SEARCH_TOOL as SEARCH_ATTACHMENTS_TOOL 

47from app.util.attachments import TOOL as ATTACHMENT_TOOL 

48from app.util.source_registry import norm_url as _norm_url 

49 

50#: What a tool's result is a source of: the web, a knowledge base's 

51#: passages, a knowledge graph, a document read in full, or anything else. 

52CitationKind = Literal["web", "knowledge", "graph", "document", "other"] 

53 

54#: Every tool whose result is a source, by its exact name — the one table 

55#: that says what each is. A name it does not hold is ``other``: a prefix 

56#: (``search_``, ``explore_``) made any tool so named read as a knowledge 

57#: search. ``list_documents`` lists names, not content, so it is no source. 

58#: ``retrieval`` and ``retrieval_graph`` are the pipeline's own citations 

59#: (``RetrievedPassage.citation``, ``GraphFact.citation``). 

60TOOL_KINDS: dict[str, CitationKind] = { 

61 "web_search": "web", 

62 "url_fetch": "web", 

63 SEARCH_KNOWLEDGE_TOOL: "knowledge", 

64 "query_knowledge_base": "knowledge", 

65 "retrieval": "knowledge", 

66 EXPLORE_GRAPH_TOOL: "graph", 

67 "query_knowledge_graph": "graph", 

68 "retrieval_graph": "graph", 

69 READ_DOCUMENT_TOOL: "document", 

70 # A document the person attached to the conversation 

71 # (``app/util/attachments.py``): cited by its id like any document, as 

72 # the run holds it and as its tools read it (``app/tools/attachments.py``). 

73 ATTACHMENT_TOOL: "document", 

74 READ_ATTACHMENT_TOOL: "document", 

75 SEARCH_ATTACHMENTS_TOOL: "document", 

76} 

77 

78#: The tools whose results are the person's attached documents. 

79_ATTACHMENT_TOOLS = frozenset( 

80 {ATTACHMENT_TOOL, READ_ATTACHMENT_TOOL, SEARCH_ATTACHMENTS_TOOL} 

81) 

82 

83 

84def tool_kind(name: str) -> CitationKind: 

85 """What a result of the tool named ``name`` is a source of.""" 

86 return TOOL_KINDS.get(name or "", "other") 

87 

88 

89def with_kind(citation: dict[str, Any]) -> dict[str, Any]: 

90 """``citation`` with its ``kind``: what its tool's results are a source 

91 of (``tool_kind``). A kind it already carries is kept.""" 

92 if citation.get("kind") in get_args(CitationKind): 

93 return citation 

94 return {**citation, "kind": tool_kind(str(citation.get("tool") or ""))} 

95 

96 

97# ─── What a tool's result cites ───────────────────────────────────────────── 

98 

99 

100#: The line a tool result's block opens with inside a run: the id the answer 

101#: cites it by (``util/source_registry.cite_line``). 

102_CITE_AS = re.compile(r"^Cite as: \[(S\d+)\]$") 

103 

104 

105def _cite_as(line: str) -> str | None: 

106 match = _CITE_AS.match(line) 

107 return match.group(1) if match else None 

108 

109 

110def _search_results(content: str) -> list[dict[str, Any]]: 

111 """A ``web_search`` result's pages: each ``Title:`` / ``URL:`` pair, with 

112 the ``Cite as:`` id that opens its block inside a run 

113 (``tools/web/search.format_result``).""" 

114 out: list[dict[str, Any]] = [] 

115 title: str | None = None 

116 sid: str | None = None 

117 for line in content.splitlines(): 

118 line = line.strip() 

119 if _cite_as(line): 

120 sid = _cite_as(line) 

121 elif line.startswith("Title: "): 

122 title = line[7:] 

123 elif line.startswith("URL: "): 

124 url = line[5:].strip() 

125 if url: 

126 page: dict[str, Any] = {"source": url, "title": title or url} 

127 if sid: 

128 page["citation_id"] = sid 

129 out.append(page) 

130 title = sid = None 

131 return out 

132 

133 

134def _fetched_page(content: str) -> list[dict[str, Any]]: 

135 """The page a ``url_fetch`` result read, from its header lines — its 

136 ``Cite as:`` id inside a run, then ``URL:`` then ``Title:``, the reverse 

137 of a search result's order (``tools/web/fetch.format_page``). An error 

138 message names no page.""" 

139 url = title = sid = None 

140 for line in content.splitlines()[:5]: 

141 line = line.strip() 

142 if _cite_as(line) and sid is None: 

143 sid = _cite_as(line) 

144 elif line.startswith("URL: ") and url is None: 

145 url = line[5:].strip() 

146 elif line.startswith("Title: ") and title is None: 

147 title = line[7:].strip() 

148 if not url: 

149 return [] 

150 page: dict[str, Any] = {"source": url, "title": title or url, "url": url} 

151 if sid: 

152 page["citation_id"] = sid 

153 return [page] 

154 

155 

156def _trailer(marker: str) -> Callable[[str], list[dict[str, Any]]]: 

157 """A parser of the sources trailer a knowledge tool ends its result with 

158 (``app.util.source_trailers``): each entry a source's name, or 

159 ``{"source", "kb_name"}`` when the result says which knowledge base it 

160 came from.""" 

161 

162 def parse(content: str) -> list[dict[str, Any]]: 

163 out: list[dict[str, Any]] = [] 

164 for entry in source_trailers.split(content, marker)[1]: 

165 sid = None 

166 if isinstance(entry, dict): 

167 source, kb_name = entry.get("source"), entry.get("kb_name") 

168 sid = entry.get("citation_id") 

169 else: 

170 source, kb_name = entry, None 

171 if not isinstance(source, str) or not source: 

172 continue 

173 citation: dict[str, Any] = {"source": source, "title": source} 

174 if isinstance(kb_name, str) and kb_name: 

175 citation["kb_name"] = kb_name 

176 if isinstance(sid, str) and _CITE_AS.match(f"Cite as: [{sid}]"): 

177 citation["citation_id"] = sid 

178 out.append(citation) 

179 return out 

180 

181 return parse 

182 

183 

184#: How each tool's result names its sources, by the tool's exact name — the 

185#: tools ``TOOL_KINDS`` calls sources, less the pipeline's own (whose 

186#: citations it builds itself). A tool without an entry cites nothing: a 

187#: prefix (``search_``, ``explore_``, ``files_``) once made any tool so named 

188#: read as a knowledge search. 

189CITATION_PARSERS: dict[str, Callable[[str], list[dict[str, Any]]]] = { 

190 "web_search": _search_results, 

191 "url_fetch": _fetched_page, 

192 SEARCH_KNOWLEDGE_TOOL: _trailer(source_trailers.KNOWLEDGE), 

193 "query_knowledge_base": _trailer(source_trailers.KNOWLEDGE), 

194 EXPLORE_GRAPH_TOOL: _trailer(source_trailers.GRAPH), 

195 "query_knowledge_graph": _trailer(source_trailers.GRAPH), 

196 READ_DOCUMENT_TOOL: _trailer(source_trailers.DOCUMENT), 

197 READ_ATTACHMENT_TOOL: _trailer(source_trailers.DOCUMENT), 

198 SEARCH_ATTACHMENTS_TOOL: _trailer(source_trailers.DOCUMENT), 

199} 

200 

201 

202def result_citations(tool: str, content: str) -> list[dict[str, Any]]: 

203 """The sources one result of the tool named ``tool`` cites, in its order: 

204 each ``{tool, source, title, kind}``, plus ``url`` for a page read and 

205 ``kb_name`` when the result names its knowledge base. ``[]`` for a tool 

206 that is no source, and for a result that names none.""" 

207 parser = CITATION_PARSERS.get(tool or "") 

208 if parser is None or not isinstance(content, str) or not content: 

209 return [] 

210 kind = tool_kind(tool) 

211 return [{"tool": tool, **c, "kind": kind} for c in parser(content)] 

212 

213 

214def message_citations(messages: Iterable[Any]) -> list[dict[str, Any]]: 

215 """Every source the tool results among ``messages`` cite, in order. 

216 

217 Only a tool's result: a node's own reply is named after the node 

218 (``graph._name_node_messages``), and a skill node called ``web_search`` 

219 wrote an answer, not a search result. 

220 """ 

221 out: list[dict[str, Any]] = [] 

222 for msg in messages or []: 

223 if getattr(msg, "tool_call_id", None) is None: 

224 continue 

225 out += result_citations( 

226 str(getattr(msg, "name", "") or ""), getattr(msg, "content", "") 

227 ) 

228 return out 

229 

230 

231#: How ``ToolNode`` words a tool that raised, as the model is sent it 

232#: (langgraph's ``TOOL_CALL_ERROR_TEMPLATE``, ``Error: {error}…``). 

233RAISED_TOOL_PREFIX = "Error: " 

234#: How ``ToolNode`` answers a call to a tool the step does not hold 

235#: (langgraph's ``INVALID_TOOL_NAME_ERROR_TEMPLATE``). 

236_NOT_HELD = re.compile(r"^Error: (\S+) is not a valid tool, try one of \[") 

237#: What a reader is shown in its place: nothing ran. 

238NOT_HELD_NOTE = ( 

239 "Not run: this step does not hold {tool}, so nothing was called — it is " 

240 "no result of that tool, and no sign it failed." 

241) 

242 

243 

244def not_held(text: object) -> str | None: 

245 """The tool a result says the step does not hold, or None. The quality 

246 check read Research brief's writing step calling ``render_document``, a 

247 tool its workflow keeps to a later step, as "the render_document tool 

248 failed", and failed a delivered document twice.""" 

249 match = _NOT_HELD.match(text) if isinstance(text, str) else None 

250 return match.group(1) if match else None 

251 

252 

253def tool_failed(text: str) -> bool: 

254 """True when a tool's result is a failure: the tool's own report of 

255 failing — how every built-in tool answers when it could not do its work — 

256 or ``ToolNode``'s for a tool that raised.""" 

257 return text.startswith(("Tool error:", "Unknown tool:", RAISED_TOOL_PREFIX)) 

258 

259 

260def web_answered(messages: Iterable[Any]) -> bool: 

261 """True when the web answered in this run: a web tool returned at least 

262 one result — a search that listed a page, or a page that was read. 

263 

264 A web tool's error is no answer, and neither is a search that matched 

265 nothing (``No results for "…"``) or one past its call limit: neither 

266 names a page, so nothing came from the web for the answer to rest on. 

267 """ 

268 for msg in messages or []: 

269 if getattr(msg, "tool_call_id", None) is None: 

270 continue 

271 name = str(getattr(msg, "name", "") or "") 

272 if tool_kind(name) != "web": 

273 continue 

274 content = getattr(msg, "content", "") 

275 if getattr(msg, "status", "success") == "error" or not isinstance(content, str): 

276 continue 

277 if not tool_failed(content) and result_citations(name, content): 

278 return True 

279 return False 

280 

281 

282def web_searched(messages: Iterable[Any]) -> bool: 

283 """True when a web tool ran in this run, whatever it found: a search 

284 that matched nothing or failed still looked. Unlike :func:`web_answered`, 

285 which asks whether the web gave the answer anything to rest on.""" 

286 return any( 

287 getattr(msg, "tool_call_id", None) is not None 

288 and tool_kind(str(getattr(msg, "name", "") or "")) == "web" 

289 for msg in messages or [] 

290 ) 

291 

292 

293SourceKind = Literal[ 

294 "knowledge_document", 

295 "knowledge_page", 

296 "knowledge_graph", 

297 "knowledge_link", 

298 "knowledge_referrer", 

299 "web_search", 

300 "web_page", 

301 "document", 

302 "attached_document", 

303 "other", 

304] 

305 

306_KIND_LABEL: dict[str, str] = { 

307 "knowledge_document": "knowledge base document", 

308 "knowledge_page": "knowledge base web page", 

309 "knowledge_graph": "knowledge graph", 

310 "knowledge_link": "linked from a knowledge base page", 

311 "knowledge_referrer": "knowledge base page that linked here", 

312 "web_search": "web search result", 

313 "web_page": "fetched web page", 

314 "document": "document read", 

315 "attached_document": "document the person attached", 

316 "other": "tool result", 

317} 

318 

319#: Ledger entries listed to the evaluator. Verdicts cover every citation 

320#: regardless; this only bounds the reference list in its prompt. 

321MAX_LISTED = 80 

322#: A name shorter than this is too generic to match on ("FAQ", "Docs"). 

323_MIN_NAME = 4 

324#: A file name's extension: ``.md``, ``.pdf``, ``.docx``. 

325_EXTENSION = re.compile(r"\.[A-Za-z][A-Za-z0-9]{0,7}$") 

326 

327 

328def _stems(names: Iterable[str]) -> list[str]: 

329 """Each file name among ``names`` without its extension: models name a 

330 document as a title reads — "Employee Handbook", "03-agents" — not as 

331 its file is called.""" 

332 return [ 

333 _EXTENSION.sub("", name) 

334 for name in names 

335 if "://" not in name and _EXTENSION.search(name) 

336 ] 

337 

338 

339@dataclass(frozen=True) 

340class LedgerSource: 

341 kind: str 

342 title: str 

343 url: str = "" 

344 source: str = "" 

345 kb_name: str = "" 

346 citation_id: str = "" 

347 #: A deep citation's parent: the retrieved page this source was linked 

348 #: from (``knowledge_link``) or that linked to a retrieved page 

349 #: (``knowledge_referrer``). 

350 via: str = "" 

351 

352 def names(self) -> list[str]: 

353 """Every name this source may be cited by.""" 

354 out = [self.title, self.source] 

355 if self.source and "/" in self.source and "://" not in self.source: 

356 out.append(self.source.rsplit("/", 1)[-1]) # a path's filename 

357 if not self.url: 

358 out += _stems(out) 

359 out.append(self.kb_name) 

360 return [n for n in out if n and len(n.strip()) >= _MIN_NAME] 

361 

362 

363@dataclass(frozen=True) 

364class CitedSource: 

365 marker: str 

366 text: str 

367 url: str = "" 

368 

369 

370@dataclass(frozen=True) 

371class CitationCheck: 

372 marker: str 

373 text: str 

374 status: prompts.CitationStatus 

375 match: LedgerSource | None = None 

376 

377 

378# ─── Building the ledger ───────────────────────────────────────────────────── 

379 

380 

381def _looks_like_url(value: str) -> bool: 

382 return value.startswith(("http://", "https://")) 

383 

384 

385def _from_retrieval(citation: dict[str, Any]) -> LedgerSource: 

386 tool = str(citation.get("tool") or "") 

387 url = str(citation.get("url") or "") 

388 source = str(citation.get("source") or "") 

389 if tool in _ATTACHMENT_TOOLS: 

390 kind = "attached_document" 

391 elif tool == "retrieval_graph": 

392 kind = "knowledge_graph" 

393 elif url or _looks_like_url(source): 

394 kind = "knowledge_page" 

395 else: 

396 kind = "knowledge_document" 

397 return LedgerSource( 

398 kind=kind, 

399 title=str(citation.get("title") or source), 

400 url=url or (source if _looks_like_url(source) else ""), 

401 source=source, 

402 kb_name=str(citation.get("kb_name") or ""), 

403 citation_id=str(citation.get("citation_id") or ""), 

404 ) 

405 

406 

407def _from_tool(citation: dict[str, Any]) -> LedgerSource: 

408 tool = str(citation.get("tool") or "") 

409 source = str(citation.get("source") or "") 

410 cited = tool_kind(tool) 

411 kind: SourceKind 

412 if tool in _ATTACHMENT_TOOLS: 

413 kind = "attached_document" 

414 elif cited == "web": 

415 kind = "web_page" if tool == "url_fetch" else "web_search" 

416 elif cited == "document": 

417 kind = "document" 

418 elif cited == "graph": 

419 kind = "knowledge_graph" 

420 elif cited == "knowledge": 

421 kind = "knowledge_page" if _looks_like_url(source) else "knowledge_document" 

422 else: 

423 kind = "other" 

424 return LedgerSource( 

425 kind=kind, 

426 title=str(citation.get("title") or source), 

427 url=str(citation.get("url") or (source if _looks_like_url(source) else "")), 

428 source=source, 

429 kb_name=str(citation.get("kb_name") or ""), 

430 citation_id=str(citation.get("citation_id") or ""), 

431 ) 

432 

433 

434def _deep_links(citation: dict[str, Any]) -> list[LedgerSource]: 

435 """The pages a retrieved web passage links to, and the pages that linked 

436 to it — both legitimately citable, each marked with the page it hangs 

437 off. Citing an aggregator's entry by the article it links is the point 

438 of a deep citation, not a fabrication.""" 

439 parent = str(citation.get("title") or citation.get("url") or "") 

440 kb_name = str(citation.get("kb_name") or "") 

441 out = [] 

442 for link in citation.get("links") or []: 

443 url = str((link or {}).get("url") or "") 

444 if _looks_like_url(url): 

445 out.append( 

446 LedgerSource( 

447 kind="knowledge_link", 

448 title=str(link.get("text") or url), 

449 url=url, 

450 source=url, 

451 kb_name=kb_name, 

452 via=parent, 

453 ) 

454 ) 

455 for referrer in citation.get("via") or []: 

456 url = str((referrer or {}).get("url") or "") 

457 if _looks_like_url(url): 

458 out.append( 

459 LedgerSource( 

460 kind="knowledge_referrer", 

461 title=str(referrer.get("title") or url), 

462 url=url, 

463 source=url, 

464 kb_name=kb_name, 

465 via=parent, 

466 ) 

467 ) 

468 return out 

469 

470 

471def _called_tools(messages: Iterable[Any]) -> list[LedgerSource]: 

472 """Every tool that answered in this run, as a source named by the tool. 

473 

474 ``CITATION_PARSERS`` knows the tools whose results carry their own 

475 sources (web search, fetched pages, documents, knowledge). Any other tool 

476 — an agent's own, or a case's scripted one — returns data with no URL, and 

477 an answer that cites it ("lookup_order") cited something real: the 

478 evaluator was told such a citation was fabricated, and failed it. 

479 """ 

480 out: list[LedgerSource] = [] 

481 for msg in messages: 

482 if getattr(msg, "tool_call_id", None) is None: 

483 continue 

484 name = str(getattr(msg, "name", "") or "") 

485 if name: 

486 out.append(LedgerSource(kind="other", title=name, source=name)) 

487 return out 

488 

489 

490def build_ledger( 

491 retrieval_citations: Iterable[dict[str, Any]], messages: Iterable[Any] 

492) -> list[LedgerSource]: 

493 """Every source the run retrieved: pipeline retrieval first (its ``S#`` 

494 ids are what agents were told to cite), then the pages those passages 

495 link to or were linked from (deep citations), then tool results, then 

496 every tool that answered, de-duplicated.""" 

497 ledger: list[LedgerSource] = [] 

498 seen: set[tuple[str, str, str]] = set() 

499 retrieval = list(retrieval_citations or []) 

500 messages = list(messages or []) 

501 entries = ( 

502 [_from_retrieval(c) for c in retrieval] 

503 + [link for c in retrieval for link in _deep_links(c)] 

504 + [_from_tool(c) for c in message_citations(messages)] 

505 + _called_tools(messages) 

506 ) 

507 for entry in entries: 

508 # By URL (or name) alone: a page both retrieved and linked from 

509 # another retrieved page is one source — the retrieved form, listed 

510 # first, wins. 

511 key = ("", _norm_url(entry.url) or entry.source, entry.kb_name) 

512 if key in seen: 

513 continue 

514 seen.add(key) 

515 ledger.append(entry) 

516 return ledger 

517 

518 

519# ─── Reading the draft's citations ────────────────────────────────────────── 

520 

521_SOURCES_WORD = r"(?:sources?|references?|citations?)" 

522#: A heading alone on its line, singular or plural, with the count some 

523#: models add: ``**Sources (5)**``, ``## References``, ``Source:``. 

524_SOURCES_HEADING = re.compile( 

525 rf"^\s{{0,3}}(?:#{{1,6}}\s*)?(?:\*\*|__)?\s*{_SOURCES_WORD}\s*" 

526 r"(?:\(\s*\d+\s*\)\s*)?(?:\*\*|__)?\s*:?\s*(?:\*\*|__)?\s*$", 

527 re.IGNORECASE, 

528) 

529#: "Source" with its entries on the line: ``Sources: [BBC](…), [Reuters](…)``, 

530#: ``**Source:** 03-agents.md``. The colon is required: prose that opens 

531#: with the word ("Sources say …") lists nothing. Only "source": a 

532#: ``Citation:`` or ``Reference:`` label on a line names a case or a 

533#: standard as often as where an answer came from. 

534_SOURCES_INLINE = re.compile( 

535 r"^\s*(?:[-*•+]\s+)?(?:\*\*|__)?\s*sources?\s*(?:\(\s*\d+\s*\)\s*)?" 

536 r"(?:\*\*|__)?\s*:\s*(?:\*\*|__)?\s*(?P<rest>\S.*?)\s*$", 

537 re.IGNORECASE, 

538) 

539#: ``[1] Title``. A bracket opening a markdown link (``[Reuters](https://…)``) 

540#: is the link's text, not a marker. 

541_ENTRY = re.compile(r"^\s*(?:[-*•]\s*)?\[(\w+)\](?!\()\s*[:.\-–—]?\s*(.+?)\s*$") 

542_NUMBERED = re.compile(r"^\s*(\d+)[.)]\s+(.+?)\s*$") 

543#: An unmarked bullet, read with or without a link: ``- [Headline](https://…)``, 

544#: as gpt-oss lists its sources, or ``- 03-agents.md — CHAIN-R User Guide``. 

545_BULLET = re.compile(r"^\s*[-*•+]\s+(.+?)\s*$") 

546_MD_LINK = re.compile(r"\[([^\]]+)\]\((https?://[^)\s]+)\)") 

547_BARE_URL = re.compile(r"https?://[^\s)>\]]+") 

548#: An unbulleted line read as an entry only when it is a link or a URL 

549#: itself, with at most a short tail: ``[Headline](https://…) — Reuters``. A 

550#: sentence that carries a link ("The Met Office has it at https://…") is 

551#: not one. 

552_LINK_LINE = re.compile( 

553 r"^\s*(?:\[[^\]]+\]\(https?://[^)\s]+\)|https?://[^\s)>\]]+)(?P<tail>.*?)\s*$" 

554) 

555_LINK_TAIL_CHARS = 80 

556#: What ends a URL written in prose rather than belonging to it. 

557_URL_TRAILER = ".,;:!?'\"*_" 

558 

559 

560def _entry(marker: str, rest: str) -> CitedSource: 

561 link = _MD_LINK.search(rest) 

562 if link: 

563 url = link.group(2) 

564 text = _MD_LINK.sub(lambda m: m.group(1), rest) 

565 else: 

566 bare = _BARE_URL.search(rest) 

567 url = bare.group(0).rstrip(_URL_TRAILER) if bare else "" 

568 text = rest 

569 return CitedSource(marker=marker, text=text.strip(" *_"), url=url) 

570 

571 

572def _list_entry(line: str) -> CitedSource | None: 

573 """``line`` as an entry of a Sources list, or None when it is not 

574 list-shaped: a marked line (``[1] …``), a numbered one, a bullet, or a 

575 line that is a link or URL with at most a short tail.""" 

576 match = _ENTRY.match(line) or _NUMBERED.match(line) 

577 if match: 

578 return _entry(match.group(1), match.group(2)) 

579 if bullet := _BULLET.match(line): 

580 return _entry("", bullet.group(1)) 

581 linked = _LINK_LINE.match(line) 

582 if linked and len(linked.group("tail").strip()) <= _LINK_TAIL_CHARS: 

583 return _entry("", line.strip()) 

584 return None 

585 

586 

587def _inline_entries(rest: str) -> list[CitedSource]: 

588 """The entries of an inline ``Sources: …`` line: each link or URL one, 

589 else the line's text as one.""" 

590 out = [ 

591 CitedSource(marker="", text=m.group(1).strip(" *_"), url=m.group(2)) 

592 for m in _MD_LINK.finditer(rest) 

593 ] 

594 plain = _MD_LINK.sub(" ", rest) 

595 out += [ 

596 CitedSource(marker="", text=url, url=url) 

597 for url in (u.rstrip(_URL_TRAILER) for u in _BARE_URL.findall(plain)) 

598 ] 

599 if out: 

600 return out 

601 text = rest.strip(" *_.") 

602 return [CitedSource(marker="", text=text)] if text else [] 

603 

604 

605def parse_sources_section(draft: str) -> list[CitedSource]: 

606 """The entries of the draft's Sources sections, in order. 

607 

608 A section opens at a heading alone on its line — ``**Sources**``, 

609 ``## References``, ``Source:``, with a count or without — and its 

610 entries are the list-shaped lines that follow it: the forms the response 

611 standards ask for (``[1] [Title](url)``, ``[S2] Name (knowledge base)``) 

612 and numbered lines, any bullet — with a link or without, its marker 

613 ``""`` — and a line that is a link or URL with at most a short tail. 

614 Prose before the first entry is passed over; once one has been read, a 

615 line that is not list-shaped ends the section, as does the next heading. 

616 An inline ``Source(s): …`` line, wherever it stands, lists its own: each 

617 link or URL on it is an entry, else its text is one. A draft with none 

618 cites nothing checkable here. Markers a model wrote its own way 

619 (``【1】``) are read once ``normalise_citation_markers`` has rewritten 

620 them. 

621 """ 

622 cited: list[CitedSource] = [] 

623 in_section = read = False 

624 for line in draft.splitlines(): 

625 if _SOURCES_HEADING.match(line): 

626 in_section, read = True, False 

627 continue 

628 if inline := _SOURCES_INLINE.match(line): 

629 entries = _inline_entries(inline.group("rest")) 

630 cited.extend(entries) 

631 read = read or (in_section and bool(entries)) 

632 continue 

633 if not in_section or not line.strip(): 

634 continue 

635 if line.lstrip().startswith("#"): 

636 in_section = False # the next section 

637 continue 

638 entry = _list_entry(line) 

639 if entry is not None: 

640 cited.append(entry) 

641 read = True 

642 elif read: 

643 in_section = False # prose after the list 

644 return cited 

645 

646 

647# ─── Matching ──────────────────────────────────────────────────────────────── 

648 

649 

650def _norm_text(value: str) -> str: 

651 """``value`` lowercased with every run of other characters one space, so 

652 names compare whole word by whole word whatever separates them — the 

653 hyphens models write (‐ ‑ ‒ – —, gpt-oss's "03‑agents") read as ``-`` 

654 does.""" 

655 return re.sub(r"[^\w]+", " ", value.lower()).strip() 

656 

657 

658def _match(cited: CitedSource, ledger: list[LedgerSource]) -> LedgerSource | None: 

659 """The retrieved source a citation points at, or None. 

660 

661 A citation that carries a URL is identified by it: a real page title 

662 beside a URL the run never fetched is how a fabricated citation looks, so 

663 the name alone must not rescue it. An entry marked with a pipeline id 

664 (``[S3] …``, as the response standards write knowledge) is identified by 

665 that id alone: an id the run never handed out is fabricated, whatever the 

666 entry names. Otherwise a pipeline id or a retrieved name — document or 

667 page title first, a knowledge base's name last, since every passage of it 

668 carries that — appearing as whole words in the citation's text 

669 identifies it. 

670 """ 

671 if cited.url: 

672 target = _norm_url(cited.url) 

673 for entry in ledger: 

674 if target and target in (_norm_url(entry.url), _norm_url(entry.source)): 

675 return entry 

676 return None 

677 if _PIPELINE_ID.fullmatch(cited.marker or ""): 

678 wanted = cited.marker.upper() 

679 return next((e for e in ledger if e.citation_id.upper() == wanted), None) 

680 text = f" {_norm_text(cited.text)} " 

681 if not text.strip(): 

682 return None 

683 for entry in ledger: 

684 if entry.citation_id and f" {entry.citation_id.lower()} " in text: 

685 return entry 

686 for named in (_document_names, _knowledge_base_name): 

687 for entry in ledger: 

688 for name in named(entry): 

689 normalised = _norm_text(name) 

690 if normalised and f" {normalised} " in text: 

691 return entry 

692 return None 

693 

694 

695#: A Sources entry's marker that is a pipeline id: ``S3``. 

696_PIPELINE_ID = re.compile(r"S\d+", re.IGNORECASE) 

697 

698 

699def _document_names(entry: LedgerSource) -> list[str]: 

700 return [name for name in entry.names() if name != entry.kb_name] 

701 

702 

703def _knowledge_base_name(entry: LedgerSource) -> list[str]: 

704 return [entry.kb_name] if entry.kb_name in entry.names() else [] 

705 

706 

707def verify_citations( 

708 cited: list[CitedSource], ledger: list[LedgerSource] 

709) -> list[CitationCheck]: 

710 checks = [] 

711 for c in cited: 

712 match = _match(c, ledger) 

713 checks.append( 

714 CitationCheck( 

715 marker=c.marker, 

716 text=c.text, 

717 status=( 

718 prompts.CITATION_VERIFIED if match else prompts.CITATION_UNMATCHED 

719 ), 

720 match=match, 

721 ) 

722 ) 

723 return checks 

724 

725 

726def verify_markers(draft: str, registry: Any) -> list[CitationCheck]: 

727 """The source each id the draft cites names, as the quality check reads 

728 it: every id the run handed out is verified by code. A marker that names 

729 no source is not listed — it is a citation problem the agent revises 

730 (``answer_sources.check_markers``), never the check's to judge.""" 

731 if not draft or registry is None: 

732 return [] 

733 prose = _CODE.sub(" ", normalise_citation_markers(draft)) 

734 checks: list[CitationCheck] = [] 

735 seen: set[str] = set() 

736 # Grouped markers too: "[S1, S2]" had verified neither, and a draft that 

737 # cited only in groups read as citing nothing. 

738 for sid in (sid for g in SID_GROUP.findall(prose) for sid in ids_in_group(g)): 

739 citation = registry.get(sid) 

740 if citation is None or sid in seen: 

741 continue 

742 seen.add(sid) 

743 match = _from_tool(citation) 

744 checks.append( 

745 CitationCheck( 

746 marker=sid, 

747 text=match.title, 

748 status=prompts.CITATION_VERIFIED, 

749 match=match, 

750 ) 

751 ) 

752 return checks 

753 

754 

755# ─── What an answer cites ──────────────────────────────────────────────────── 

756 

757#: An inline marker: ``[3]`` or ``[S3]`` — not a link's text or target. 

758_MARKER = re.compile(r"(?<![\w\]])(?<!\]\()\[(S?\d{1,3})\](?!\()") 

759#: Pipeline ids cited inline, alone or grouped: ``[S3]``, ``[S1, S3]``, 

760#: ``[S1; 2]``. Unlike a number an id is never an index, so it may follow a 

761#: word or another marker: "agent[S1]", "[S1][S2]". Never a link's text 

762#: (``[S3](…)``) nor its target. 

763SID_GROUP = re.compile( 

764 r"(?<!\]\()\[\s*(S\d{1,3}(?:\s*[,;]\s*S?\d{1,3})*)\s*\](?!\()", 

765 re.IGNORECASE, 

766) 

767_ONE_SID = re.compile(r"S?(\d{1,3})", re.IGNORECASE) 

768 

769 

770def ids_in_group(group: str) -> list[str]: 

771 """The ids of one :data:`SID_GROUP` match, as ``S``-numbers.""" 

772 return [f"S{n}" for n in _ONE_SID.findall(group)] 

773 

774 

775#: Code is not prose: a marker inside it cites nothing. 

776_CODE = re.compile(r"```.*?(?:```|$)|`[^`\n]*`", re.DOTALL) 

777 

778#: A marker in the brackets some models write in place of ``[3]``: 

779#: lenticular (gpt-oss's ``【3】``), fullwidth square or tortoise-shell, with 

780#: ASCII or fullwidth digits. A pipeline id (``【S3】``) is kept as one. 

781_WIDE_MARKER = re.compile( 

782 r"【\s*([SS]?[0-90-9]{1,3})\s*】" 

783 r"|[\s*([SS]?[0-90-9]{1,3})\s*]" 

784 r"|〔\s*([SS]?[0-90-9]{1,3})\s*〕" 

785) 

786#: gpt-oss's references into its tool output — cursor references 

787#: (``【3†L1-L5】``, ``【4†source】``, ``【12:3†L2】``) and browsing ids 

788#: (``【turn0search3】``, ``【turn1view0†L4】``) — which the reader never 

789#: sees: removed, with the space before them. Any other ``【…】`` is text — 

790#: a Chinese or Japanese heading, label or date (``【重要】``, 

791#: ``【2024年10月】``) — and stays as written. 

792_TOOL_REFERENCE = re.compile( 

793 r"[ \t]*【(?:\d+(?::\d+)?†[^】\n]*|turn\d+[a-z]+\d+(?:†[^】\n]*)?)】" 

794) 

795_WIDE_OPENERS = ("【", "[", "〔") 

796_FULLWIDTH = str.maketrans("0123456789S", "0123456789S") 

797#: What a marker cannot follow and still be read as one (``_MARKER``): a 

798#: word character, or another marker's ``]``. 

799_GLUED = re.compile(r"[\w\]]") 

800 

801 

802def _normalise_prose(text: str) -> str: 

803 text = _TOOL_REFERENCE.sub("", text) 

804 out: list[str] = [] 

805 before = "" # the last character written 

806 last = 0 

807 for m in _WIDE_MARKER.finditer(text): 

808 if m.start() > last: 

809 out.append(text[last : m.start()]) 

810 before = text[m.start() - 1] 

811 marker = next(g for g in m.groups() if g).translate(_FULLWIDTH) 

812 # gpt-oss glues its markers on — "agent【S1】", "【S1】【S2】" — which, 

813 # rewritten in place, no reader of ``[n]`` would see as markers; and 

814 # "headline【1】and" would read "headline [1]and". 

815 after = text[m.end() : m.end() + 1] 

816 out.append( 

817 f"{' ' if _GLUED.fullmatch(before) else ''}[{marker}]" 

818 f"{' ' if after.isalnum() else ''}" 

819 ) 

820 before = "]" 

821 last = m.end() 

822 out.append(text[last:]) 

823 return "".join(out) 

824 

825 

826def tidy_answer(text: str) -> str: 

827 """An answer as it ships: its citation markers written ``[n]`` 

828 (:func:`normalise_citation_markers`) and its links made to render 

829 (``documents.markdown.tidy_answer_links``: bracketed targets unwrapped, a 

830 Wikimedia file page drawn as its picture). Kept apart from the marker 

831 pass, which also reads drafts for what they cite: a rewritten image link 

832 would no longer credit the page it named. Idempotent.""" 

833 from app.common.settings import get_settings 

834 from app.documents.markdown import tidy_answer_links 

835 

836 return tidy_answer_links(normalise_citation_markers(text), get_settings()) 

837 

838 

839def normalise_citation_markers(text: str) -> str: 

840 """``text`` with its citation markers written ``[n]``. 

841 

842 gpt-oss writes ``【1】`` and leaves references into its tool output 

843 (``【3†L1-L5】``, ``【turn0search3】``) in its answer: the evaluator found 

844 no Sources entry to check, and the reply showed the person references 

845 they cannot open. ``【n】``, ``[n]`` and ``〔n〕`` (ASCII or fullwidth 

846 digits, ``S`` for a pipeline id) become ``[n]``, set apart by a space 

847 from a word or a marker it was glued to (``agent [S1]``, ``[S1] [S2]``); 

848 those references are removed. Every other ``【…】`` — Chinese and 

849 Japanese use them for headings, labels and dates — is text and stays. 

850 Code — fences and inline spans — is left as written. Idempotent. 

851 """ 

852 if not text or not any(opener in text for opener in _WIDE_OPENERS): 

853 return text 

854 out: list[str] = [] 

855 last = 0 

856 for code in _CODE.finditer(text): 

857 out.append(_normalise_prose(text[last : code.start()])) 

858 out.append(code.group(0)) 

859 last = code.end() 

860 out.append(_normalise_prose(text[last:])) 

861 return "".join(out) 

862 

863 

864def _citation_names(citation: dict[str, Any]) -> list[str]: 

865 """What a citation may be named by in a Sources entry — its own title, 

866 source and filename, each also without its extension ("03-agents", 

867 "Employee Handbook"), never its knowledge base's name: naming the user 

868 guide names every passage of it.""" 

869 source = str(citation.get("source") or "") 

870 names = [str(citation.get("title") or ""), source] 

871 if source and "/" in source and "://" not in source: 

872 names.append(source.rsplit("/", 1)[-1]) 

873 if not _citation_urls(citation): # a page's title is no file name 

874 names += _stems(names) 

875 return [n for n in names if len(n.strip()) >= _MIN_NAME] 

876 

877 

878def _citation_urls(citation: dict[str, Any]) -> set[str]: 

879 return { 

880 _norm_url(str(citation.get("url") or "")), 

881 _norm_url(str(citation.get("source") or "")), 

882 } - {""} 

883 

884 

885def _document(citation: dict[str, Any]) -> str: 

886 """The page or document a citation is a passage of: its URL, else its 

887 knowledge base and document id, else its name in its knowledge base — a 

888 README.md in two knowledge bases is two documents.""" 

889 url = min(_citation_urls(citation), default="") 

890 if url: 

891 return url 

892 kb = str(citation.get("kb_id") or citation.get("kb_name") or "") 

893 if citation.get("document_id"): 

894 return f"{kb}\x00{citation['document_id']}" 

895 name = _norm_text(str(citation.get("source") or citation.get("title") or "")) 

896 return f"{kb}\x00{name}" 

897 

898 

899def _linked_urls(prose: str) -> list[str]: 

900 """Every URL the prose links or writes out, normalised, in order.""" 

901 out: list[str] = [] 

902 for raw in _BARE_URL.findall(prose): 

903 url = _norm_url(raw.rstrip(_URL_TRAILER)) 

904 if url and url not in out: 

905 out.append(url) 

906 return out 

907 

908 

909#: A pipeline id written in an entry's text: ``S3``. 

910_SID = re.compile(r"\bs\d{1,3}\b") 

911 

912 

913def cited_citations( 

914 draft: str, citations: list[dict[str, Any]] 

915) -> list[dict[str, Any]]: 

916 """The citations ``draft`` uses, in their order — what its sources are. 

917 

918 A run's citations are everything it retrieved, before any answer was 

919 written; the chat showed every one under the answer as a source, so a 

920 passage the answer never used — the user guide, for a question about 

921 today's news — read as something it rested on. A citation counts as 

922 used only on exact evidence that the draft names it: 

923 

924 * its pipeline id, ``[S3]`` — inline anywhere, as a Sources entry's 

925 marker, or in an entry's text; 

926 * its URL, linked or written out anywhere in the draft (scheme, 

927 ``www.``, fragment and trailing slash aside); 

928 * its document's name, title or file name, with or without its 

929 extension, in a Sources entry (never its knowledge base's: that names 

930 every passage of it). 

931 

932 A page or document is shown once: an id names its passage, and a URL or 

933 a name the first passage of a page or document no id has named. 

934 

935 A number is never read as a citation's: the model numbers its Sources 

936 section as it likes, and the run numbered its citations in the order it 

937 retrieved them, so ``[1]`` beside a web headline had credited the run's 

938 first passage — a user guide page — with the headline. A number alone, 

939 with no id, URL or name: nothing is cited, and there is no source to 

940 show. 

941 """ 

942 if not draft or not citations: 

943 return [] 

944 prose = _CODE.sub(" ", normalise_citation_markers(draft)) 

945 by_sid = { 

946 str(c.get("citation_id")).upper(): i 

947 for i, c in enumerate(citations) 

948 if c.get("citation_id") 

949 } 

950 used: set[int] = set() 

951 shown: set[str] = set() 

952 

953 def use(i: int) -> None: 

954 used.add(i) 

955 shown.add(_document(citations[i])) 

956 

957 def use_first(indices: Iterable[int]) -> None: 

958 """The first of ``indices``, unless its page or document is shown.""" 

959 first = next(iter(indices), None) 

960 if first is not None and _document(citations[first]) not in shown: 

961 use(first) 

962 

963 # By pipeline id: the passage itself. 

964 for sid in (sid for g in SID_GROUP.findall(prose) for sid in ids_in_group(g)): 

965 if sid in by_sid: 

966 use(by_sid[sid]) 

967 entries = parse_sources_section(prose) 

968 unnamed: list[CitedSource] = [] 

969 for entry in entries: 

970 sids = {entry.marker.upper()} | { 

971 sid.upper() for sid in _SID.findall(_norm_text(entry.text)) 

972 } 

973 ids = [by_sid[sid] for sid in sids if sid in by_sid] 

974 for i in ids: 

975 use(i) 

976 if not ids: 

977 unnamed.append(entry) 

978 

979 # By URL, wherever the draft links or writes it. 

980 for url in _linked_urls(prose): 

981 use_first(i for i, c in enumerate(citations) if url in _citation_urls(c)) 

982 

983 # By name, in an entry whose URL (if any) named nothing the run read. 

984 for entry in unnamed: 

985 target = _norm_url(entry.url) 

986 if target and any(target in _citation_urls(c) for c in citations): 

987 continue 

988 text = f" {_norm_text(entry.text)} " 

989 if not text.strip(): 

990 continue 

991 named = [ 

992 i 

993 for i, c in enumerate(citations) 

994 if any( 

995 f" {_norm_text(name)} " in text 

996 for name in _citation_names(c) 

997 if _norm_text(name) 

998 ) 

999 ] 

1000 # One per page or document the entry names. 

1001 for document in dict.fromkeys(_document(citations[i]) for i in named): 

1002 use_first(i for i in named if _document(citations[i]) == document) 

1003 return [c for i, c in enumerate(citations) if i in used] 

1004 

1005 

1006# ─── For the evaluator ─────────────────────────────────────────────────────── 

1007 

1008 

1009def _attr(value: str) -> str: 

1010 import html 

1011 

1012 return html.escape(value, quote=True) 

1013 

1014 

1015def render_for_evaluator( 

1016 ledger: list[LedgerSource], checks: list[CitationCheck] 

1017) -> list[str]: 

1018 """The ``<sources>`` and ``<citation_check>`` sections of the evaluator 

1019 input, as lines.""" 

1020 if not ledger: 

1021 out = [" <sources>(none)</sources>"] 

1022 else: 

1023 out = [f' <sources count="{len(ledger)}">'] 

1024 for entry in ledger[:MAX_LISTED]: 

1025 attrs = [f'kind="{_KIND_LABEL.get(entry.kind, entry.kind)}"'] 

1026 if entry.citation_id: 

1027 attrs.insert(0, f'id="{_attr(entry.citation_id)}"') 

1028 if entry.kb_name: 

1029 attrs.append(f'knowledge_base="{_attr(entry.kb_name)}"') 

1030 if entry.url: 

1031 attrs.append(f'url="{_attr(entry.url)}"') 

1032 if entry.via: 

1033 attrs.append(f'via="{_attr(entry.via)}"') 

1034 out.append(f" <source {' '.join(attrs)}>{_attr(entry.title)}</source>") 

1035 if len(ledger) > MAX_LISTED: 

1036 out.append(f" <!-- {len(ledger) - MAX_LISTED} more not listed -->") 

1037 out.append(" </sources>") 

1038 if checks: 

1039 out.append(" <citation_check>") 

1040 for check in checks: 

1041 matched = "" 

1042 if check.match is not None: 

1043 label = check.match.citation_id or check.match.title 

1044 matched = f' matches="{_attr(label)}"' 

1045 out.append( 

1046 f' <citation marker="{_attr(check.marker)}" ' 

1047 f'status="{check.status}"{matched}>{_attr(check.text)}</citation>' 

1048 ) 

1049 out.append(" </citation_check>") 

1050 else: 

1051 out.append(" <citation_check>(the draft cites no source)</citation_check>") 

1052 return out