Suite review, first batch: test groups smallest first, covers named before the sync reads them #238

Merged
bvandeusen merged 5 commits from dev into main 2026-12-01 06:41:21 -05:00
12 changed files with 160 additions and 58 deletions
+9 -1
View File
@@ -21,6 +21,8 @@ interface GroupTest extends ShapeRef {
} }
interface Group { interface Group {
key: string; key: string;
kind: "copies" | "area";
files: number;
guards: ShapeRef[]; guards: ShapeRef[];
tests: GroupTest[]; tests: GroupTest[];
} }
@@ -145,6 +147,10 @@ watch(() => props.projectId, load);
</p> </p>
<ul v-else class="tg-list"> <ul v-else class="tg-list">
<li v-for="g in groups" :key="g.key" class="tg-group"> <li v-for="g in groups" :key="g.key" class="tg-group">
<p v-if="g.kind === 'area'" class="tg-kind">
One feature tested from {{ g.files }} files: fold the scattered
cases into its own test file, and remove only what another test covers.
</p>
<div class="tg-guards"> <div class="tg-guards">
<span class="tg-label">Guard</span> <span class="tg-label">Guard</span>
<code v-for="s in g.guards" :key="s.id" :title="s.path">{{ s.symbol }}</code> <code v-for="s in g.guards" :key="s.id" :title="s.path">{{ s.symbol }}</code>
@@ -199,7 +205,8 @@ watch(() => props.projectId, load);
</li> </li>
</ul> </ul>
<p v-if="count > groups.length" class="tg-note"> <p v-if="count > groups.length" class="tg-note">
Showing {{ groups.length }} of {{ count }}, largest first. Showing {{ groups.length }} of {{ count }}, smallest first: the
smallest groups are the likeliest copies.
</p> </p>
</div> </div>
</div> </div>
@@ -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-guards, .tg-test { display: flex; flex-wrap: wrap; align-items: center; gap: var(--fs-space-2); }
.tg-label { color: var(--fs-text-tertiary); } .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); } code { font-family: var(--fs-font-mono); color: var(--fs-text-primary); }
.tg-signal { .tg-signal {
padding: 0 var(--fs-space-2); padding: 0 var(--fs-space-2);
+1 -1
View File
@@ -1,7 +1,7 @@
{ {
"name": "grimoire", "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).", "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": { "author": {
"name": "Bryan Van Deusen" "name": "Bryan Van Deusen"
}, },
+6
View File
@@ -47,6 +47,12 @@ finish it before starting the next. In each area:
with its `signals`: `signature` (pins how code is declared), `mock-only` with its `signals`: `signature` (pins how code is declared), `mock-only`
(asserts only that mocks were called), `source-text` (reads source as (asserts only that mocks were called), `source-text` (reads source as
text). Signals point at what to read first; they never decide a verdict. 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: 2. **Read every test** and give it one verdict:
- **keep** — it protects something a user or caller relies on, and - **keep** — it protects something a user or caller relies on, and
nothing else in the suite protects it; nothing else in the suite protects it;
+12 -2
View File
@@ -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 tests whose sets match exactly across files. Within one file a shared
subject is a table of cases, so it never forms a group. 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: A group is a candidate, not a verdict. Read the tests, then either:
- classify_shapes one of them `redundant` with `covered_by` naming the - classify_shapes one of them `redundant` with `covered_by` naming the
test that checks everything it checks, and a reason — then delete it; 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: Args:
project_id: The project whose suite to read. 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. 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}]}]}. "tests": [{id, path, symbol, status, signals}]}]}.
""" """
from grimoire.services import access from grimoire.services import access
+15 -5
View File
@@ -800,12 +800,22 @@ async def classify_shapes(
status = item["status"] status = item["status"]
cover_id = None cover_id = None
if status == "redundant": if status == "redundant":
# The cover is a live row of this project, resolved exactly # The cover resolves exactly like the shape being judged: a
# like the shape being judged; a cover no row matches is an # live row, or with a bound `repo` a provisional one, because
# error, because a redundant verdict without its cover is the # a test is usually rewritten in the same change that removes
# one claim nobody can check. # 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"] 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: if not covers:
raise ValueError( raise ValueError(
f"covered_by {cover['path']}::{cover['symbol']} matches no live shape " f"covered_by {cover['path']}::{cover['symbol']} matches no live shape "
+24 -5
View File
@@ -382,7 +382,9 @@ def same_guard_groups(
"""Tests that guard exactly the same non-empty set of shapes from more """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). 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 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) by_set: dict[frozenset[int], list[tuple[int, str]]] = defaultdict(list)
for tid, path, guarded in tests: for tid, path, guarded in tests:
if guarded: if guarded:
@@ -392,10 +394,24 @@ def same_guard_groups(
for guarded, members in by_set.items() for guarded, members in by_set.items()
if len({p for _t, p in members}) > 1 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 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 --------------------------------------------------------- # --- the ledger side ---------------------------------------------------------
# Statuses whose test has had its verdict: it leaves every group. # 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: 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 """Tests that guard exactly the same shapes from more than one file, and
have not been reviewed as distinct: {"count", "groups": [...]}, largest have not been reviewed as distinct: {"count", "groups": [...]}, smallest
first. Each group carries what its tests guard and, per test, its weak first. Each group carries its `kind` ("copies" or "area", see
signals, status and the key a review is recorded under.""" `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 sqlalchemy import select
from grimoire.models import async_session from grimoire.models import async_session
@@ -543,6 +560,8 @@ async def guard_groups(project_id: int, *, top: int = GROUPS_SHOWN) -> dict:
continue continue
out.append({ out.append({
"key": key, "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"])), "guards": sorted((_shape_ref(by_id[x]) for x in g), key=lambda d: (d["path"], d["symbol"])),
"tests": [ "tests": [
{**_shape_ref(by_id[t]), "status": by_id[t].status, {**_shape_ref(by_id[t]), "status": by_id[t].status,
+45
View File
@@ -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)
+27
View File
@@ -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 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 @pytest.mark.integration
async def test_the_end_of_turn_question_asks_about_product_code_not_test_cases(seeded): async def test_the_end_of_turn_question_asks_about_product_code_not_test_cases(seeded):
from grimoire.services.shape_ledger import unjudged_shapes from grimoire.services.shape_ledger import unjudged_shapes
+9 -10
View File
@@ -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(): def test_starting_a_plan_is_routed_on_the_app():
from grimoire.routes import tasks as tasks_routes from grimoire.app import create_app
assert callable(tasks_routes.start_planning_route) rules = {
(str(r.rule), m) for r in create_app().url_map.iter_rules() for m in r.methods
}
def test_planning_service_signature(): assert ("/api/tasks/planning", "POST") in rules
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
-17
View File
@@ -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
+2 -17
View File
@@ -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 from unittest.mock import AsyncMock, MagicMock, patch
import pytest import pytest
@@ -20,19 +21,3 @@ async def test_create_note_passes_task_kind_to_model():
from grimoire.services.notes import create_note from grimoire.services.notes import create_note
await create_note(user_id=1, title="P", status="todo", task_kind="plan") await create_note(user_id=1, title="P", status="todo", task_kind="plan")
assert captured["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
+10
View File
@@ -131,6 +131,16 @@ def test_a_group_spans_files_and_one_file_never_forms_one():
assert groups == [(same, [10, 11])] 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(): 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")]) 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")]) assert a == tg.group_key([("tests/b.py", "test_2"), ("tests/a.py", "test_1")])