Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ echo '{"answer": "...", "sources": ["...", "..."]}' | groundcheck --json-input -
| `--threshold F` | Overlap below which a claim is unsupported (0–1, default 0.5) |
| `--fail-under N` | Exit non-zero if the grounding score is below N |
| `--fail-on LEVEL` | Exit non-zero on a finding at/above `low`/`medium`/`high` |
| `--note FILE` | Append a Markdown note for reviewers (see below) |

**Exit codes:** `0` grounded, `1` below threshold or a blocking finding, `2`
usage. With neither `--fail-under` nor `--fail-on`, it only reports (exit 0).
Expand All @@ -128,6 +129,41 @@ Gate a RAG regression suite on groundedness:
Any answer that invents a statistic (`--fail-on high`) or drops below 70%
grounded fails the build.

### A note for whoever signs off

A failed run usually ends in a CI log that only the engineer reads, while the
person approving the release sees a summary. `--note FILE` appends a short
Markdown note with each blocking claim quoted over the source sentence that
shares the most wording with it, so the claim and the evidence travel together.
It leaves the score out on purpose: a decent score hides the one sentence that
matters.

```yaml
groundcheck --json-input "$case" --fail-on high --note "$GITHUB_STEP_SUMMARY"
```

```markdown
### groundcheck: 2 claim(s) not supported by the sources

**fabricated-number** (high)
> Profit margins expanded to 47%.

No sentence in the sources shares its wording.

_'47%' not found in 1 source(s)_

**fabricated-number** (high)
> Third quarter revenue reached $4 million.

Closest in source 1:
> Revenue rose to $3.1 million in the third quarter.

_'$4 million' not found in 1 source(s)_
```

The note appends rather than overwrites, so it can go straight into
`$GITHUB_STEP_SUMMARY` or a file your pipeline posts as a pull-request comment.

## As a library

