From 9f6f04e89873f6c1dc6f2cf76bc9ad2ee716a2c1 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Mon, 30 Nov 2026 15:33:13 -0500 Subject: [PATCH 1/6] fix(8241,8242): a pointer line names a record once a session, and a place delivery is booked once The plugin ledger of what a session has seen holds only records given a line, so a record named by id came back on every edit and message (one handoff note 35 times in a session). Every pointer line now goes through _point, which asks the server delivery ledger what this session was already shown or pointed at and leaves those out. Snippets beside an edited file were booked both pushed (via record_surfaced) and pointed; record_surfaced now leaves write_path_place to its door. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/services/note_usage.py | 10 ++- src/grimoire/services/plugin_context.py | 36 +++++++-- tests/test_pointer_once_per_session.py | 100 ++++++++++++++++++++++++ 3 files changed, 137 insertions(+), 9 deletions(-) create mode 100644 tests/test_pointer_once_per_session.py diff --git a/src/grimoire/services/note_usage.py b/src/grimoire/services/note_usage.py index ba44dc99..5943a7bc 100644 --- a/src/grimoire/services/note_usage.py +++ b/src/grimoire/services/note_usage.py @@ -137,14 +137,18 @@ def record_surfaced( return _schedule(rows) # The same lines, against the session a plugin door is delivering to. A - # synced skill is not a line in front of the session, so it is left out. + # synced skill is not a line in front of the session, and a pointer is + # booked as `pointed` by the door that names it, so both are left out. if source not in _NOT_A_LINE: from grimoire.services import record_deliveries record_deliveries.record(user_id, note_ids, source) -# Surfacing sources that put nothing in front of the session as a line. -_NOT_A_LINE = frozenset({"process_skill_sync"}) +# Surfacing sources that put nothing in front of the session as a line: +# a synced skill, and the snippets beside an edited file, which are named by +# id in a pointer line (its door records them as `pointed`). Booking these +# as `pushed` too would count each delivery twice. +_NOT_A_LINE = frozenset({"process_skill_sync", "write_path_place"}) def record_pulled( diff --git a/src/grimoire/services/plugin_context.py b/src/grimoire/services/plugin_context.py index 7db40c5c..94be4dce 100644 --- a/src/grimoire/services/plugin_context.py +++ b/src/grimoire/services/plugin_context.py @@ -852,13 +852,12 @@ async def build_autoinject_hint( # What else cleared the floor, named by id only. Recorded as `pointed` # rather than surfaced: no line was spent on these, so an open that # follows says whether a pointer is enough. - pointer = record_kinds.pointer_line(pointers, POINTER_LEAD) + pointer = await _point(user_id, pointers, POINTER_LEAD, "auto_inject_pointer") if pointer: lines.append(pointer[0]) parts.append(hook_payload.Part( text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])}, )) - record_deliveries_svc.record(user_id, pointer[1], "auto_inject_pointer", way=POINTED) # A lookup, not a ranking, so it writes no retrieval_logs row — there is no # score or bar to tune — and its surfacings are its own source, which is @@ -877,6 +876,31 @@ async def build_autoinject_hint( } +async def _point( + user_id: int, pointers: dict[str, list[int]], lead: str, source: str, +) -> tuple[str, list[int]] | None: + """One pointer line, naming each record at most once a session, booked + under `source` as `pointed`; None when nothing is left to name. + + A pointer is for a record the session has not met. The plugin's own + ledger of what a session has seen holds only the records given a line, + so without this a record named by id comes back on every edit and every + message. A handoff note can then be named dozens of times in one session, + and a line that repeats on every turn stops being read. The server's + delivery ledger knows every record shown or pointed at in the session, + whatever the plugin version, so that is what is asked. Outside a plugin + request there is no session, nothing is left out, and nothing is booked. + """ + ids = [i for kind_ids in pointers.values() for i in kind_ids] + had = await record_deliveries_svc.delivered_this_session(user_id, ids) + if had: + pointers = {k: [i for i in v if i not in had] for k, v in pointers.items()} + pointer = record_kinds.pointer_line(pointers, lead) + if pointer: + record_deliveries_svc.record(user_id, pointer[1], source, way=POINTED) + return pointer + + async def _origins(notes, project_id: int | None) -> dict[int, str]: """{note id: project title} for the records here from a project other than the session's. Empty with no session project, where every record is @@ -1901,7 +1925,9 @@ async def build_write_path_hint( entry.append(f"> ↳ {passage}") parts[-1] = replace(parts[-1], text="\n".join(entry)) - place_pointer = record_kinds.pointer_line({"snippet": placed}, PLACE_POINTER_LEAD) + place_pointer = await _point( + user_id, {"snippet": placed}, PLACE_POINTER_LEAD, "write_path_place", + ) place_named: list[int] = [] if place_pointer: place_named = place_pointer[1] @@ -1910,15 +1936,13 @@ async def build_write_path_hint( text=place_pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(place_named)}, )) - record_deliveries_svc.record(user_id, place_named, "write_path_place", way=POINTED) - pointer = record_kinds.pointer_line(pointers, POINTER_LEAD) + pointer = await _point(user_id, pointers, POINTER_LEAD, "write_path_pointer") if pointer: lines.append(pointer[0]) parts.append(hook_payload.Part( text=pointer[0], block="pointer", ids={hook_payload.NOTE: tuple(pointer[1])}, )) - record_deliveries_svc.record(user_id, pointer[1], "write_path_pointer", way=POINTED) if suggested: lines.append(_suggest_line(path, suggested)) diff --git a/tests/test_pointer_once_per_session.py b/tests/test_pointer_once_per_session.py new file mode 100644 index 00000000..d6c4a8ed --- /dev/null +++ b/tests/test_pointer_once_per_session.py @@ -0,0 +1,100 @@ +"""A pointer line names a record once a session, and is counted once. + +A pointer line names, by id, records that cleared the floor but got no line +of their own. The plugin's ledger of what a session has seen holds only the +records given a line, so the server asks its own delivery ledger which +records this session was already shown or pointed at, and leaves those out. +Without that a handoff note is named again on every edit and every message. + +And each delivery is booked once: the snippets beside an edited file are +named in a pointer line, so they are `pointed`, never also `pushed`. +""" +from __future__ import annotations + +import re +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from grimoire.services import note_usage +from grimoire.services import plugin_context as pc +from tests.helpers import fake_note + +# Six equally close notes: the menu shows its top three, and the rest are +# named in the pointer line. +HITS = [(0.8 - i * 0.001, fake_note(id=20 + i, title=f"a note {i}", note_type="note", user_id=1)) + for i in range(6)] + + +async def _pointer(ledger: set[int]) -> tuple[list[int], MagicMock]: + """The ids the auto-inject pointer line names, given what the session's + delivery ledger already holds, and the booking call.""" + calls: list[int] = [] + + async def _search(*_a, **kw): + calls.append(1) + return HITS if len(calls) == 1 else [] + + booked = MagicMock() + with patch.object(pc, "get_autoinject_config", + AsyncMock(return_value={"enabled": True, "threshold": 0.55, "top_k": 3})), \ + patch.object(pc, "semantic_search_notes", _search), \ + patch.object(pc, "superseded_ids", AsyncMock(return_value=set())), \ + patch.object(pc, "system_names_for", AsyncMock(return_value={})), \ + patch.object(pc, "record_retrieval", MagicMock()), \ + patch.object(pc, "record_surfaced", MagicMock()), \ + patch.object(pc.record_deliveries_svc, "delivered_this_session", + AsyncMock(return_value=set(ledger))), \ + patch.object(pc.record_deliveries_svc, "record", booked): + out = (await pc.build_autoinject_hint(1, "q", project_id=2))["context"] + line = next((ln for ln in out.splitlines() if pc.POINTER_LEAD in ln), "") + return [int(i) for i in re.findall(r"#(\d+)", line)], booked + + +@pytest.mark.asyncio +async def test_a_pointer_names_what_the_session_has_not_met(): + named, booked = await _pointer(set()) + assert named, "six close notes and a menu of three should leave a pointer line" + booked.assert_called_once() + assert list(booked.call_args.args[1]) == named + assert booked.call_args.args[2] == "auto_inject_pointer" + + +@pytest.mark.asyncio +async def test_a_record_already_pointed_at_this_session_is_not_named_again(): + first, _ = await _pointer(set()) + again, booked = await _pointer({first[0]}) + assert first[0] not in again + assert set(again) == set(first) - {first[0]} + # Only what the line names is booked, so the ledger stays a record of + # what the session actually saw. + assert first[0] not in booked.call_args.args[1] + + +@pytest.mark.asyncio +async def test_no_line_when_the_session_has_met_every_record_it_would_name(): + first, _ = await _pointer(set()) + again, booked = await _pointer(set(first)) + assert again == [] + booked.assert_not_called() + + +# --- each delivery booked once -------------------------------------------- + +def _booked_for(source: str) -> MagicMock: + booked = MagicMock() + with patch.object(note_usage, "_schedule"), \ + patch("grimoire.services.record_deliveries.record", booked): + note_usage.record_surfaced(user_id=1, note_ids=[7], source=source, project_id=2) + return booked + + +def test_snippets_beside_an_edited_file_are_not_also_booked_as_pushed(): + # Their door books them as `pointed` when it names them. + _booked_for("write_path_place").assert_not_called() + + +def test_a_line_shown_in_full_is_booked_as_pushed(): + # The same call books an ordinary line, so the test above is about the + # place arm and not about booking being switched off. + _booked_for("write_path_sync").assert_called_once() -- 2.54.0 From 134dd682748887969376d6273f208af2f9268a2c Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Mon, 30 Nov 2026 15:40:44 -0500 Subject: [PATCH 2/6] test(8241): the pointer test reuses the auto-inject menu harness instead of copying it Co-Authored-By: Claude Opus 5.5 --- tests/test_pointer_once_per_session.py | 18 +++--------------- 1 file changed, 3 insertions(+), 15 deletions(-) diff --git a/tests/test_pointer_once_per_session.py b/tests/test_pointer_once_per_session.py index d6c4a8ed..593fbe0a 100644 --- a/tests/test_pointer_once_per_session.py +++ b/tests/test_pointer_once_per_session.py @@ -19,6 +19,7 @@ import pytest from grimoire.services import note_usage from grimoire.services import plugin_context as pc from tests.helpers import fake_note +from tests.test_autoinject_context import _menu # Six equally close notes: the menu shows its top three, and the rest are # named in the pointer line. @@ -29,24 +30,11 @@ HITS = [(0.8 - i * 0.001, fake_note(id=20 + i, title=f"a note {i}", note_type="n async def _pointer(ledger: set[int]) -> tuple[list[int], MagicMock]: """The ids the auto-inject pointer line names, given what the session's delivery ledger already holds, and the booking call.""" - calls: list[int] = [] - - async def _search(*_a, **kw): - calls.append(1) - return HITS if len(calls) == 1 else [] - booked = MagicMock() - with patch.object(pc, "get_autoinject_config", - AsyncMock(return_value={"enabled": True, "threshold": 0.55, "top_k": 3})), \ - patch.object(pc, "semantic_search_notes", _search), \ - patch.object(pc, "superseded_ids", AsyncMock(return_value=set())), \ - patch.object(pc, "system_names_for", AsyncMock(return_value={})), \ - patch.object(pc, "record_retrieval", MagicMock()), \ - patch.object(pc, "record_surfaced", MagicMock()), \ - patch.object(pc.record_deliveries_svc, "delivered_this_session", + with patch.object(pc.record_deliveries_svc, "delivered_this_session", AsyncMock(return_value=set(ledger))), \ patch.object(pc.record_deliveries_svc, "record", booked): - out = (await pc.build_autoinject_hint(1, "q", project_id=2))["context"] + out = await _menu(HITS, [], {}) line = next((ln for ln in out.splitlines() if pc.POINTER_LEAD in ln), "") return [int(i) for i in re.findall(r"#(\d+)", line)], booked -- 2.54.0 From 865465ce8fec0e7b4c499d1c061d529ea77dcf5e Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Mon, 30 Nov 2026 21:17:48 -0500 Subject: [PATCH 3/6] feat(8246): the code index links each test to what it guards, and can say redundant or unused Every coverage refresh now reads, for each test in a bound repo, which product shapes its body exercises: through module aliases and imports, following test helpers, with mocked names left out and shapes most test files reach dropped as hubs. Tests in different files that guard exactly the same set form a group. The project page lists the groups and a person can mark one test redundant, naming the test that covers it, or keep them all with a reason. Agents get test_guard_groups and review_test_group, and classify_shapes takes the two new removal verdicts, redundant (with covered_by) and unused. Co-Authored-By: Claude Opus 5.5 --- alembic/versions/0140_test_guards.py | 63 +++ frontend/src/components/TestGuardReview.vue | 242 +++++++++ frontend/src/views/ProjectView.vue | 11 +- plugin/.claude-plugin/plugin.json | 2 +- plugin/skills/shape-accounting/SKILL.md | 14 + src/grimoire/mcp/server.py | 4 +- src/grimoire/mcp/tools/shapes.py | 69 ++- src/grimoire/models/__init__.py | 5 +- src/grimoire/models/code_shape.py | 92 +++- src/grimoire/routes/projects.py | 67 +++ src/grimoire/services/backup.py | 72 ++- src/grimoire/services/coverage.py | 42 +- src/grimoire/services/shape_ledger.py | 41 +- src/grimoire/services/test_guards.py | 523 ++++++++++++++++++++ src/grimoire/services/write_scope.py | 1 + tests/test_pattern_coverage.py | 3 +- tests/test_services_backup.py | 12 +- tests/test_shape_ledger.py | 5 +- tests/test_test_guards.py | 171 +++++++ 19 files changed, 1412 insertions(+), 27 deletions(-) create mode 100644 alembic/versions/0140_test_guards.py create mode 100644 frontend/src/components/TestGuardReview.vue create mode 100644 src/grimoire/services/test_guards.py create mode 100644 tests/test_test_guards.py diff --git a/alembic/versions/0140_test_guards.py b/alembic/versions/0140_test_guards.py new file mode 100644 index 00000000..1d0b6ba8 --- /dev/null +++ b/alembic/versions/0140_test_guards.py @@ -0,0 +1,63 @@ +"""code_shape_guards, code_shape_guard_reviews, and the removal verdicts + +Revision ID: 0140 +Revises: 0139 +Create Date: 2026-12-01 + +What each test guards, read by the coverage sync from the repo archive, so +the ledger can show tests that guard the same thing from different files: +- code_shape_guards: test shape -> guarded shape, or -> a repo path. + Mechanical, rebuilt by every sync, not backed up. +- code_shape_guard_reviews: a group judged to be distinct behaviours. +- code_shapes.covered_by_id: the shape a `redundant` row is covered by. +- code_shapes.test_signals: a test's weak-test signals from the last sync. +The statuses `redundant` and `unused` need no schema change: status is a +plain text column. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0140" +down_revision = "0139" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.add_column("code_shapes", sa.Column( + "covered_by_id", sa.Integer(), + sa.ForeignKey("code_shapes.id", ondelete="SET NULL"), nullable=True, + )) + op.add_column("code_shapes", sa.Column( + "test_signals", sa.Text(), nullable=False, server_default="", + )) + op.create_table( + "code_shape_guards", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("test_id", sa.Integer(), sa.ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=False), + sa.Column("guarded_id", sa.Integer(), sa.ForeignKey("code_shapes.id", ondelete="CASCADE"), nullable=True), + sa.Column("path", sa.Text(), nullable=True), + sa.Column("basis", sa.Text(), nullable=False, server_default="static"), + ) + op.create_index("ix_code_shape_guards_test", "code_shape_guards", ["test_id"]) + op.create_index("ix_code_shape_guards_guarded", "code_shape_guards", ["guarded_id"]) + op.create_table( + "code_shape_guard_reviews", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("project_id", sa.Integer(), sa.ForeignKey("projects.id", ondelete="CASCADE"), nullable=False), + sa.Column("group_key", sa.Text(), nullable=False), + sa.Column("verdict", sa.Text(), nullable=False, server_default="distinct"), + sa.Column("reason", sa.Text(), nullable=False, server_default=""), + sa.Column("reviewed_by", sa.Text(), nullable=False), + sa.Column("reviewed_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.text("now()")), + sa.UniqueConstraint("project_id", "group_key", name="uq_code_shape_guard_reviews_group"), + ) + + +def downgrade() -> None: + op.drop_table("code_shape_guard_reviews") + op.drop_index("ix_code_shape_guards_guarded", table_name="code_shape_guards") + op.drop_index("ix_code_shape_guards_test", table_name="code_shape_guards") + op.drop_table("code_shape_guards") + op.drop_column("code_shapes", "test_signals") + op.drop_column("code_shapes", "covered_by_id") diff --git a/frontend/src/components/TestGuardReview.vue b/frontend/src/components/TestGuardReview.vue new file mode 100644 index 00000000..4fc96e9f --- /dev/null +++ b/frontend/src/components/TestGuardReview.vue @@ -0,0 +1,242 @@ + + + + + diff --git a/frontend/src/views/ProjectView.vue b/frontend/src/views/ProjectView.vue index e55db8f8..ee6c114d 100644 --- a/frontend/src/views/ProjectView.vue +++ b/frontend/src/views/ProjectView.vue @@ -18,6 +18,7 @@ import { canWriteRecord } from "@/utils/permission"; import ProjectRulesTab from "@/components/rules/ProjectRulesTab.vue"; import SystemsSection from "@/components/SystemsSection.vue"; import InceptionCard from "@/components/InceptionCard.vue"; +import TestGuardReview from "@/components/TestGuardReview.vue"; import { fmtDate } from "@/utils/dateFormat"; import type { InceptionDecision, InceptionRecord } from "@/api/inception"; import { @@ -498,6 +499,8 @@ interface Coverage { divergent?: number; divergence?: Divergence[]; recheck?: number; + // Same-guard test groups awaiting a verdict (TestGuardReview). + test_groups?: number; } interface Divergence { path: string; @@ -834,7 +837,7 @@ async function confirmDelete() {
@@ -888,6 +891,12 @@ async function confirmDelete() { {{ coverage.recheck }} to recheck
+

Not measured yet — Refresh reads the bound repo's definitions into diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index d3486fef..9bdf5795 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), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.11.28.2315", + "version": "2026.12.01.0217", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/skills/shape-accounting/SKILL.md b/plugin/skills/shape-accounting/SKILL.md index 640b5f4a..3baae236 100644 --- a/plugin/skills/shape-accounting/SKILL.md +++ b/plugin/skills/shape-accounting/SKILL.md @@ -24,6 +24,10 @@ row carries a status: unreachable from any other file). Accounted for without a judgment; still proposed against, grouped and flagged; any judgment you make overrides it. Not the todo. +- `redundant` — should be removed: `covered_by` names the shape that already + does its job. **Reason required.** Delete the code; the next sync retires + the row. +- `unused` — should be removed: nothing needs it. **Reason required.** - `unclassified` — nobody has judged it yet. **This is the todo list.** ## The loop @@ -181,6 +185,16 @@ Three questions the ledger answers mechanically: one and record the verdict with `classify_shapes` — `instance` if it is, otherwise what it actually is. +## Tests that guard the same thing + +Every refresh links each test to the shapes its body exercises (mocks +excluded), and the coverage line's "N test groups guarding the same thing — +test_guard_groups" counts tests in different files that guard exactly the +same set. A group is a candidate: read the tests, then mark one `redundant` +with the test that covers it, or `review_test_group` with what each checks +that the others don't. Each test's `signals` (signature, mock-only, +source-text) are evidence for that reading, never a verdict. + ## What this buys Divergence becomes mechanical: when button B appears where button A is canon, diff --git a/src/grimoire/mcp/server.py b/src/grimoire/mcp/server.py index f327eccb..c2359d41 100644 --- a/src/grimoire/mcp/server.py +++ b/src/grimoire/mcp/server.py @@ -108,7 +108,7 @@ _READ_ONLY_TOOLS = frozenset({ "list_repo_bindings", # The shape ledger's todo query. Reads only — classify_shapes is # the write, and it is deliberately NOT here. - "list_shapes", "shape_history", "stamps_to_review", + "list_shapes", "shape_history", "stamps_to_review", "test_guard_groups", # The retrieval telemetry readout. Aggregates two log tables and # writes nothing. Listed explicitly because its name carries no read # prefix, so the completeness test below cannot derive it — the same @@ -196,7 +196,7 @@ _WRITE_TOOLS = frozenset({ "merge_snippets", "unmerge_snippet", "create_process", "update_process", "delete_process", "classify_shapes", "classify_shapes_by_rule", "confirm_shape_proposals", - "refresh_pattern_coverage", "move_path", + "refresh_pattern_coverage", "move_path", "review_test_group", # design systems "create_design_system", "update_design_system", "delete_design_system", "create_design_token", "update_design_token", "delete_design_token", diff --git a/src/grimoire/mcp/tools/shapes.py b/src/grimoire/mcp/tools/shapes.py index dcc77f10..720a901f 100644 --- a/src/grimoire/mcp/tools/shapes.py +++ b/src/grimoire/mcp/tools/shapes.py @@ -26,6 +26,11 @@ async def classify_shapes( - `variant` of snippet N — a deliberate, named departure. `reason` (the why) is REQUIRED; it is the record. - `exempt` — judged genuinely one-off. `reason` REQUIRED. + - `redundant` — should be removed: another shape already does its + job. `covered_by` {path, symbol} names that shape and `reason` says + why it covers this one — for a test, what the covering test checks + that this one also checked. test_guard_groups lists the candidates. + - `unused` — should be removed: nothing needs it. `reason` REQUIRED. - `canonical` of snippet N — this row IS the snippet's reference (rarely set by hand; the coverage sync stamps these mechanically). - `unclassified` — withdraw a judgment; the shape rejoins the todo. @@ -38,7 +43,7 @@ async def classify_shapes( Args: project_id: The project whose ledger is being judged. classifications: Objects of {path, symbol, status, kind?, snippet_id?, - idea_id?, reason?, reason_code?}. path+symbol name the shape exactly as + idea_id?, reason?, reason_code?, covered_by?}. path+symbol name the shape exactly as list_shapes shows it; kind ("sym"/"css") narrows when one file defines both. snippet_id is required for canonical/instance/ variant — or idea_id, a family idea: the shape is then judged @@ -46,7 +51,7 @@ async def classify_shapes( language, or its first reference when none is in that language (an idea is shared across languages: a Python shape can be an instance of an idea whose reference is Go). reason is required - for variant/exempt. reason_code is + for variant/exempt/redundant/unused. reason_code is an OPTIONAL index beside the prose (one of: scoped-css, one-off-handler, test-helper, convention-plumbing, pure-helper, generated, script, typed-record) so the ledger can be filtered @@ -106,7 +111,9 @@ async def list_shapes( (fed by the coverage refresh). Filters compose: Args: - status: canonical | instance | variant | exempt | scoped | unclassified. + status: canonical | instance | variant | exempt | redundant | unused | + scoped | unclassified. `redundant`/`unused` are the removal + verdicts: the row stays until the code goes. `scoped` is the sync's mechanical stamp on one-offs by construction (a Vue component's scoped