From dc9e88aa6dffab79e26fff5bb5ddb90ca840cbcf Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Mon, 30 Nov 2026 21:57:57 -0500 Subject: [PATCH] feat(8247): a test case is accounted for by what it guards, and the coverage line counts the suite by it A refresh now stamps a test case `test` when it is linked to something it guards, and withdraws the stamp when its links go; a judgment always wins. A test case linked to nothing stays in the todo, because nothing says what it is for. Specs written as it()/test() calls get one ledger row per file, read whole. The coverage line and card count tests linked, guarding nothing found, and redundant, and the end-of-turn question no longer asks the writer to call a test case a one-off. Co-Authored-By: Claude Opus 5.5 --- frontend/src/views/ProjectView.vue | 18 +++- src/grimoire/mcp/tools/shapes.py | 4 +- src/grimoire/models/code_shape.py | 8 +- src/grimoire/services/coverage.py | 28 +++++- src/grimoire/services/shape_ledger.py | 7 ++ src/grimoire/services/test_guards.py | 83 +++++++++++++++++- tests/test_integration_test_guards.py | 119 ++++++++++++++++++++++++++ tests/test_pattern_coverage.py | 2 +- tests/test_shape_ledger.py | 2 +- tests/test_test_guards.py | 28 ++++++ 10 files changed, 288 insertions(+), 11 deletions(-) create mode 100644 tests/test_integration_test_guards.py diff --git a/frontend/src/views/ProjectView.vue b/frontend/src/views/ProjectView.vue index ee6c114d..f33d2464 100644 --- a/frontend/src/views/ProjectView.vue +++ b/frontend/src/views/ProjectView.vue @@ -501,6 +501,8 @@ interface Coverage { recheck?: number; // Same-guard test groups awaiting a verdict (TestGuardReview). test_groups?: number; + // The suite by what it protects. + tests?: { linked: number; unlinked: number; redundant: number } | null; } interface Divergence { path: string; @@ -837,7 +839,7 @@ async function confirmDelete() {
@@ -891,6 +893,20 @@ async function confirmDelete() { {{ coverage.recheck }} to recheck
+
+ Tests: + {{ coverage.tests.linked }} linked + + {{ coverage.tests.unlinked }} guarding nothing found + + + {{ coverage.tests.redundant }} redundant + +
rules and its diff --git a/src/grimoire/models/code_shape.py b/src/grimoire/models/code_shape.py index 5e88bb8e..bce61cdf 100644 --- a/src/grimoire/models/code_shape.py +++ b/src/grimoire/models/code_shape.py @@ -29,9 +29,15 @@ from grimoire.models.base import TimestampMixin, iso # test, the test that guards the same thing more fully), unused says nothing # needs it. Both take a reason. The row stays until the code is removed and # the next sync marks it vanished, which is how the verdict is carried out. +# +# `test` is the sync's mechanical stamp on a test case that is linked to +# something it guards (services/test_guards): accounted for by what it +# protects, without anyone judging it one-off. A test case linked to nothing +# stays `unclassified`, the todo, because nothing says what it is for. Any +# judgment overrides the stamp, and losing every link withdraws it. SHAPE_STATUSES = ( "canonical", "instance", "variant", "exempt", "redundant", "unused", - "scoped", "unclassified", + "scoped", "test", "unclassified", ) # `person` is a judgment made in the web UI. SHAPE_CLASSIFIERS = ("agent", "audit", "hook", "mechanical", "import", "person") diff --git a/src/grimoire/services/coverage.py b/src/grimoire/services/coverage.py index 4c093ed7..6b113142 100644 --- a/src/grimoire/services/coverage.py +++ b/src/grimoire/services/coverage.py @@ -722,6 +722,14 @@ def scan_archive(blob: bytes) -> ArchiveScan: references[path] = refs if test_guards.is_test_path(path): test_files[path] = test_guards.read_test_file(text) + # A spec whose cases are calls gets one row of its own, the + # whole file as its body, so the linker can read what it + # guards. + if test_guards.is_call_style_spec(path, text, (d.name for d in defs)) \ + and not any(d.name == file_stem(path) for d in defs): + shapes.append(ArchiveShape( + path, "file", file_stem(path), f"file {path}", "", text, + )) return ArchiveScan(shapes, references, tuple(paths), test_files) @@ -864,6 +872,10 @@ async def compute_coverage( links = test_guards.link_tests( [test_guards.Def(d.path, d.name, d.body) for d in definitions if d.kind == "sym"], scan.test_files or {}, scan.paths, + file_tests=[ + test_guards.Def(d.path, d.name, d.body) for d in definitions + if d.kind == "file" and d.body and test_guards.is_test_path(d.path) + ], ) await test_guards.sync_repo_guards(project_id, key, links) except Exception: @@ -932,7 +944,7 @@ async def compute_coverage( # repo that was unreachable today still has live rows, and they count. rows = await shape_ledger.live_rows(project_id) counts = {"canonical": 0, "instance": 0, "variant": 0, "exempt": 0, - "redundant": 0, "unused": 0, "scoped": 0, "unclassified": 0} + "redundant": 0, "unused": 0, "scoped": 0, "test": 0, "unclassified": 0} for row in rows: counts[row.status] = counts.get(row.status, 0) + 1 by_repo: dict[str, dict[str, int]] = {} @@ -976,9 +988,10 @@ async def compute_coverage( from grimoire.services import test_guards test_groups = (await test_guards.guard_groups(project_id, top=0))["count"] + tests = await test_guards.test_summary(project_id) except Exception: logger.warning("test guard groups read failed", exc_info=True) - test_groups = 0 + test_groups, tests = 0, None # The write-time figure: how often the end-of-turn # question was put on this project, and how often it was walked past. # An audit reads the ledger; this reads whether the reflex held. @@ -1008,6 +1021,8 @@ async def compute_coverage( "unused_css": unused_css, # Same-guard test groups awaiting a verdict (test_guard_groups). "test_groups": test_groups, + # The suite by what it protects: {linked, unlinked, redundant}. + "tests": tests, "proposer": proposer_stats, # The divergence readout: new shapes where a different canon # dominates, and judged shapes whose bodies moved since they were @@ -1152,7 +1167,8 @@ def coverage_line(coverage: dict) -> str: counts = coverage.get("counts") or {} breakdown = " · ".join( f"{counts[k]} {k}" - for k in ("canonical", "instance", "variant", "exempt", "redundant", "unused", "scoped") + for k in ("canonical", "instance", "variant", "exempt", "redundant", "unused", + "scoped", "test") if counts.get(k) ) line = ( @@ -1217,6 +1233,12 @@ def coverage_line(coverage: dict) -> str: line += ", largest: " + ", ".join(gaps) elif standing: line += f"; standing: {', '.join(standing)}" + tests = coverage.get("tests") or {} + if any(tests.values()): + line += ( + f"; tests: {tests.get('linked', 0)} linked · {tests.get('unlinked', 0)} " + f"guarding nothing found · {tests.get('redundant', 0)} redundant" + ) if coverage.get("recheck"): line += f"; {coverage['recheck']} judged shape{'s' if coverage['recheck'] != 1 else ''} changed since judged — recheck" # Rows the hook asserted on evidence below the ledger's floor. They do diff --git a/src/grimoire/services/shape_ledger.py b/src/grimoire/services/shape_ledger.py index 6f4a836c..3c884318 100644 --- a/src/grimoire/services/shape_ledger.py +++ b/src/grimoire/services/shape_ledger.py @@ -3035,8 +3035,15 @@ async def unjudged_shapes( async with async_session() as session: rows = (await session.execute(query)).scalars().all() by_key = {(r.path, r.kind, r.symbol): r for r in rows} + from grimoire.services.test_guards import is_test_case + out: list[dict] = [] for path, kind, name in wanted: + # A test case is accounted for by what it guards: the refresh links + # it and stamps it `test`, so the writer is not asked to call it a + # one-off. + if is_test_case(path, name, kind): + continue row = by_key.get((path, kind, name)) if row is not None and _is_judged(row): continue diff --git a/src/grimoire/services/test_guards.py b/src/grimoire/services/test_guards.py index 219ba59a..ad6432c2 100644 --- a/src/grimoire/services/test_guards.py +++ b/src/grimoire/services/test_guards.py @@ -39,6 +39,7 @@ from __future__ import annotations import hashlib import re from collections import defaultdict +from datetime import datetime, timezone from typing import Iterable, NamedTuple # Directory names that hold tests, in the conventions the ledger meets. @@ -89,6 +90,28 @@ def is_test_name(name: str) -> bool: return bool(_TEST_NAME_RE.match(name)) +# A spec written as calls — `it("…", …)`, `test("…", …)` — defines no +# test-named function, so the file is the unit: one ledger row per spec. +_TEST_CALL_RE = re.compile(r"^\s*(?:it|test)(?:\.\w+)?\s*\(", re.MULTILINE) + + +def is_call_style_spec(path: str, text: str, names: Iterable[str]) -> bool: + """A test file whose cases are calls, not definitions.""" + return ( + is_test_path(path) + and not any(is_test_name(n) for n in names) + and _TEST_CALL_RE.search(text) is not None + ) + + +def is_test_case(path: str, symbol: str, kind: str) -> bool: + """Is this ledger row a test case: a test-named definition in a test + file, or a call-style spec file's own row?""" + if not is_test_path(path): + return False + return kind == "file" or (kind == "sym" and is_test_name(symbol)) + + def test_signals(body: str) -> list[str]: """The weak-test signals a test's body shows, sorted.""" out = [name for name, rx in SIGNALS.items() if rx.search(body)] @@ -210,13 +233,15 @@ def link_tests( files: dict[str, TestFile], repo_paths: Iterable[str] = (), *, + file_tests: Iterable[Def] = (), blank=None, ) -> Links: """Link each test in a repo to what it guards. Pure: `defs` are the repo's symbol definitions with their bodies, `files` each test file read by `read_test_file`, `repo_paths` every file in the tree. `blank` masks strings and comments out of a body; it defaults to the coverage - extractor's own pass so the two read code the same way. + extractor's own pass so the two read code the same way. `file_tests` + are call-style spec files, each a test whose body is the whole file. A qualified reference `q.name` counts only when `q` is the defining module, by name or through an alias the file binds (`pc` for @@ -238,6 +263,9 @@ def link_tests( tests.append(d) else: product[d.name].append(d.path) + for d in file_tests: + helpers[d.name].append(d) + tests.append(d) own_names: dict[str, set[str]] = defaultdict(set) # test file → names it defines for name, ds in helpers.items(): @@ -372,6 +400,10 @@ def same_guard_groups( # Statuses whose test has had its verdict: it leaves every group. _SETTLED = ("redundant", "unused") +_TEST_REASON = ( + "a test case linked to what it guards (stamped by the coverage sync); " + "test_guard_groups lists the ones guarding the same thing" +) # How many groups a readout carries; the count says how many there are. GROUPS_SHOWN = 25 @@ -393,7 +425,8 @@ async def sync_repo_guards(project_id: int, repo_key: str, links: Links) -> int: CodeShape.vanished_at.is_(None), ) )).scalars().all() - ids = {(r.path, r.symbol): r.id for r in rows if r.kind == "sym"} + ids = {(r.path, r.symbol): r.id for r in rows if r.kind in ("sym", "file")} + by_key = {(r.path, r.symbol): r for r in rows if r.kind in ("sym", "file")} all_ids = [r.id for r in rows] if all_ids: await session.execute(delete(CodeShapeGuard).where(CodeShapeGuard.test_id.in_(all_ids))) @@ -411,13 +444,57 @@ async def sync_repo_guards(project_id: int, repo_key: str, links: Links) -> int: session.add(CodeShapeGuard(test_id=tid, path=path, basis="static")) edges += 1 for r in rows: - sig = ",".join(links.signals.get((r.path, r.symbol), ())) if r.kind == "sym" else "" + sig = ",".join(links.signals.get((r.path, r.symbol), ())) if r.kind in ("sym", "file") else "" if (r.test_signals or "") != sig: r.test_signals = sig + # The `test` stamp follows the links: on while a test case guards + # something, withdrawn when it guards nothing, never over a judgment. + from grimoire.services.shape_ledger import _judge + + now = datetime.now(timezone.utc) + for key, guarded in links.shapes.items(): + row = by_key.get(key) + if row is None: + continue + linked = bool(guarded) or bool(links.paths.get(key)) + if linked and row.status == "unclassified": + await _judge(session, row, status="test", snippet_id=None, + by="mechanical", reason=_TEST_REASON, at=now) + elif not linked and row.status == "test": + await _judge(session, row, status="unclassified", snippet_id=None, + by=None, reason=None, at=now) await session.commit() return edges +async def test_summary(project_id: int) -> dict: + """{linked, unlinked, redundant} over a project's live test cases: linked + to something they guard, linked to nothing, judged redundant.""" + from sqlalchemy import select + + from grimoire.models import async_session + from grimoire.models.code_shape import CodeShape, CodeShapeGuard + + async with async_session() as session: + rows = (await session.execute( + select(CodeShape.id, CodeShape.path, CodeShape.symbol, CodeShape.kind, CodeShape.status) + .where(CodeShape.project_id == project_id, CodeShape.vanished_at.is_(None)) + )).all() + cases = {r[0]: r for r in rows if is_test_case(r[1], r[2], r[3])} + guarded = set((await session.execute( + select(CodeShapeGuard.test_id).where(CodeShapeGuard.test_id.in_(list(cases))) + )).scalars().all()) if cases else set() + out = {"linked": 0, "unlinked": 0, "redundant": 0} + for tid, r in cases.items(): + if r[4] == "redundant": + out["redundant"] += 1 + elif tid in guarded: + out["linked"] += 1 + else: + out["unlinked"] += 1 + return out + + def _shape_ref(row) -> dict: return {"id": row.id, "path": row.path, "symbol": row.symbol} diff --git a/tests/test_integration_test_guards.py b/tests/test_integration_test_guards.py new file mode 100644 index 00000000..46e2e478 --- /dev/null +++ b/tests/test_integration_test_guards.py @@ -0,0 +1,119 @@ +"""Real-Postgres tests for test-guard links: the `test` stamp, the groups, +a redundant verdict, and a kept group. + +What the pure tests can't prove: that a sync stamps a linked test case and +withdraws the stamp when its links go, never over a judgment, and that the +group readout honours verdicts and reviews held in the database. Ledger rows +are seeded through the same sync the coverage walk uses; no forge needed. +""" +import pytest +import pytest_asyncio +from sqlalchemy import select + +from grimoire.models import async_session +from grimoire.models.code_shape import CodeShape +from grimoire.models.project import Project +from grimoire.services import test_guards as tg +from grimoire.services.shape_ledger import classify_shapes, sync_repo_shapes +from tests.helpers import ensure_user + +pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")] + +REPO = "git.example.com/alice/widget" +CHARGE = ("src/billing.py", "charge") +A = ("tests/test_a.py", "test_charges") +B = ("tests/test_b.py", "test_also_charges") +LONE = ("tests/test_c.py", "test_reads_nothing") +SHAPES = [(p, "sym", s) for p, s in (CHARGE, A, B, LONE)] + + +def _links(*, a_links: bool = True) -> tg.Links: + shapes = {A: {CHARGE} if a_links else set(), B: {CHARGE}, LONE: set()} + return tg.Links(shapes, {k: set() for k in shapes}, {k: [] for k in shapes}, set()) + + +@pytest_asyncio.fixture +async def seeded(): + async with async_session() as s: + owner = await ensure_user(s, "guards_owner") + project = Project(user_id=owner.id, title="Guards target") + s.add(project) + await s.flush() + ids = {"owner": owner.id, "pid": project.id} + await s.commit() + await sync_repo_shapes(ids["pid"], REPO, SHAPES, seen_marker="main") + return ids + + +async def _rows(pid: int) -> dict[tuple[str, str], CodeShape]: + async with async_session() as s: + rows = (await s.execute(select(CodeShape).where(CodeShape.project_id == pid))).scalars().all() + return {(r.path, r.symbol): r for r in rows} + + +@pytest.mark.integration +async def test_a_linked_test_case_is_stamped_and_loses_the_stamp_with_its_links(seeded): + pid = seeded["pid"] + await tg.sync_repo_guards(pid, REPO, _links()) + rows = await _rows(pid) + assert rows[A].status == "test" and rows[A].classified_by == "mechanical" + # Linked to nothing: still the todo, because nothing says what it is for. + assert rows[LONE].status == "unclassified" + assert await tg.test_summary(pid) == {"linked": 2, "unlinked": 1, "redundant": 0} + + await tg.sync_repo_guards(pid, REPO, _links(a_links=False)) + assert (await _rows(pid))[A].status == "unclassified" + + +@pytest.mark.integration +async def test_the_stamp_never_overrides_a_judgment(seeded): + pid, owner = seeded["pid"], seeded["owner"] + await classify_shapes(owner, pid, [{"path": A[0], "symbol": A[1], "status": "exempt", + "reason": "a smoke check kept on purpose"}]) + await tg.sync_repo_guards(pid, REPO, _links()) + assert (await _rows(pid))[A].status == "exempt" + + +@pytest.mark.integration +async def test_a_group_leaves_the_readout_once_a_test_is_judged_redundant(seeded): + pid, owner = seeded["pid"], seeded["owner"] + await tg.sync_repo_guards(pid, REPO, _links()) + groups = await tg.guard_groups(pid) + assert groups["count"] == 1 + assert {(t["path"], t["symbol"]) for t in groups["groups"][0]["tests"]} == {A, B} + + await classify_shapes(owner, pid, [{ + "path": A[0], "symbol": A[1], "status": "redundant", + "covered_by": {"path": B[0], "symbol": B[1]}, + "reason": "test_also_charges makes the same call and checks the total too", + }]) + rows = await _rows(pid) + assert rows[A].covered_by_id == rows[B].id + assert (await tg.guard_groups(pid))["count"] == 0 + assert (await tg.test_summary(pid))["redundant"] == 1 + + +@pytest.mark.integration +async def test_a_kept_group_leaves_the_readout_until_its_members_change(seeded): + pid, owner = seeded["pid"], seeded["owner"] + await tg.sync_repo_guards(pid, REPO, _links()) + rows = await _rows(pid) + await tg.review_group(owner, pid, [rows[A].id, rows[B].id], + reason="one checks the amount, the other the receipt", by="agent") + assert (await tg.guard_groups(pid))["count"] == 0 + + # A third test joins: a new group, back in front of a reviewer. + links = _links() + links.shapes[LONE] = {CHARGE} + await tg.sync_repo_guards(pid, REPO, links) + assert (await tg.guard_groups(pid))["count"] == 1 + + +@pytest.mark.integration +async def test_the_end_of_turn_question_asks_about_product_code_not_test_cases(seeded): + from grimoire.services.shape_ledger import unjudged_shapes + + asked = await unjudged_shapes(seeded["pid"], [ + (A[0], "sym", A[1]), (CHARGE[0], "sym", CHARGE[1]), + ]) + assert [(x["path"], x["symbol"]) for x in asked] == [CHARGE] diff --git a/tests/test_pattern_coverage.py b/tests/test_pattern_coverage.py index 766a2671..12b9166a 100644 --- a/tests/test_pattern_coverage.py +++ b/tests/test_pattern_coverage.py @@ -483,7 +483,7 @@ async def test_coverage_measures_the_tree_exactly_and_caches(seeded): assert coverage["unclassified"] == 2 assert coverage["counts"] == { "canonical": 2, "instance": 0, "variant": 0, "exempt": 0, - "redundant": 0, "unused": 0, "scoped": 0, + "redundant": 0, "unused": 0, "scoped": 0, "test": 0, } assert coverage["estimate"] is True assert coverage["repos"] == [{ diff --git a/tests/test_shape_ledger.py b/tests/test_shape_ledger.py index ba2999e6..2632845d 100644 --- a/tests/test_shape_ledger.py +++ b/tests/test_shape_ledger.py @@ -30,7 +30,7 @@ def test_the_todo_state_is_the_default(): assert "unclassified" in SHAPE_STATUSES assert set(SHAPE_STATUSES) == { "canonical", "instance", "variant", "exempt", "redundant", "unused", - "scoped", "unclassified", + "scoped", "test", "unclassified", } assert set(SHAPE_CLASSIFIERS) == { "agent", "audit", "hook", "mechanical", "import", "person", diff --git a/tests/test_test_guards.py b/tests/test_test_guards.py index 283b0b53..4f453510 100644 --- a/tests/test_test_guards.py +++ b/tests/test_test_guards.py @@ -169,3 +169,31 @@ def test_the_coverage_line_names_the_removal_verdicts_and_the_test_groups(): }) assert "2 redundant" in line and "1 unused" in line assert "3 test groups guarding the same thing" in line + + +def test_a_test_case_is_a_test_named_definition_or_a_call_style_spec_file(): + assert tg.is_test_case("tests/test_a.py", "test_x", "sym") + assert not tg.is_test_case("tests/test_a.py", "_helper", "sym") + assert not tg.is_test_case("src/app/billing.py", "test_mode", "sym") + assert tg.is_test_case("web/src/a.spec.ts", "a.spec", "file") + + +def test_a_spec_written_as_calls_is_one_test_and_links_by_its_imports(): + text = "import { charge } from '../app/billing'\n\nit('charges', () => {\n expect(charge(1)).toBe(1)\n})\n" + assert tg.is_call_style_spec("web/src/billing.spec.ts", text, []) + # A file that defines test-named functions is read per function instead. + assert not tg.is_call_style_spec("tests/test_a.py", "def test_x():\n pass\n", ["test_x"]) + spec = tg.Def("web/src/billing.spec.ts", "billing.spec", text) + product = tg.Def("web/app/billing.ts", "charge", "export function charge(n) {\n return n\n}\n") + links = tg.link_tests([product], {spec.path: tg.read_test_file(text)}, file_tests=[spec]) + assert links.shapes[(spec.path, "billing.spec")] == {("web/app/billing.ts", "charge")} + + +def test_the_coverage_line_counts_tests_by_what_they_guard(): + line = coverage_line({ + "accounted": 10, "total": 12, "unclassified": 2, "counts": {"test": 8}, + "tests": {"linked": 8, "unlinked": 2, "redundant": 1}, + "computed_at": "2026-12-01T00:00:00+00:00", + }) + assert "8 test" in line + assert "tests: 8 linked · 2 guarding nothing found · 1 redundant" in line