```python
Expand Down
2 changes: 1 addition & 1 deletion groundcheck/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__version__ = "1.0.0"
__version__ = "1.1.0"

from .checker import check # noqa: E402
from .model import ClaimResult, Finding, Report, Severity # noqa: E402
Expand Down
13 changes: 12 additions & 1 deletion groundcheck/checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,13 @@
import re

from .model import ClaimResult, Finding, Report, Severity
from .signals import best_overlap, negation_conflict, overlap_score, unsupported_numbers
from .signals import (
best_overlap,
closest_passage,
negation_conflict,
overlap_score,
unsupported_numbers,
)
from .text import content_tokens, extract_numbers, split_sentences

# [1] [2,3] [1, 2] — citation markers pointing at 1-based source indices.
Expand Down Expand Up @@ -143,6 +149,11 @@ def check(answer: str, sources: list[str], *,
claim.findings.append(f)
report.findings.append(f)

nearest = closest_passage(sentence, sources) if claim.findings else None
if nearest:
for f in claim.findings:
f.closest_source, f.closest_passage = nearest

report.claims.append(claim)

report.findings.sort(key=lambda f: -int(f.severity))
Expand Down
52 changes: 47 additions & 5 deletions groundcheck/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from . import __version__
from .checker import DEFAULT_SUPPORT_THRESHOLD, check
from .model import Report, Severity
from .model import Finding, Report, Severity

EXIT_OK = 0 # score at or above --fail-under and no blocking findings
EXIT_UNGROUNDED = 1 # below threshold, or a finding at/above --fail-on
Expand Down Expand Up @@ -88,6 +88,10 @@ def build_parser() -> argparse.ArgumentParser:
p.add_argument("--fail-on", default="never",
choices=["low", "medium", "high", "never"],
help="exit non-zero on a finding at/above this severity")
p.add_argument("--note", metavar="FILE",
help="append a Markdown note for reviewers: each blocking claim over the "
"closest source sentence, no score (for a PR comment or "
"$GITHUB_STEP_SUMMARY)")
p.add_argument("-V", "--version", action="version",
version=f"groundcheck {__version__}")
return p
Expand Down Expand Up @@ -126,6 +130,38 @@ def paint(sev, text):
print(f" {len(report.findings)} finding(s): {summary}", file=stream)


def _quote(text: str) -> str:
return "\n".join(f"> {line}" for line in text.splitlines() or [""])


def render_note(findings: list[Finding]) -> str:
"""Claim and evidence side by side, so a reader can judge without the tool.

The score is left out on purpose: a decent score hides the one sentence
that matters, and the person signing off should read that sentence.
"""
if not findings:
return ("### groundcheck: nothing blocking\n\n"
"Every flagged claim is below the failing level.\n")
claims = {f.claim for f in findings}
lines = [f"### groundcheck: {len(claims)} claim(s) not supported by the sources", ""]
for f in findings:
lines += [f"**{f.kind}** ({f.severity.label})", _quote(f.claim) if f.claim else "", ""]
if f.closest_passage:
lines += [f"Closest in source {f.closest_source + 1}:", _quote(f.closest_passage), ""]
elif f.claim:
lines += ["No sentence in the sources shares its wording.", ""]
lines += [f"_{f.evidence or f.detail}_", ""]
return "\n".join(lines)


def _blocking(report: Report, fail_on: str) -> list[Finding]:
if fail_on == "never":
return list(report.findings)
level = Severity[fail_on.upper()]
return [f for f in report.findings if f.severity >= level]


def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)

Expand All @@ -147,13 +183,19 @@ def main(argv: list[str] | None = None) -> int:
else:
_render_text(report, sys.stdout)

if args.note:
try:
with open(args.note, "a") as fh:
fh.write(render_note(_blocking(report, args.fail_on)))
except OSError as exc:
print(f"groundcheck: cannot write the note: {exc}", file=sys.stderr)
return EXIT_USAGE

exit_code = EXIT_OK
if args.fail_under is not None and report.score < args.fail_under:
exit_code = EXIT_UNGROUNDED
if args.fail_on != "never":
threshold = Severity[args.fail_on.upper()]
if any(f.severity >= threshold for f in report.findings):
exit_code = EXIT_UNGROUNDED
if args.fail_on != "never" and _blocking(report, args.fail_on):
exit_code = EXIT_UNGROUNDED
return exit_code


Expand Down
4 changes: 4 additions & 0 deletions groundcheck/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ class Finding:
claim: str
detail: str
evidence: str = ""
closest_source: int = -1 # source holding closest_passage, -1 if none
closest_passage: str = "" # the source sentence nearest to the claim

def to_dict(self) -> dict:
return {
Expand All @@ -39,6 +41,8 @@ def to_dict(self) -> dict:
"claim": self.claim,
"detail": self.detail,
"evidence": self.evidence,
"closest_source": self.closest_source,
"closest_passage": self.closest_passage,
}


Expand Down
21 changes: 20 additions & 1 deletion groundcheck/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

from __future__ import annotations

from .text import Number, content_tokens, extract_numbers, has_negation
from .text import Number, content_tokens, extract_numbers, has_negation, split_sentences


def _bigrams(tokens: list[str]) -> set[tuple[str, str]]:
Expand Down Expand Up @@ -96,3 +96,22 @@ def negation_conflict(claim: str, source: str, *, overlap_threshold: float = 0.6
if overlap_score(claim, source) < overlap_threshold:
return False
return has_negation(claim) != has_negation(source)


def closest_passage(claim: str, sources: list[str]) -> tuple[int, str] | None:
"""The source sentence that shares the most wording with a claim.

Shown next to a flagged claim so a reviewer can compare the two without
opening the sources. None when no sentence shares a content word: that
absence is itself the evidence (the report never mentions margins).
"""
if not content_tokens(claim):
return None
best: tuple[int, str] | None = None
best_score = 0.0
for i, source in enumerate(sources):
for sentence in split_sentences(source):
score = overlap_score(claim, sentence)
if score > best_score:
best, best_score = (i, sentence), score
return best
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "groundcheck"
version = "1.0.0"
version = "1.1.0"
description = "A deterministic groundedness linter for RAG/LLM answers — flags fabricated numbers, unsupported claims, and broken citations, with exit codes for CI."
readme = "README.md"
requires-python = ">=3.9"
Expand Down
74 changes: 74 additions & 0 deletions tests/test_note.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
"""The reviewer note: each blocking claim next to the closest source passage."""

from __future__ import annotations

import json

from groundcheck import cli
from groundcheck.checker import check
from groundcheck.signals import closest_passage

REPORT = (
"Revenue rose to $3.1 million in the third quarter. "
"Operating costs were flat. The board approved a new office lease."
)


def write(tmp_path, name, text):
p = tmp_path / name
p.write_text(text)
return str(p)


def test_closest_passage_is_the_source_sentence_sharing_most_words():
assert closest_passage("Third quarter revenue reached $4 million.", ["x.", REPORT]) == (
1, "Revenue rose to $3.1 million in the third quarter.")


def test_no_shared_words_means_no_passage():
assert closest_passage("Profit margins expanded to 47%.", [REPORT]) is None


def test_findings_carry_the_closest_passage():
[finding] = check("Third quarter revenue reached $4 million.", [REPORT]).findings
assert finding.closest_source == 0
assert finding.closest_passage.startswith("Revenue rose to $3.1 million")
assert finding.to_dict()["closest_passage"] == finding.closest_passage


def test_note_puts_the_claim_over_the_closest_passage_without_a_score(tmp_path):
src = write(tmp_path, "report.txt", REPORT)
ans = write(tmp_path, "answer.txt", "Third quarter revenue reached $4 million.")
note = tmp_path / "note.md"
rc = cli.main(["--answer", ans, "--source", src, "--fail-on", "high", "--note", str(note)])
text = note.read_text()
assert rc == cli.EXIT_UNGROUNDED
assert "> Third quarter revenue reached $4 million." in text
assert "> Revenue rose to $3.1 million in the third quarter." in text
assert "/100" not in text


def test_note_says_so_when_the_sources_have_nothing_close(tmp_path):
data = write(tmp_path, "in.json", json.dumps(
{"answer": "Profit margins expanded to 47%.", "sources": [REPORT]}))
note = tmp_path / "note.md"
cli.main(["--json-input", data, "--fail-on", "high", "--note", str(note)])
assert "No sentence in the sources shares its wording." in note.read_text()


def test_note_lists_only_findings_at_the_fail_on_level(tmp_path):
data = write(tmp_path, "in.json", json.dumps({
"answer": "The board approved a new office lease [2].",
"sources": [REPORT, "Unrelated text about weather patterns."]}))
note = tmp_path / "note.md"
assert cli.main(["--json-input", data, "--fail-on", "high", "--note", str(note)]) == 0
assert note.read_text().startswith("### groundcheck: nothing blocking")


def test_note_appends_so_a_ci_job_summary_keeps_earlier_steps(tmp_path):
note = tmp_path / "summary.md"
note.write_text("earlier step\n")
data = write(tmp_path, "in.json",
json.dumps({"answer": "Margins hit 47%.", "sources": [REPORT]}))
cli.main(["--json-input", data, "--note", str(note)])
assert note.read_text().startswith("earlier step\n")