Skip to content

The agent that grows with you

fix(skills): match evidence quotes through markdown markup

Tekniuma6defd4f1549
diff --git a/skills/research/grounded-citations/SKILL.md b/skills/research/grounded-citations/SKILL.md
index a40e709e967..fe703d1df9e 100644
--- a/skills/research/grounded-citations/SKILL.md
+++ b/skills/research/grounded-citations/SKILL.md
@@ -81,6 +81,7 @@ id within a ledger, so ids stay stable across many search/extract rounds.
| Show ledger | `sources.py list [--json]` |
| Render the Sources block | `sources.py render [--style markdown\|plain\|footnotes\|bibtex\|evidence] [--only 1,3]` |
| Render only what a draft cites | `sources.py render --cited-in draft.md` |
+| Rewrite a draft's Sources block in place | `sources.py render --replace-in draft.md` |
| Check a draft's citations | `sources.py verify draft.md [--strict] [--min-coverage 0.6] [--evidence]` |
## Procedure
@@ -139,8 +140,12 @@ python3 "$S" quote 1 --text "Ice is about 9% less dense than liquid water." --fr
```
The quote is rejected unless it appears verbatim in the evidence text
-(whitespace- and case-insensitive), so a paraphrase or misremembered figure
-cannot masquerade as evidence. Copy-paste from the fetched text; never retype.
+(insensitive to whitespace, case, and markdown markup — inline links like
+`_[ERAP1](https://…)_` in extracted text match the plain prose a reader sees),
+so a paraphrase or misremembered figure cannot masquerade as evidence.
+Copy-paste from the fetched text; never retype. Quote the sentence as the
+reader sees it — the matcher sees through the extractor's markup for you, so
+you don't have to reproduce link syntax or escaped asterisks in your quote.
② **Flag model-knowledge claims with `[unverified]`.** A load-bearing claim
you could not source gets an explicit marker instead of a citation:
@@ -164,13 +169,24 @@ corroboration.
```bash
python3 "$S" verify report.md --evidence --min-coverage 0.5
-python3 "$S" render --style evidence --cited-in report.md
+python3 "$S" render --style evidence --replace-in report.md
```
`--evidence` fails the draft if any cited source has no attached quote. The
`evidence` render style prints each source's quotes beneath its URL, so the
deliverable shows claim → source → exact supporting text with nothing taken on
-faith.
+faith. Use `--replace-in <draft>` to rewrite an existing Sources block in place
+(idempotent — safe to re-run after attaching more quotes); `--cited-in` prints
+to stdout instead. Both emit the heading `## Sources` (`--style plain` emits
+`Sources:`).
+
+**What `--min-coverage` counts.** Coverage is
+`sentences with declared provenance / prose sentences`. A prose sentence is a
+non-empty line fragment of 4+ words after the Sources block, headings (`#`),
+table rows (`|`), and fenced code are dropped; blockquote markers are stripped.
+Provenance is declared by either a `[n]` citation or an `[unverified]` marker,
+so a sentence carrying both counts once. Run `verify` without a threshold first
+and read the `info: stats:` line to see the counts before picking a number.
## Pitfalls
@@ -200,6 +216,8 @@ faith.
- **Using `[unverified]` as an escape hatch.** It marks the rare claim that
genuinely cannot be sourced; if most sentences carry it, the task needed more
retrieval, not more markers.
+- **Hand-editing the Sources block.** Use `render --replace-in <draft>`; slicing
+ the file yourself risks a stale or duplicated block that `verify` then flags.
## Verification
diff --git a/skills/research/grounded-citations/scripts/sources.py b/skills/research/grounded-citations/scripts/sources.py
index ac4f71d4b4c..9584b8d106a 100644
--- a/skills/research/grounded-citations/scripts/sources.py
+++ b/skills/research/grounded-citations/scripts/sources.py
@@ -234,11 +234,33 @@ def _normalize_ws(text: str) -> str:
return " ".join((text or "").split())
+# Markdown artifacts that retrieval tools inject into otherwise-identical prose.
+# ``web_extract`` returns markdown, so the most citation-worthy sentences are
+# exactly the ones carrying inline links and emphasis around terms:
+# "including _[ERAP1](https://…/erap1/)_, _[IL1A](…)_, have also been…"
+# reads identically to the page a human sees. Matching has to see through that
+# markup, or the skill pushes the agent toward weaker evidence fragments.
+_MD_LINK_RE = re.compile(r"\[([^\]]*)\]\((?:[^()\s]|\([^()]*\))*\)")
+_MD_NOISE_RE = re.compile(r"[*_`~]|\\(?=[^\w\s])")
+
+
+def _match_key(text: str) -> str:
+ """Canonicalize text for verbatim comparison.
+
+ Whitespace-, case-, and markdown-insensitive: inline links collapse to
+ their label, emphasis/code markers and backslash escapes are dropped. The
+ stored quote keeps whatever the caller passed, so the rendered evidence
+ block shows clean prose rather than extractor artifacts.
+ """
+ collapsed = _MD_LINK_RE.sub(r"\1", text or "")
+ return _normalize_ws(_MD_NOISE_RE.sub("", collapsed)).casefold()
+
+
def quote_in_evidence(quote: str, evidence: str) -> bool:
- """True when ``quote`` appears verbatim (whitespace-insensitively,
- case-insensitively) in the fetched ``evidence`` text."""
- q = _normalize_ws(quote).casefold()
- return bool(q) and q in _normalize_ws(evidence).casefold()
+ """True when ``quote`` appears verbatim in the fetched ``evidence`` text,
+ ignoring whitespace, case, and markdown markup on either side."""
+ q = _match_key(quote)
+ return bool(q) and q in _match_key(evidence)
def attach_quote(path: Path, source_id: int, quote: str, evidence: str) -> dict[str, Any]:
@@ -260,8 +282,8 @@ def attach_quote(path: Path, source_id: int, quote: str, evidence: str) -> dict[
if entry is None:
raise SystemExit(f"error: no source [{source_id}] in the ledger")
quotes = entry.setdefault("quotes", [])
- norm = _normalize_ws(quote).casefold()
- if not any(_normalize_ws(q.get("text", "")).casefold() == norm for q in quotes):
+ norm = _match_key(quote)
+ if not any(_match_key(q.get("text", "")) == norm for q in quotes):
quotes.append({"text": quote, "added": time.strftime("%Y-%m-%d")})
save_ledger(path, data)
return entry
@@ -344,6 +366,23 @@ def _split_draft(text: str) -> tuple[str, dict[int, str]]:
return "\n".join(prose), listed
+def _strip_sources_block(text: str) -> str:
+ """Return the draft with its trailing Sources block removed.
+
+ Everything from the last Sources header onward goes; a draft with no such
+ header is returned unchanged. This is what makes ``render --replace-in``
+ idempotent instead of stacking duplicate blocks.
+ """
+ lines = text.splitlines()
+ header_idx = -1
+ for i, line in enumerate(lines):
+ if _SOURCES_HEADER_RE.match(line):
+ header_idx = i
+ if header_idx < 0:
+ return text
+ return "\n".join(lines[:header_idx])
+
+
def _sentences(prose: str) -> list[str]:
"""Rough sentence split over prose lines, skipping headings and tables."""
out: list[str] = []
@@ -448,8 +487,9 @@ def verify_draft(
code = 1 if errors else (1 if (strict and warnings) else 0)
quoted = sum(1 for s in sources if s.get("quotes"))
stats = (
- f"{len(sentences)} prose sentence(s), {len(cited_sentences)} cited, "
- f"{len(unverified_sentences)} marked [unverified] ({coverage:.0%} covered), "
+ f"{len(sentences)} prose sentence(s), {len(covered)} with declared provenance "
+ f"({coverage:.0%}) — {len(cited_sentences)} cited, "
+ f"{len(unverified_sentences)} marked [unverified] (a sentence may be both); "
f"{len(cited_set)} distinct source(s) cited, "
f"{len(by_id)} in ledger ({quoted} with evidence quotes)"
)
@@ -514,6 +554,10 @@ def main(argv: list[str] | None = None) -> int:
)
p_render.add_argument("--only", help="ids to include, e.g. 1,3,5-7")
p_render.add_argument("--cited-in", help="include only ids cited in this draft file")
+ p_render.add_argument(
+ "--replace-in",
+ help="rewrite this draft's Sources block in place (implies --cited-in on it)",
+ )
p_ver = sub.add_parser("verify", help="check a draft's citations against the ledger")
p_ver.add_argument("draft")
@@ -588,8 +632,9 @@ def main(argv: list[str] | None = None) -> int:
if args.cmd == "render":
only = _parse_only(args.only)
- if args.cited_in:
- draft = Path(args.cited_in).read_text(encoding="utf-8")
+ draft_for_ids = args.replace_in or args.cited_in
+ if draft_for_ids:
+ draft = Path(draft_for_ids).read_text(encoding="utf-8")
prose, _ = _split_draft(draft)
cited = {int(m) for m in _CITE_RE.findall(prose)}
only = cited if only is None else (only & cited)
@@ -597,6 +642,12 @@ def main(argv: list[str] | None = None) -> int:
if not block:
print("no sources to render", file=sys.stderr)
return 1
+ if args.replace_in:
+ target = Path(args.replace_in)
+ body = _strip_sources_block(target.read_text(encoding="utf-8"))
+ target.write_text(body.rstrip("\n") + "\n\n" + block + "\n", encoding="utf-8")
+ print(f"Sources block rewritten in {target}")
+ return 0
print(block)
return 0
@@ -613,7 +664,8 @@ def main(argv: list[str] | None = None) -> int:
require_evidence=args.evidence,
)
for w in warnings:
- print(f"warn: {w}")
+ prefix = "info" if w.startswith("stats: ") else "warn"
+ print(f"{prefix}: {w}")
for e in errors:
print(f"FAIL: {e}", file=sys.stderr)
print("citations OK" if code == 0 else "verification failed")
diff --git a/tests/skills/test_grounded_citations_skill.py b/tests/skills/test_grounded_citations_skill.py
index c21a2d58c18..1dd1dd01a63 100644
--- a/tests/skills/test_grounded_citations_skill.py
+++ b/tests/skills/test_grounded_citations_skill.py
@@ -466,3 +466,141 @@ def test_cli_quote_and_evidence_verify_roundtrip(sources_mod, tmp_path: Path, ca
capsys.readouterr()
assert sources_mod.main(args + ["render", "--style", "evidence"]) == 0
assert '> "Water expands when it freezes."' in capsys.readouterr().out
+
+
+# ---------------------------------------------------------------------------
+# Markdown-markup tolerance in the verbatim check
+#
+# Retrieval returns markdown, so the most citation-worthy sentences are the
+# ones carrying inline links and emphasis around terms. Requiring the agent to
+# reproduce that markup pushed a real live run toward a weaker evidence
+# fragment, which is the opposite of the skill's purpose.
+# ---------------------------------------------------------------------------
+
+# Verbatim shape of the MedlinePlus sentence as web_extract returns it.
+_MD_PAGE = (
+ "Variations in several additional genes, including "
+ "_[ERAP1](https://medlineplus.gov/genetics/gene/erap1/)_, "
+ "_[IL1A](https://medlineplus.gov/genetics/gene/il1a/)_, and "
+ "_[IL23R](https://medlineplus.gov/genetics/gene/il23r/)_, have also been\n"
+ "associated with ankylosing spondylitis.\n"
+ "While over 90% of AS patients have an HLA-B\\*27 haplotype, only around 5% develop AS.\n"
+)
+
+
+def test_quote_matches_through_inline_links_and_emphasis(sources_mod, ledger: Path) -> None:
+ sources_mod.add_sources(ledger, ["https://medlineplus.gov/x"])
+ entry = sources_mod.attach_quote(
+ ledger,
+ 1,
+ "Variations in several additional genes, including ERAP1, IL1A, and IL23R, "
+ "have also been associated with ankylosing spondylitis.",
+ _MD_PAGE,
+ )
+ assert len(entry["quotes"]) == 1
+ # The stored quote keeps the caller's clean prose — no extractor artifacts
+ # leak into the rendered deliverable.
+ assert "medlineplus.gov/genetics/gene" not in entry["quotes"][0]["text"]
+
+
+def test_quote_matches_through_escaped_asterisks(sources_mod, ledger: Path) -> None:
+ sources_mod.add_sources(ledger, ["https://frontiersin.org/x"])
+ entry = sources_mod.attach_quote(
+ ledger, 1, "over 90% of AS patients have an HLA-B*27 haplotype", _MD_PAGE
+ )
+ assert entry["quotes"][0]["text"] == "over 90% of AS patients have an HLA-B*27 haplotype"
+
+
+def test_markup_tolerance_does_not_admit_paraphrase(sources_mod, ledger: Path) -> None:
+ """Seeing through markup must not weaken the substantive check."""
+ sources_mod.add_sources(ledger, ["https://medlineplus.gov/x"])
+ with pytest.raises(SystemExit) as exc:
+ sources_mod.attach_quote(
+ ledger, 1, "Several other immune genes are also linked to the disease.", _MD_PAGE
+ )
+ assert "not found verbatim" in str(exc.value)
+
+
+# ---------------------------------------------------------------------------
+# render --replace-in
+# ---------------------------------------------------------------------------
+
+
+def test_render_replace_in_rewrites_block_idempotently(sources_mod, tmp_path: Path, capsys) -> None:
+ ledger = tmp_path / "rp.json"
+ page = tmp_path / "p.txt"
+ page.write_text(_PAGE, encoding="utf-8")
+ args = ["--ledger", str(ledger)]
+ sources_mod.main(args + ["add", "https://a.example", "https://b.example"])
+ sources_mod.main(
+ args + ["quote", "1", "--text", "Water expands when it freezes.", "--from", str(page)]
+ )
+ capsys.readouterr()
+
+ draft = tmp_path / "d.md"
+ draft.write_text(
+ "A claim resting on the first source.[1]\n\n## Sources\n\n[1] https://stale.example\n",
+ encoding="utf-8",
+ )
+ assert sources_mod.main(args + ["render", "--style", "evidence", "--replace-in", str(draft)]) == 0
+ first = draft.read_text(encoding="utf-8")
+ assert "stale.example" not in first
+ assert first.count("## Sources") == 1
+ assert '> "Water expands when it freezes."' in first
+ # [2] is registered but uncited — --replace-in filters to cited ids.
+ assert "b.example" not in first
+
+ assert sources_mod.main(args + ["render", "--style", "evidence", "--replace-in", str(draft)]) == 0
+ assert draft.read_text(encoding="utf-8") == first, "second run must be a no-op"
+ capsys.readouterr()
+ assert sources_mod.main(args + ["verify", str(draft), "--evidence"]) == 0
+
+
+def test_render_replace_in_appends_when_no_block_exists(sources_mod, tmp_path: Path, capsys) -> None:
+ ledger = tmp_path / "ap.json"
+ args = ["--ledger", str(ledger)]
+ sources_mod.main(args + ["add", "https://a.example"])
+ draft = tmp_path / "d.md"
+ draft.write_text("A claim resting on the first source.[1]\n", encoding="utf-8")
+ assert sources_mod.main(args + ["render", "--replace-in", str(draft)]) == 0
+ body = draft.read_text(encoding="utf-8")
+ assert body.startswith("A claim resting on the first source.[1]")
+ assert "## Sources" in body and "[1] https://a.example" in body
+ capsys.readouterr()
+
+
+# ---------------------------------------------------------------------------
+# Output legibility
+# ---------------------------------------------------------------------------
+
+
+def test_stats_line_is_info_not_warn_on_success(sources_mod, tmp_path: Path, capsys) -> None:
+ ledger = tmp_path / "st.json"
+ args = ["--ledger", str(ledger)]
+ sources_mod.main(args + ["add", "https://a.example"])
+ draft = tmp_path / "d.md"
+ draft.write_text(
+ "A claim resting on the first source.[1]\n\nSources:\n[1] https://a.example\n",
+ encoding="utf-8",
+ )
+ capsys.readouterr()
+ assert sources_mod.main(args + ["verify", str(draft)]) == 0
+ out = capsys.readouterr().out
+ assert "info: stats:" in out
+ assert "warn: stats:" not in out
+
+
+def test_stats_reports_provenance_total_matching_coverage(sources_mod, ledger: Path, tmp_path: Path) -> None:
+ """The stats line's counts must reconcile with the percentage it prints."""
+ _seed(sources_mod, ledger)
+ text = (
+ "A cited claim about the subject matter.[1]\n"
+ "A claim both cited and hedged as uncertain.[2][unverified]\n"
+ "A model-knowledge claim declared as such.[unverified]\n"
+ "An uncited, unmarked claim about the subject.\n\n"
+ "Sources:\n[1] https://a.example\n[2] https://b.example\n"
+ )
+ _code, _errors, warnings = _verify(sources_mod, ledger, tmp_path, text)
+ stats = warnings[0]
+ # 4 sentences, 3 with provenance (the both-marked sentence counts once).
+ assert "4 prose sentence(s), 3 with declared provenance (75%)" in stats
diff --git a/website/docs/user-guide/skills/bundled/research/research-grounded-citations.md b/website/docs/user-guide/skills/bundled/research/research-grounded-citations.md
index 0d37d54eec7..487e06a6b6c 100644
--- a/website/docs/user-guide/skills/bundled/research/research-grounded-citations.md
+++ b/website/docs/user-guide/skills/bundled/research/research-grounded-citations.md
@@ -98,6 +98,7 @@ id within a ledger, so ids stay stable across many search/extract rounds.
| Show ledger | `sources.py list [--json]` |
| Render the Sources block | `sources.py render [--style markdown\|plain\|footnotes\|bibtex\|evidence] [--only 1,3]` |
| Render only what a draft cites | `sources.py render --cited-in draft.md` |
+| Rewrite a draft's Sources block in place | `sources.py render --replace-in draft.md` |
| Check a draft's citations | `sources.py verify draft.md [--strict] [--min-coverage 0.6] [--evidence]` |
## Procedure
@@ -156,8 +157,12 @@ python3 "$S" quote 1 --text "Ice is about 9% less dense than liquid water." --fr
```
The quote is rejected unless it appears verbatim in the evidence text
-(whitespace- and case-insensitive), so a paraphrase or misremembered figure
-cannot masquerade as evidence. Copy-paste from the fetched text; never retype.
+(insensitive to whitespace, case, and markdown markup — inline links like
+`_[ERAP1](https://…)_` in extracted text match the plain prose a reader sees),
+so a paraphrase or misremembered figure cannot masquerade as evidence.
+Copy-paste from the fetched text; never retype. Quote the sentence as the
+reader sees it — the matcher sees through the extractor's markup for you, so
+you don't have to reproduce link syntax or escaped asterisks in your quote.
② **Flag model-knowledge claims with `[unverified]`.** A load-bearing claim
you could not source gets an explicit marker instead of a citation:
@@ -181,13 +186,24 @@ corroboration.
```bash
python3 "$S" verify report.md --evidence --min-coverage 0.5
-python3 "$S" render --style evidence --cited-in report.md
+python3 "$S" render --style evidence --replace-in report.md
```
`--evidence` fails the draft if any cited source has no attached quote. The
`evidence` render style prints each source's quotes beneath its URL, so the
deliverable shows claim → source → exact supporting text with nothing taken on
-faith.
+faith. Use `--replace-in <draft>` to rewrite an existing Sources block in place
+(idempotent — safe to re-run after attaching more quotes); `--cited-in` prints
+to stdout instead. Both emit the heading `## Sources` (`--style plain` emits
+`Sources:`).
+
+**What `--min-coverage` counts.** Coverage is
+`sentences with declared provenance / prose sentences`. A prose sentence is a
+non-empty line fragment of 4+ words after the Sources block, headings (`#`),
+table rows (`|`), and fenced code are dropped; blockquote markers are stripped.
+Provenance is declared by either a `[n]` citation or an `[unverified]` marker,
+so a sentence carrying both counts once. Run `verify` without a threshold first
+and read the `info: stats:` line to see the counts before picking a number.
## Pitfalls
@@ -217,6 +233,8 @@ faith.
- **Using `[unverified]` as an escape hatch.** It marks the rare claim that
genuinely cannot be sourced; if most sentences carry it, the task needed more
retrieval, not more markers.
+- **Hand-editing the Sources block.** Use `render --replace-in <draft>`; slicing
+ the file yourself risks a stale or duplicated block that `verify` then flags.
## Verification