diff --git a/frontend/src/components/TestGuardReview.vue b/frontend/src/components/TestGuardReview.vue index 4fc96e9f..86f879f8 100644 --- a/frontend/src/components/TestGuardReview.vue +++ b/frontend/src/components/TestGuardReview.vue @@ -21,6 +21,8 @@ interface GroupTest extends ShapeRef { } interface Group { key: string; + kind: "copies" | "area"; + files: number; guards: ShapeRef[]; tests: GroupTest[]; } @@ -145,6 +147,10 @@ watch(() => props.projectId, load);

- Showing {{ groups.length }} of {{ count }}, largest first. + Showing {{ groups.length }} of {{ count }}, smallest first: the + smallest groups are the likeliest copies.

@@ -229,6 +236,7 @@ watch(() => props.projectId, load); } .tg-guards, .tg-test { display: flex; flex-wrap: wrap; align-items: center; gap: var(--fs-space-2); } .tg-label { color: var(--fs-text-tertiary); } +.tg-kind { margin: 0; color: var(--fs-text-secondary); } code { font-family: var(--fs-font-mono); color: var(--fs-text-primary); } .tg-signal { padding: 0 var(--fs-space-2); diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index 75ce7a61..eb2846fe 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "grimoire", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.12.01.0344", + "version": "2026.12.01.0748", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/skills/reviewing-tests/SKILL.md b/plugin/skills/reviewing-tests/SKILL.md index 88d1b74e..c8112a9c 100644 --- a/plugin/skills/reviewing-tests/SKILL.md +++ b/plugin/skills/reviewing-tests/SKILL.md @@ -47,6 +47,12 @@ finish it before starting the next. In each area: with its `signals`: `signature` (pins how code is declared), `mock-only` (asserts only that mocks were called), `source-text` (reads source as text). Signals point at what to read first; they never decide a verdict. + Groups come smallest first. A `copies` group (three tests or fewer) is + where one-for-one duplicates hide. An `area` group is one feature + tested from several files, since every test that drives a feature + through its entry point reaches the same code. Read it as one area: fold + the scattered cases into the feature's own file, and remove only what + another test already checks. 2. **Read every test** and give it one verdict: - **keep** — it protects something a user or caller relies on, and nothing else in the suite protects it; diff --git a/src/grimoire/mcp/tools/shapes.py b/src/grimoire/mcp/tools/shapes.py index 1dae61aa..8853d327 100644 --- a/src/grimoire/mcp/tools/shapes.py +++ b/src/grimoire/mcp/tools/shapes.py @@ -459,6 +459,15 @@ async def test_guard_groups(project_id: int, top: int = 10) -> dict: tests whose sets match exactly across files. Within one file a shared subject is a table of cases, so it never forms a group. + Groups come smallest first, each with a `kind`. "copies" (three tests + or fewer) is where one test most often checks nothing another does not. + "area" is one feature tested from several files: a test that drives a + feature through its entry point reaches exactly that entry point, + whatever behaviour it checks, so the group gathers the feature's + tests. Its usual verdict is to fold the scattered files' cases into + the feature's own test file, and to remove only the ones another + test already covers. + A group is a candidate, not a verdict. Read the tests, then either: - classify_shapes one of them `redundant` with `covered_by` naming the test that checks everything it checks, and a reason — then delete it; @@ -472,10 +481,11 @@ async def test_guard_groups(project_id: int, top: int = 10) -> dict: Args: project_id: The project whose suite to read. - top: How many groups to return, largest first; `count` says how many + top: How many groups to return, smallest first; `count` says how many there are. - Returns {"count": N, "groups": [{"key", "guards": [{id, path, symbol}], + Returns {"count": N, "groups": [{"key", "kind", "files", + "guards": [{id, path, symbol}], "tests": [{id, path, symbol, status, signals}]}]}. """ from grimoire.services import access diff --git a/src/grimoire/services/shape_ledger.py b/src/grimoire/services/shape_ledger.py index 3c884318..6ca13ecd 100644 --- a/src/grimoire/services/shape_ledger.py +++ b/src/grimoire/services/shape_ledger.py @@ -800,12 +800,22 @@ async def classify_shapes( status = item["status"] cover_id = None if status == "redundant": - # The cover is a live row of this project, resolved exactly - # like the shape being judged; a cover no row matches is an - # error, because a redundant verdict without its cover is the - # one claim nobody can check. + # The cover resolves exactly like the shape being judged: a + # live row, or with a bound `repo` a provisional one, because + # a test is usually rewritten in the same change that removes + # the one it replaces, so the cover is new to the ledger. A + # cover nothing can name is an error: a redundant verdict + # without its cover is the one claim nobody can check. cover = item["covered_by"] - covers = by_key.get((cover["path"].strip(), cover["symbol"].strip())) or [] + cpath, csymbol = cover["path"].strip(), cover["symbol"].strip() + covers = by_key.get((cpath, csymbol)) or [] + if not covers and repo_key: + covers = [await provisional_row( + session, project_id=project_id, repo_key=repo_key, path=cpath, + symbol=csymbol, kind=snippet_kind(csymbol, ""), + )] + by_key.setdefault((cpath, csymbol), []).extend(covers) + provisional += 1 if not covers: raise ValueError( f"covered_by {cover['path']}::{cover['symbol']} matches no live shape " diff --git a/src/grimoire/services/test_guards.py b/src/grimoire/services/test_guards.py index ad6432c2..7d37c7ab 100644 --- a/src/grimoire/services/test_guards.py +++ b/src/grimoire/services/test_guards.py @@ -382,7 +382,9 @@ def same_guard_groups( """Tests that guard exactly the same non-empty set of shapes from more than one file: `tests` are (test shape id, path, guarded shape ids). Within one file a shared subject is a table of cases, so a group must - span files. Largest first.""" + span files. Smallest first: two or three tests reaching the same code + from different files are the likeliest one-for-one copies, while a big + group is usually one feature tested from many files (`group_kind`).""" by_set: dict[frozenset[int], list[tuple[int, str]]] = defaultdict(list) for tid, path, guarded in tests: if guarded: @@ -392,10 +394,24 @@ def same_guard_groups( for guarded, members in by_set.items() if len({p for _t, p in members}) > 1 ] - out.sort(key=lambda g: (-len(g[1]), g[1][0])) + out.sort(key=lambda g: (len(g[1]), g[1][0])) return out +# A group of more tests than this is read as a feature AREA rather than as +# candidate copies: a test that drives a feature through its one public +# entry point reaches exactly that entry point whatever behaviour it checks, +# so every test of the feature lands in one group. Its useful verdict is +# usually merging the scattered files' cases into the feature's own file. +SMALL_GROUP = 3 + + +def group_kind(n_tests: int) -> str: + """"copies" for a group small enough to read as possible duplicates, + "area" for one feature tested from several files.""" + return "copies" if n_tests <= SMALL_GROUP else "area" + + # --- the ledger side --------------------------------------------------------- # Statuses whose test has had its verdict: it leaves every group. @@ -501,9 +517,10 @@ def _shape_ref(row) -> dict: async def guard_groups(project_id: int, *, top: int = GROUPS_SHOWN) -> dict: """Tests that guard exactly the same shapes from more than one file, and - have not been reviewed as distinct: {"count", "groups": [...]}, largest - first. Each group carries what its tests guard and, per test, its weak - signals, status and the key a review is recorded under.""" + have not been reviewed as distinct: {"count", "groups": [...]}, smallest + first. Each group carries its `kind` ("copies" or "area", see + `group_kind`), how many files it spans, what its tests guard and, per + test, its weak signals, status and the key a review is recorded under.""" from sqlalchemy import select from grimoire.models import async_session @@ -543,6 +560,8 @@ async def guard_groups(project_id: int, *, top: int = GROUPS_SHOWN) -> dict: continue out.append({ "key": key, + "kind": group_kind(len(members)), + "files": len({by_id[t].path for t in members}), "guards": sorted((_shape_ref(by_id[x]) for x in g), key=lambda d: (d["path"], d["symbol"])), "tests": [ {**_shape_ref(by_id[t]), "status": by_id[t].status, diff --git a/tests/test_integration_task_kind_list.py b/tests/test_integration_task_kind_list.py new file mode 100644 index 00000000..362dc906 --- /dev/null +++ b/tests/test_integration_task_kind_list.py @@ -0,0 +1,45 @@ +"""Listing tasks by kind returns that kind only, counted the same way. + +A mocked session cannot show this: the filter is a WHERE clause, and only a +real query proves it keeps the issue out of a list of work and the count in +step with the page. +""" +import pytest +import pytest_asyncio + +from grimoire.models import async_session +from grimoire.models.note import Note +from grimoire.models.project import Project +from grimoire.services import notes as notes_svc +from tests.helpers import ensure_user + +pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine", "_no_embedding")] + + +@pytest_asyncio.fixture +async def world(): + async with async_session() as s: + owner = await ensure_user(s, "task_kind_lister") + project = Project(user_id=owner.id, title="Kinds") + s.add(project) + await s.flush() + s.add_all([ + Note(user_id=owner.id, project_id=project.id, title=f"{kind} {i}", + status="todo", task_kind=kind) + for kind, n in (("work", 2), ("issue", 1), ("spike", 1)) for i in range(n) + ]) + await s.commit() + return {"owner": owner.id, "pid": project.id} + + +@pytest.mark.parametrize("kind, titles", [ + ("issue", ["issue 0"]), + ("work", ["work 0", "work 1"]), + (None, ["issue 0", "spike 0", "work 0", "work 1"]), +]) +async def test_listing_by_kind_returns_that_kind_and_counts_it(world, kind, titles): + rows, total = await notes_svc.list_notes( + world["owner"], is_task=True, project_id=world["pid"], task_kind=kind, + ) + assert sorted(r.title for r in rows) == titles + assert total == len(titles) diff --git a/tests/test_integration_test_guards.py b/tests/test_integration_test_guards.py index 46e2e478..23d8fa15 100644 --- a/tests/test_integration_test_guards.py +++ b/tests/test_integration_test_guards.py @@ -109,6 +109,33 @@ async def test_a_kept_group_leaves_the_readout_until_its_members_change(seeded): assert (await tg.guard_groups(pid))["count"] == 1 +@pytest.mark.integration +async def test_a_redundant_verdict_can_name_a_cover_the_sync_has_not_read_yet(seeded): + """The replacement test lands in the same change as the removal, so its + row does not exist yet: with a bound repo the cover becomes a provisional + row, and the sync that reads it keeps the link. Without repo the verdict + is refused, as a cover nobody can check.""" + from grimoire.services import repo_bindings as repo_bindings_svc + + pid, owner = seeded["pid"], seeded["owner"] + await repo_bindings_svc.set_binding(owner, REPO, pid) + new = ("tests/test_d.py", "test_charges_and_counts") + verdict = [{"path": A[0], "symbol": A[1], "kind": "sym", "status": "redundant", + "reason": "the rewrite checks the charge and the count", + "covered_by": {"path": new[0], "symbol": new[1]}}] + + with pytest.raises(ValueError, match="matches no live shape"): + await classify_shapes(owner, pid, verdict) + out = await classify_shapes(owner, pid, verdict, repo=REPO) + assert out["provisional"] == 1 + + await sync_repo_shapes(pid, REPO, SHAPES + [(new[0], "sym", new[1])], seen_marker="c2") + rows = await _rows(pid) + assert rows[A].status == "redundant" + assert rows[A].covered_by_id == rows[new].id + assert rows[new].vanished_at is None + + @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 diff --git a/tests/test_routes_planning.py b/tests/test_routes_planning.py index 7f731f85..0524ff6b 100644 --- a/tests/test_routes_planning.py +++ b/tests/test_routes_planning.py @@ -1,12 +1,11 @@ -import inspect +"""The planning door of the tasks API is routed: POST /api/tasks/planning +reaches a handler on the running app. What the handler does is the planning +service's to prove (tests/test_mcp_tool_create_records.py drives it).""" -def test_planning_handler_callable(): - from grimoire.routes import tasks as tasks_routes - assert callable(tasks_routes.start_planning_route) - - -def test_planning_service_signature(): - from grimoire.services.planning import start_planning - params = inspect.signature(start_planning).parameters - assert "user_id" in params and "project_id" in params and "title" in params +def test_starting_a_plan_is_routed_on_the_app(): + from grimoire.app import create_app + rules = { + (str(r.rule), m) for r in create_app().url_map.iter_rules() for m in r.methods + } + assert ("/api/tasks/planning", "POST") in rules diff --git a/tests/test_routes_tasks_kind.py b/tests/test_routes_tasks_kind.py deleted file mode 100644 index 2a8ce1dd..00000000 --- a/tests/test_routes_tasks_kind.py +++ /dev/null @@ -1,17 +0,0 @@ -import inspect - - -def test_create_note_accepts_task_kind(): - from grimoire.services.notes import create_note - assert "task_kind" in inspect.signature(create_note).parameters - - -def test_list_notes_accepts_task_kind(): - from grimoire.services.notes import list_notes - assert "task_kind" in inspect.signature(list_notes).parameters - - -def test_tasks_blueprint_registered_in_app(): - from grimoire.app import create_app - app = create_app() - assert "tasks" in app.blueprints diff --git a/tests/test_services_notes_task_kind.py b/tests/test_services_notes_task_kind.py index d85fd70b..4c9de31a 100644 --- a/tests/test_services_notes_task_kind.py +++ b/tests/test_services_notes_task_kind.py @@ -1,4 +1,5 @@ -"""task_kind create + list-filter behavior in services/notes.py.""" +"""create_note carries the task_kind it is given onto the row. The list +filter is proven against real Postgres in test_integration_task_kind_list.""" from unittest.mock import AsyncMock, MagicMock, patch import pytest @@ -20,19 +21,3 @@ async def test_create_note_passes_task_kind_to_model(): from grimoire.services.notes import create_note await create_note(user_id=1, title="P", status="todo", task_kind="plan") assert captured["task_kind"] == "plan" - - -@pytest.mark.asyncio -async def test_list_notes_filters_by_task_kind(): - mock_session = make_mock_session() - mock_session.scalar = AsyncMock(return_value=0) - exec_result = MagicMock() - exec_result.scalars.return_value.all.return_value = [] - mock_session.execute = AsyncMock(return_value=exec_result) - with patch("grimoire.services.notes.async_session") as mock_cls: - mock_cls.return_value = mock_session - from grimoire.services.notes import list_notes - # Should not raise; task_kind is a recognized kwarg. - rows, total = await list_notes(user_id=1, is_task=True, task_kind="plan") - assert rows == [] - assert total == 0 diff --git a/tests/test_test_guards.py b/tests/test_test_guards.py index 4f453510..dad5736e 100644 --- a/tests/test_test_guards.py +++ b/tests/test_test_guards.py @@ -131,6 +131,16 @@ def test_a_group_spans_files_and_one_file_never_forms_one(): assert groups == [(same, [10, 11])] +def test_the_smallest_groups_come_first_and_a_big_one_reads_as_a_feature_area(): + pair, area = frozenset({1}), frozenset({2}) + tests = [(10, "tests/test_a.py", pair), (11, "tests/test_b.py", pair)] + tests += [(20 + i, f"tests/test_{i % 2}.py", area) for i in range(6)] + groups = tg.same_guard_groups(tests) + assert [g for g, _members in groups] == [pair, area] + assert tg.group_kind(len(groups[0][1])) == "copies" + assert tg.group_kind(len(groups[1][1])) == "area" + + def test_a_group_is_named_by_its_members_in_any_order(): a = tg.group_key([("tests/a.py", "test_1"), ("tests/b.py", "test_2")]) assert a == tg.group_key([("tests/b.py", "test_2"), ("tests/a.py", "test_1")])