From 5d764ecf2f8db574aa9932565c01d19f2635cf44 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:06:32 -0500 Subject: [PATCH 01/27] test(8249): the caller-scoping contract is a property of the services, not four lists of names Review of the signature-flagged tests: - Four route files each listed service names by hand and checked each takes user_id. A new service without the caller passed them, and a renamed one failed them. They become one test over services/{design_systems,systems, rulebooks,snippets}.py: every public coroutine takes user_id, except eight named with the reason each needs none, and an exception for a function that is gone or now takes the caller fails too. - test_routes_trash was four existence checks: blueprint name, registered, handlers callable, the service surface, delete's parameter names. It becomes one check that the three trash routes are on the app; what they do is proven by test_services_trash and test_mcp_tool_trash. Co-Authored-By: Claude Opus 5.5 --- tests/test_routes_design_systems.py | 15 ------- tests/test_routes_rulebooks.py | 18 -------- tests/test_routes_snippets.py | 13 ------ tests/test_routes_systems.py | 11 ----- tests/test_routes_trash.py | 40 +++++------------- tests/test_service_user_id_contract.py | 58 ++++++++++++++++++++++++++ 6 files changed, 69 insertions(+), 86 deletions(-) create mode 100644 tests/test_service_user_id_contract.py diff --git a/tests/test_routes_design_systems.py b/tests/test_routes_design_systems.py index 1ed0b322..e5afa5cd 100644 --- a/tests/test_routes_design_systems.py +++ b/tests/test_routes_design_systems.py @@ -60,21 +60,6 @@ def test_every_endpoint_is_reachable_on_the_app(): } -def test_service_functions_take_user_id(): - """Routes must call the services with user_id — verify the contract (#33).""" - from grimoire.services import design_systems as svc - for fn_name in ( - "create_design_system", "list_design_systems", "get_design_system", - "update_design_system", "delete_design_system", "resolve_design_system", - "create_token", "list_tokens", "update_token", "delete_token", - "set_project_design_system", - "stylesheet_for_system", "check_snippets_against_system", - ): - fn = getattr(svc, fn_name) - assert callable(fn) - assert "user_id" in inspect.signature(fn).parameters - - def test_agent_and_web_surfaces_stay_at_parity(): """The MCP tools and the REST routes are two callers of one service; a capability on one has to exist on the other. diff --git a/tests/test_routes_rulebooks.py b/tests/test_routes_rulebooks.py index e0597c59..b228c278 100644 --- a/tests/test_routes_rulebooks.py +++ b/tests/test_routes_rulebooks.py @@ -37,23 +37,6 @@ def test_topic_handlers_callable(): assert callable(getattr(rb_routes, name)) -def test_service_signatures_require_user_id(): - """Routes must call services with user_id — verify the contract.""" - from grimoire.services import rulebooks as svc - for fn_name in ( - "create_rulebook", "list_rulebooks", "get_rulebook", - "update_rulebook", "delete_rulebook", "find_rulebook_by_title", - "create_topic", "list_topics", "get_topic", "update_topic", "delete_topic", - "create_rule", "create_project_rule", "rule_detail", - "set_rule_systems", "add_rule_relation", "remove_rule_relation", - "list_rules", - "get_rule", "update_rule", "delete_rule", - "get_applicable_rules", - ): - sig = inspect.signature(getattr(svc, fn_name)) - assert "user_id" in sig.parameters, f"{fn_name} missing user_id param" - - def test_rule_model_carries_project_id_and_topic_id_nullable(): """Migration 0059 made topic_id nullable and added project_id.""" from grimoire.models.rulebook import Rule @@ -112,7 +95,6 @@ def test_the_rule_list_zero_fills_usage_on_every_row(): reading `undefined` on almost every row — and the difference between "no events" and "no field" is exactly the distinction a readout must keep. """ - import inspect from grimoire.routes import rulebooks as rb_routes diff --git a/tests/test_routes_snippets.py b/tests/test_routes_snippets.py index ed8477b6..a9f2d1c8 100644 --- a/tests/test_routes_snippets.py +++ b/tests/test_routes_snippets.py @@ -26,19 +26,6 @@ def test_snippet_handlers_callable(): assert callable(getattr(routes, name)) -def test_service_functions_take_user_id(): - """Routes must call snippet services with user_id — verify the contract.""" - from grimoire.services import snippets as svc - for fn_name in ( - "create_snippet", "list_snippets", "get_snippet", "update_snippet", - "delete_snippet", "merge_snippets", "record_verification", - "unmerge_snippet", - ): - fn = getattr(svc, fn_name) - assert callable(fn) - assert "user_id" in inspect.signature(fn).parameters - - def test_agent_and_web_surfaces_stay_at_parity(): """The MCP tools and the REST routes are two callers of one service; a capability on one has to exist on the other. Two doors maintained diff --git a/tests/test_routes_systems.py b/tests/test_routes_systems.py index a526e0a1..1f5f08af 100644 --- a/tests/test_routes_systems.py +++ b/tests/test_routes_systems.py @@ -25,14 +25,3 @@ def test_system_handlers_callable(): assert callable(getattr(routes, name)) -def test_service_functions_take_user_id(): - """Routes must call systems services with user_id — verify the contract.""" - from grimoire.services import systems as svc - for fn_name in ( - "create_system", "list_systems", "get_system", "update_system", - "delete_system", "list_records_for_system", "list_issues", - "open_issue_counts_by_system", - ): - fn = getattr(svc, fn_name) - assert callable(fn) - assert "user_id" in inspect.signature(fn).parameters diff --git a/tests/test_routes_trash.py b/tests/test_routes_trash.py index 5968a803..5ef7affd 100644 --- a/tests/test_routes_trash.py +++ b/tests/test_routes_trash.py @@ -1,32 +1,14 @@ -"""Structural tests for the trash blueprint + delete-flip contracts.""" -import inspect +"""The trash API is routed: list, restore and purge reach handlers on the +running app. What they do is the trash service's to prove +(tests/test_services_trash.py, tests/test_mcp_tool_trash.py).""" -def test_trash_blueprint_registered(): - from grimoire.routes.trash import trash_bp - assert trash_bp.name == "trash" - assert trash_bp.url_prefix == "/api/trash" - - -def test_trash_blueprint_registered_in_app(): +def test_the_trash_routes_are_on_the_app(): from grimoire.app import create_app - app = create_app() - assert "trash" in app.blueprints - - -def test_trash_handlers_callable(): - from grimoire.routes import trash as trash_routes - for name in ("list_trash", "restore_batch", "purge_batch"): - assert callable(getattr(trash_routes, name)) - - -def test_trash_service_surface(): - from grimoire.services import trash as svc - for fn_name in ("delete", "restore", "purge", "list_trash", "purge_expired", "alive"): - assert hasattr(svc, fn_name), f"trash service missing {fn_name}" - - -def test_delete_service_signature(): - from grimoire.services.trash import delete - params = inspect.signature(delete).parameters - assert "user_id" in params and "entity_type" in params and "entity_id" in params + rules = { + (str(r.rule), m) for r in create_app().url_map.iter_rules() for m in r.methods + } + for route in (("/api/trash", "GET"), + ("/api/trash//restore", "POST"), + ("/api/trash/", "DELETE")): + assert route in rules, route diff --git a/tests/test_service_user_id_contract.py b/tests/test_service_user_id_contract.py new file mode 100644 index 00000000..fbf1c0cb --- /dev/null +++ b/tests/test_service_user_id_contract.py @@ -0,0 +1,58 @@ +"""Every public service the routes and MCP tools call is scoped by its caller. + +The access helpers (services/access.py) need the caller's id, so a public +coroutine in these modules takes `user_id`. A new one without it fails here, +before a route passes it nothing. The exceptions are named with the reason +each needs none: they work on records the caller has already been allowed to +read, on ids it already holds, or on the whole instance. +""" +import ast +import pathlib + +import pytest + +SERVICES = pathlib.Path(__file__).resolve().parents[1] / "src" / "grimoire" / "services" + +NEEDS_NO_CALLER = { + "systems": { + "standard_systems": "the shared vocabulary, the same for everyone", + "system_names_for": "names for records the caller has already read", + }, + "rulebooks": { + "list_rule_moments": "batch detail for rule ids the caller already holds", + "list_rule_systems": "batch detail for rule ids the caller already holds", + "list_rule_relations": "batch detail for rule ids the caller already holds", + }, + "snippets": { + "backfill_snippet_data": "a startup backfill over every snippet", + "attach_live_body": "decorates a snippet the caller has already pulled", + "invalidate_for_push": "a forge push touches every snippet at that location", + }, + "design_systems": {}, +} + + +def _public_coroutines(module: str) -> dict[str, list[str]]: + tree = ast.parse((SERVICES / f"{module}.py").read_text()) + return { + n.name: [a.arg for a in n.args.args + n.args.kwonlyargs] + for n in tree.body + if isinstance(n, ast.AsyncFunctionDef) and not n.name.startswith("_") + } + + +@pytest.mark.parametrize("module", sorted(NEEDS_NO_CALLER)) +def test_every_public_service_takes_the_caller(module): + found = _public_coroutines(module) + missing = sorted( + name for name, args in found.items() + if "user_id" not in args and name not in NEEDS_NO_CALLER[module] + ) + assert not missing, f"services/{module}.py: {missing} take no user_id" + # An exception for a function that is gone, or now takes the caller, + # would excuse whatever takes the name next. + stale = sorted( + name for name in NEEDS_NO_CALLER[module] + if name not in found or "user_id" in found[name] + ) + assert not stale, f"services/{module}.py: stale exceptions {stale}" -- 2.54.0 From 496d047d69218f2aeeab7892b879498625840973 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:06:32 -0500 Subject: [PATCH 02/27] test(8249): DELIBERATE BREAK, a service without the caller and the trash list route removed Reverted by the next commit. CI must go red on test_service_user_id_contract[systems] and test_routes_trash. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/routes/trash.py | 2 +- src/grimoire/services/systems.py | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/src/grimoire/routes/trash.py b/src/grimoire/routes/trash.py index 001255fb..7f97b775 100644 --- a/src/grimoire/routes/trash.py +++ b/src/grimoire/routes/trash.py @@ -10,7 +10,7 @@ trash_bp = Blueprint("trash", __name__, url_prefix="/api/trash") -@trash_bp.get("") +# DELIBERATE BREAK (#8249) @login_required async def list_trash(): return jsonify({"batches": await trash_svc.list_trash(get_current_user_id())}) diff --git a/src/grimoire/services/systems.py b/src/grimoire/services/systems.py index 10a70c07..eea7b118 100644 --- a/src/grimoire/services/systems.py +++ b/src/grimoire/services/systems.py @@ -535,3 +535,7 @@ async def list_issues(user_id: int, project_id: int, open_only: bool = True) -> query = query.order_by(Note.updated_at.desc()) result = await session.execute(query) return list(result.scalars().all()) + + +async def list_everything(project_id: int): # DELIBERATE BREAK (#8249) + return [] -- 2.54.0 From bd69c8d0963ad45b97741aaacf122d2a3a26a8d1 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:10:02 -0500 Subject: [PATCH 03/27] Revert the deliberate break: the systems service and the trash list route are back Co-Authored-By: Claude Opus 5.5 --- src/grimoire/routes/trash.py | 2 +- src/grimoire/services/systems.py | 4 ---- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/src/grimoire/routes/trash.py b/src/grimoire/routes/trash.py index 7f97b775..001255fb 100644 --- a/src/grimoire/routes/trash.py +++ b/src/grimoire/routes/trash.py @@ -10,7 +10,7 @@ trash_bp = Blueprint("trash", __name__, url_prefix="/api/trash") -# DELIBERATE BREAK (#8249) +@trash_bp.get("") @login_required async def list_trash(): return jsonify({"batches": await trash_svc.list_trash(get_current_user_id())}) diff --git a/src/grimoire/services/systems.py b/src/grimoire/services/systems.py index eea7b118..10a70c07 100644 --- a/src/grimoire/services/systems.py +++ b/src/grimoire/services/systems.py @@ -535,7 +535,3 @@ async def list_issues(user_id: int, project_id: int, open_only: bool = True) -> query = query.order_by(Note.updated_at.desc()) result = await session.execute(query) return list(result.scalars().all()) - - -async def list_everything(project_id: int): # DELIBERATE BREAK (#8249) - return [] -- 2.54.0 From 2a4d73176e05ff6472ac619a3de63367668c2b9f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:09:47 -0500 Subject: [PATCH 04/27] test(8249): signature and source-text batch, the hook tests run the hook - The caller-scoping property now covers services/family, family_adoption and platforms, with the seven reads that need no caller named and why. The hand-written platform list goes. - The snippet location keys: one test checks every door (service, MCP tool, web route) takes them; the route-only copy goes. - The write-path hook: the payload-shape and skip-list tests searched the shell script for strings. They now run the hook against a local listener and check what it sends: the code from each of the four payload field names, and nothing for a note, JSON or SVG while a YAML file and a .py are still asked about. Co-Authored-By: Claude Opus 5.5 --- tests/test_routes_platforms.py | 16 ++-------- tests/test_routes_snippets.py | 13 -------- tests/test_service_user_id_contract.py | 13 ++++++++ tests/test_snippet_location_filter.py | 7 ++++- tests/test_write_path_trigger.py | 43 ++++++++++++++------------ 5 files changed, 46 insertions(+), 46 deletions(-) diff --git a/tests/test_routes_platforms.py b/tests/test_routes_platforms.py index 3b98624b..ae8c17ab 100644 --- a/tests/test_routes_platforms.py +++ b/tests/test_routes_platforms.py @@ -1,7 +1,6 @@ -"""Structural tests for the platforms blueprint — -registration and the route-to-service contract. What the writes do is in -tests/test_integration_platforms.py.""" -import inspect +"""Structural tests for the platforms blueprint: every endpoint is routed. +That each service takes its caller is in tests/test_service_user_id_contract.py, +and what the writes do is in tests/test_integration_platforms.py.""" def test_platforms_blueprint_registered_in_app(): @@ -17,12 +16,3 @@ def test_platforms_blueprint_registered_in_app(): ("/api/projects//platforms", "PUT"), ): assert (rule, method) in rules, f"{method} {rule} is not routed" - - -def test_writes_to_the_catalog_and_to_a_project_take_the_caller(): - """The catalog's admin gate and the project's write gate both live in the - service, so every write must be handed the caller to check.""" - from grimoire.services import platforms as svc - for name in ("create_platform", "update_platform", "set_project_platforms", - "project_platforms"): - assert "user_id" in inspect.signature(getattr(svc, name)).parameters diff --git a/tests/test_routes_snippets.py b/tests/test_routes_snippets.py index a9f2d1c8..6732e486 100644 --- a/tests/test_routes_snippets.py +++ b/tests/test_routes_snippets.py @@ -73,19 +73,6 @@ def test_project_scoping_reaches_every_caller(): assert "project_id" in inspect.getsource(routes.list_snippets_route) -def test_location_lookup_reaches_every_caller(): - """The reverse lookup — "what already lives here?" — has to be askable from - both surfaces, or an agent and a human get different answers about the same - file.""" - from grimoire.mcp.tools import snippets as tools - from grimoire.routes import snippets as routes - from grimoire.services import snippets as svc - for key in ("repo", "path", "symbol"): - assert key in inspect.signature(svc.list_snippets).parameters - assert key in inspect.signature(tools.list_snippets).parameters - assert f'request.args.get("{key}"' in inspect.getsource(routes) - - def test_update_field_map_matches_service_kwargs(): """Every field the PATCH route forwards must be a real update_snippet kwarg (interface-contract parity).""" diff --git a/tests/test_service_user_id_contract.py b/tests/test_service_user_id_contract.py index fbf1c0cb..80e2b9bf 100644 --- a/tests/test_service_user_id_contract.py +++ b/tests/test_service_user_id_contract.py @@ -29,6 +29,19 @@ NEEDS_NO_CALLER = { "invalidate_for_push": "a forge push touches every snippet at that location", }, "design_systems": {}, + "family": { + "next_version": "numbers a canon version inside a write that has checked the caller", + }, + "family_adoption": { + "family_reference_ids": "the coverage refresh's mechanical read for a project", + "family_reach_ids": "retrieval's reach for a project it has already scoped", + }, + "platforms": { + "list_platforms": "the catalog is global and the same for everyone", + "resolve_slugs": "a lookup in the global catalog", + "record_detected": "the coverage refresh records what it detected", + "detect_for_project": "the coverage refresh's own call", + }, } diff --git a/tests/test_snippet_location_filter.py b/tests/test_snippet_location_filter.py index 0f97779c..ff23ff14 100644 --- a/tests/test_snippet_location_filter.py +++ b/tests/test_snippet_location_filter.py @@ -151,7 +151,7 @@ def test_location_clause_renders_a_jsonpath_containment(): # --- surface plumbing --------------------------------------------------------- -def test_agent_and_service_surfaces_take_the_same_location_params(): +def test_every_door_takes_the_same_location_params(): from grimoire.mcp.tools.snippets import list_snippets as mcp_list from grimoire.services.snippets import list_snippets as svc_list @@ -160,6 +160,11 @@ def test_agent_and_service_surfaces_take_the_same_location_params(): for key in LOCATION_KEYS: assert key in params, f"{fn.__qualname__} is missing {key}" assert params[key].default == "", f"{fn.__qualname__}.{key} default drifted" + # The web door reads the same keys from the query string, so an agent and + # a human asking "what already lives here?" get the same answer. + from grimoire.routes import snippets as routes + for key in LOCATION_KEYS: + assert f'request.args.get("{key}"' in inspect.getsource(routes), f"the route ignores {key}" def test_route_forwards_the_location_args_by_name(): diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index 5544f693..0ecd9458 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -1014,13 +1014,19 @@ def test_hook_is_executable_and_shell_valid(): subprocess.run(["bash", "-n", str(HOOK)], check=True) -def test_hook_reads_both_write_and_edit_payload_shapes(): +@pytest.mark.parametrize("tool,field", [ + ("Write", "content"), ("Write", "file_content"), + ("Edit", "new_string"), ("Edit", "new_str"), +]) +def test_hook_reads_every_write_and_edit_payload_shape(tmp_path, tool, field): """Write and Edit name the payload differently, and the names have changed - across Claude Code versions — read whichever is present.""" - src = HOOK.read_text() - for field in ("content", "file_content", "new_string", "new_str"): - assert f".tool_input.{field}" in src - assert ".tool_input.file_path" in src + across Claude Code versions: the code is sent whichever one is present.""" + code = "def debounce(fn):\n return fn\n" + seen = _run_hook_against_sink(tmp_path, { + "session_id": f"s-shape-{field}", "cwd": str(tmp_path), "tool_name": tool, + "tool_input": {"file_path": str(tmp_path / "b.py"), field: code}, + }) + assert seen.get("code") == [code] def test_hook_stays_a_get_so_a_read_scoped_key_works(): @@ -1046,19 +1052,18 @@ def test_hook_exits_silently_when_unconfigured(): assert out.stdout.strip() == "" -def test_hook_skips_prose_and_data_files(): - """No round-trip for a markdown edit — the server would return nothing - anyway. The list lives in the shared library and the hook asks it.""" - lib = (PLUGIN / "hooks" / "grimoire_defs.sh").read_text() - skip = re.search(r"grimoire_skip_path\(\) \{\n case \"\$1\" in\n(.*?)esac", lib, re.S) - assert skip, "expected an extension skip list in grimoire_defs.sh" - for ext in ("*.md", "*.json", "*.lock", "*.png"): - assert ext in skip.group(1) - # Config formats are deliberately NOT skipped — a workflow file is reusable. - assert "*.yml" not in skip.group(1) - src = HOOK.read_text() - assert 'grimoire_skip_path "$file_path" && exit 0' in src - assert '/grimoire_defs.sh"' in src # sourced, not copied +@pytest.mark.parametrize("name,asks", [ + ("README.md", False), ("data.json", False), ("logo.svg", False), + ("deploy.yml", True), ("b.py", True), +]) +def test_hook_asks_about_code_and_never_about_prose_or_data(tmp_path, name, asks): + """Prior art is about code. A note or a data file sends nothing; a YAML + workflow is code that gets copied between projects, so it is asked about.""" + seen = _run_hook_against_sink(tmp_path, { + "session_id": f"s-skip-{name}", "cwd": str(tmp_path), "tool_name": "Write", + "tool_input": {"file_path": str(tmp_path / name), "content": "x: 1\n"}, + }) + assert bool(seen) is asks def test_hook_keeps_sync_and_reuse_dedup_apart(): -- 2.54.0 From 881e0fd75f18ab62f08c7716ad37d622492b949f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:09:47 -0500 Subject: [PATCH 05/27] fix(test-guards): an expected error is an outcome check, so a refusal test is not mock-only A refusal test raises, then checks nothing was written with assert_not_called. The mock-only signal counted only plain asserts as outcome checks, so 28 of the 44 tests it flagged in Grimoire's own suite were refusals. pytest.raises and assertRaises now count. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/services/test_guards.py | 8 +++++++- tests/test_test_guards.py | 3 +++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/src/grimoire/services/test_guards.py b/src/grimoire/services/test_guards.py index 7d37c7ab..44eda46c 100644 --- a/src/grimoire/services/test_guards.py +++ b/src/grimoire/services/test_guards.py @@ -75,7 +75,13 @@ SIGNALS = { _MOCK_ASSERT_RE = re.compile( r"\.assert_(?:called|awaited|not_called|not_awaited|any_call|has_calls)\w*\(|toHaveBeenCalled" ) -_PLAIN_ASSERT_RE = re.compile(r"^\s*assert\b|\bexpect\((?![^\n]*toHaveBeenCalled)", re.MULTILINE) +# An outcome check: a plain assert, an expect that is not about a mock, or an +# expected error. A refusal test that raises and then checks nothing was +# written has checked its outcome; the mock assertion is the "nothing" half. +_PLAIN_ASSERT_RE = re.compile( + r"^\s*assert\b|\bexpect\((?![^\n]*toHaveBeenCalled)|\bpytest\.raises\(|\.assertRaises\w*\(", + re.MULTILINE, +) def is_test_path(path: str) -> bool: diff --git a/tests/test_test_guards.py b/tests/test_test_guards.py index dad5736e..5667f947 100644 --- a/tests/test_test_guards.py +++ b/tests/test_test_guards.py @@ -116,6 +116,9 @@ def test_weak_signals_are_read_from_the_body(): assert tg.test_signals(" f()\n mock.assert_called_once()\n") == ["mock-only"] # A plain assert beside a mock check is a real check, so no signal. assert tg.test_signals(" f()\n mock.assert_called_once()\n assert out == 1\n") == [] + # So is an expected error: a refusal, then a check that nothing was written. + refusal = " with pytest.raises(ValueError):\n f()\n write.assert_not_awaited()\n" + assert tg.test_signals(refusal) == [] assert tg.test_signals(" text = path.read_text()\n assert 'x' in text\n") == ["source-text"] -- 2.54.0 From adc460b5bad3f461361bfcb6fa6dd4d6042bf751 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:09:47 -0500 Subject: [PATCH 06/27] test(8249): DELIBERATE BREAK, notes no longer skipped, new_str not read, a platform read without the caller Reverted by the next commit. CI must go red on test_hook_asks_about_code_and_never_about_prose_or_data[README.md], test_hook_reads_every_write_and_edit_payload_shape[Edit-new_str] and test_every_public_service_takes_the_caller[platforms]. Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_defs.sh | 2 +- plugin/hooks/grimoire_prior_art.sh | 2 +- src/grimoire/services/platforms.py | 4 ++++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/plugin/hooks/grimoire_defs.sh b/plugin/hooks/grimoire_defs.sh index 0c02aabe..474e7444 100644 --- a/plugin/hooks/grimoire_defs.sh +++ b/plugin/hooks/grimoire_defs.sh @@ -39,7 +39,7 @@ # often exactly the thing worth reusing. grimoire_skip_path() { case "$1" in - *.md|*.mdx|*.txt|*.rst|*.json|*.lock|*.log|*.csv|*.tsv|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.ico|*.pdf) + *.mdx|*.txt|*.rst|*.json|*.lock|*.log|*.csv|*.tsv|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.ico|*.pdf) return 0 ;; esac return 1 diff --git a/plugin/hooks/grimoire_prior_art.sh b/plugin/hooks/grimoire_prior_art.sh index 95bc379a..c193cb51 100755 --- a/plugin/hooks/grimoire_prior_art.sh +++ b/plugin/hooks/grimoire_prior_art.sh @@ -60,7 +60,7 @@ event_cwd=$(grimoire_json_pick "$event_flat" '.cwd') code=$(grimoire_json_pick "$event_flat" '.tool_input.content') [ -n "$code" ] || code=$(grimoire_json_pick "$event_flat" '.tool_input.file_content') [ -n "$code" ] || code=$(grimoire_json_pick "$event_flat" '.tool_input.new_string') -[ -n "$code" ] || code=$(grimoire_json_pick "$event_flat" '.tool_input.new_str') +# DELIBERATE BREAK (#8249): the legacy Edit field is no longer read grimoire_skip_path "$file_path" && exit 0 diff --git a/src/grimoire/services/platforms.py b/src/grimoire/services/platforms.py index 67e4f7fb..2362c075 100644 --- a/src/grimoire/services/platforms.py +++ b/src/grimoire/services/platforms.py @@ -333,3 +333,7 @@ async def detect_for_project(project_id: int, paths: list[str]) -> list[int]: logger.info("project %s: detected platform(s) %s", project_id, added) return added + + +async def list_mine(project_id: int): # DELIBERATE BREAK (#8249) + return [] -- 2.54.0 From 3f1e9588ab68d278a5c3ea760f109d9968778042 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:12:42 -0500 Subject: [PATCH 07/27] Revert the deliberate break: notes skipped again, new_str read again, no platform read without the caller Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_defs.sh | 2 +- plugin/hooks/grimoire_prior_art.sh | 2 +- src/grimoire/services/platforms.py | 4 ---- 3 files changed, 2 insertions(+), 6 deletions(-) diff --git a/plugin/hooks/grimoire_defs.sh b/plugin/hooks/grimoire_defs.sh index 474e7444..0c02aabe 100644 --- a/plugin/hooks/grimoire_defs.sh +++ b/plugin/hooks/grimoire_defs.sh @@ -39,7 +39,7 @@ # often exactly the thing worth reusing. grimoire_skip_path() { case "$1" in - *.mdx|*.txt|*.rst|*.json|*.lock|*.log|*.csv|*.tsv|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.ico|*.pdf) + *.md|*.mdx|*.txt|*.rst|*.json|*.lock|*.log|*.csv|*.tsv|*.svg|*.png|*.jpg|*.jpeg|*.gif|*.ico|*.pdf) return 0 ;; esac return 1 diff --git a/plugin/hooks/grimoire_prior_art.sh b/plugin/hooks/grimoire_prior_art.sh index c193cb51..95bc379a 100755 --- a/plugin/hooks/grimoire_prior_art.sh +++ b/plugin/hooks/grimoire_prior_art.sh @@ -60,7 +60,7 @@ event_cwd=$(grimoire_json_pick "$event_flat" '.cwd') code=$(grimoire_json_pick "$event_flat" '.tool_input.content') [ -n "$code" ] || code=$(grimoire_json_pick "$event_flat" '.tool_input.file_content') [ -n "$code" ] || code=$(grimoire_json_pick "$event_flat" '.tool_input.new_string') -# DELIBERATE BREAK (#8249): the legacy Edit field is no longer read +[ -n "$code" ] || code=$(grimoire_json_pick "$event_flat" '.tool_input.new_str') grimoire_skip_path "$file_path" && exit 0 diff --git a/src/grimoire/services/platforms.py b/src/grimoire/services/platforms.py index 2362c075..67e4f7fb 100644 --- a/src/grimoire/services/platforms.py +++ b/src/grimoire/services/platforms.py @@ -333,7 +333,3 @@ async def detect_for_project(project_id: int, paths: list[str]) -> list[int]: logger.info("project %s: detected platform(s) %s", project_id, added) return added - - -async def list_mine(project_id: int): # DELIBERATE BREAK (#8249) - return [] -- 2.54.0 From 85b29d642f9d14bdc0dde0b3e1bcd3f32e754c7d Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 07:12:42 -0500 Subject: [PATCH 08/27] test(8249): the payload-shape test expects the code as the shell sends it, without a trailing newline Co-Authored-By: Claude Opus 5.5 --- tests/test_write_path_trigger.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index 0ecd9458..3d13cc8f 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -1020,8 +1020,9 @@ def test_hook_is_executable_and_shell_valid(): ]) def test_hook_reads_every_write_and_edit_payload_shape(tmp_path, tool, field): """Write and Edit name the payload differently, and the names have changed - across Claude Code versions: the code is sent whichever one is present.""" - code = "def debounce(fn):\n return fn\n" + across Claude Code versions: the code is sent whichever one is present. + (The shell drops a trailing newline, so the code here has none.)""" + code = "def debounce(fn):\n return fn" seen = _run_hook_against_sink(tmp_path, { "session_id": f"s-shape-{field}", "cwd": str(tmp_path), "tool_name": tool, "tool_input": {"file_path": str(tmp_path / "b.py"), field: code}, -- 2.54.0 From 8fccaa0f3c3aeaafd292c62ddabfe2567e2a182b Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:24:22 -0500 Subject: [PATCH 09/27] test(8249): hook contract tests run the hooks instead of searching their source - test_write_path_trigger: - the sync, reuse and rule dedup channels: two string searches become one run of the hook twice in a session, checking each class of id comes back on its own parameter; - "stays a GET": one request to the prior-art route, with no body; - the route/hook argument contract: the hook runs with every ledger it keeps already holding something, and every key it sends must be read by the route (read from the route's AST); - the "names the shapes" string search goes: two runtime tests already check the Write and the Edit cases. - test_rule_moment_signal_hooks: the body the route must read is the body the hook actually sent. - test_task_claims: session start is run and must send source and session_id; session end is run and releases on logout but not on /clear. Co-Authored-By: Claude Opus 5.5 --- tests/test_rule_moment_signal_hooks.py | 19 ++- tests/test_task_claims.py | 42 ++++-- tests/test_write_path_trigger.py | 185 ++++++++++++------------- 3 files changed, 131 insertions(+), 115 deletions(-) diff --git a/tests/test_rule_moment_signal_hooks.py b/tests/test_rule_moment_signal_hooks.py index 13bf56f4..bc8e40ce 100644 --- a/tests/test_rule_moment_signal_hooks.py +++ b/tests/test_rule_moment_signal_hooks.py @@ -218,14 +218,19 @@ def test_session_end_removes_the_sessions_moment_files_and_no_others(sandbox): assert sorted(p.name for p in ledger.iterdir()) == ["s2.acts"] -def test_the_hook_and_the_route_agree_on_the_body(): - """A contract across the shell/Python seam: a renamed field fails silently.""" - src = (HOOKS / "grimoire_record_opened.sh").read_text() +def test_the_hook_and_the_route_agree_on_the_body(sandbox): + """A contract across the shell/Python seam: a renamed field fails silently. + The body is what the hook actually sends; the route must read every field + of it, and the service must answer with the `context` the hook prints.""" + tmp, env = sandbox + _run("grimoire_record_opened.sh", + {"session_id": "s1", "tool_name": "mcp__grimoire__get_rule", + "tool_input": {"rule_id": 11}}, env, + FAKE_CURL_REPLY=json.dumps({"moments": [], "context": ""})) + sent = json.loads((tmp / "curl.body").read_text()) route = inspect.getsource(plugin_routes.rule_opened) - assert "/api/plugin/rule-opened" in src - for field in ("rule_id", "session_id", "acts"): - assert f'"{field}"' in src and f'"{field}"' in route - assert "'.context'" in src + for field in sent: + assert f'"{field}"' in route, f"the route ignores {field}" assert '"context"' in inspect.getsource(judgments_svc.opened_after) diff --git a/tests/test_task_claims.py b/tests/test_task_claims.py index b6e44b75..d8c0e114 100644 --- a/tests/test_task_claims.py +++ b/tests/test_task_claims.py @@ -24,7 +24,7 @@ import pytest_asyncio from grimoire.services import notes as notes_svc from grimoire.services import task_claims as tc -from tests.helpers import ensure_user +from tests.helpers import ensure_user, http_sink ROOT = Path(__file__).resolve().parents[1] @@ -233,12 +233,33 @@ def test_a_dead_claim_on_finished_work_is_not_news(): assert _render("startup", [done]) == "" -def test_the_session_start_hook_sends_the_source_and_the_session(): +def _run_hook(script, event, tmp_path, port): + import os + import shutil + import subprocess + + for tool in ("bash", "curl"): + if shutil.which(tool) is None: + pytest.skip(f"hook runtime tool {tool!r} not installed") + env = {"PATH": os.environ["PATH"], "HOME": str(tmp_path), "TMPDIR": str(tmp_path), + "GRIMOIRE_URL": f"http://127.0.0.1:{port}", "GRIMOIRE_TOKEN": "t", + "CLAUDE_PROJECT_DIR": str(tmp_path)} + out = subprocess.run(["bash", str(ROOT / "plugin/hooks" / script)], + input=json.dumps(event), capture_output=True, text=True, + env=env, timeout=30) + assert out.returncode == 0, out.stderr + + +def test_the_session_start_hook_sends_the_source_and_the_session(tmp_path): """The reader branches on what the hook sends; a hook that stopped sending either would leave every session on the no-claims path, silently.""" - text = (ROOT / "plugin/hooks/grimoire_session_context.sh").read_text() - assert re.search(r'q="source=\$\(printf', text) - assert "session_id=$(printf" in text + with http_sink() as (port, seen): + _run_hook("grimoire_session_context.sh", + {"session_id": "s-start", "source": "compact", "cwd": str(tmp_path)}, + tmp_path, port) + asked = [q for q in seen if "source" in q] + assert asked and asked[0]["source"] == ["compact"] + assert asked[0]["session_id"] == ["s-start"] @pytest.mark.integration @@ -260,15 +281,18 @@ async def test_session_start_after_a_compaction_carries_the_claimed_task(users): # --- step 4: the hand-off ---------------------------------------------------- -def test_session_end_releases_claims_but_not_on_clear(): +@pytest.mark.parametrize("reason,releases", [("logout", True), ("clear", False)]) +def test_session_end_releases_claims_but_not_on_clear(tmp_path, reason, releases): """The mechanical half of the hand-off. A /clear keeps the claim, because SessionStart(source=clear) pushes the claimed work straight back.""" hooks = json.loads((ROOT / "plugin/hooks/hooks.json").read_text())["hooks"] commands = [h["command"] for b in hooks.get("SessionEnd", []) for h in b["hooks"]] assert any("grimoire_session_end.sh" in c for c in commands) - text = (ROOT / "plugin/hooks/grimoire_session_end.sh").read_text() - assert '[ "$reason" = "clear" ] && exit 0' in text - assert "/api/plugin/release-session" in text + with http_sink(by_path={}) as (port, seen): + _run_hook("grimoire_session_end.sh", {"session_id": "s-end", "reason": reason}, + tmp_path, port) + released = [q for q in seen if q["_path"] == "/api/plugin/release-session"] + assert ([q["session_id"] for q in released] == [["s-end"]]) is releases @pytest.mark.integration diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index 3d13cc8f..4dc907c0 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -936,41 +936,57 @@ def test_prior_art_line_takes_a_search_hit_whose_snippet_is_its_excerpt(): # --- the route between them -------------------------------------------------- -def test_route_reads_every_arg_the_hook_sends(): - """The hook's query string and the route's reader are one contract, - and the hook is the only caller — a rename on either side is silent.""" +def _route_args(*fns) -> set[str]: + """Every query key the given route functions read, from their AST.""" + import ast import inspect + import textwrap + keys = set() + for fn in fns: + for node in ast.walk(ast.parse(textwrap.dedent(inspect.getsource(fn)))): + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr == "get" and ast.unparse(node.func.value) == "request.args" + and node.args and isinstance(node.args[0], ast.Constant)): + keys.add(node.args[0].value) + return keys + + +def test_route_reads_every_arg_the_hook_sends(tmp_path): + """The hook's query string and the route's reader are one contract, and + the hook is the only caller, so a rename on either side is silent. The + hook is run with every ledger it keeps already holding something, and + every key it sends must be one the route reads.""" from grimoire.routes import plugin as routes - # The handler plus the query-scope helper it delegates repo/project_id - # to — the contract is what the ROUTE MODULE reads, wherever it reads it. - src = inspect.getsource(routes.write_path_prior_art) + inspect.getsource( - routes._project_scope - ) - for arg in ("path", "code", "repo", "project_id", "exclude_ids", - "exclude_sync_ids", "shapes", "seen_ruling_systems"): - assert f'request.args.get("{arg}"' in src, f"route ignores {arg}" - hook = HOOK.read_text() - for arg in ("path=", "code=", "exclude_ids=", "exclude_sync_ids=", "shapes="): - assert arg in hook, f"hook never sends {arg}" - - # The project-scope key is not spelled in the hook: it is whichever of `repo=` / `project_id=` grimoire_scope_query picks, so the hook - # splices in its output and the helper is the other half of the contract. - assert "grimoire_scope_query" in hook, "hook no longer asks for a project scope" - # Same arrangement for the OPENED ledger: spelled once in the - # helper so its ageing and format cannot drift from the naming ledger's. - assert "grimoire_held_query" in hook, "hook no longer sends the opened ledger" - defs = (HOOK.parent / "grimoire_defs.sh").read_text() - assert set(re.findall(r"printf '([a-z_]+)=", defs)) == {"repo", "project_id"} - # Its own leading `&` — it is appended to a query that already carries a - # scope key, rather than being one of the alternatives that opens one. - assert "printf '&held_rule_ids=" in defs, ( - "the opened ledger's query key is no longer spelled in the helper" - ) - # The rulings ledger, shared with the tool-rules hook. - assert "grimoire_rulings_query" in hook, "hook no longer sends the rulings ledger" - assert "printf '&seen_ruling_systems=" in defs + env = dict(_hook_runtime_env(), TMPDIR=str(tmp_path)) + repo = tmp_path / "repo" + repo.mkdir() + subprocess.run(["git", "init", "-q"], cwd=repo, check=True, env=env) + subprocess.run(["git", "remote", "add", "origin", "https://example.com/acme/app.git"], + cwd=repo, check=True, env=env) + state = tmp_path / "grimoire-priorart" + state.mkdir() + (state / "s-args.opened.ids").write_text("7\n") + reply = (b'{"context":"> hint","note_ids":[11],"sync_note_ids":[],"rule_ids":[33],' + b'"derive_keys":["dup:1"],"ruling_system_ids":[4]}') + with http_sink(reply) as (port, seen): + env["GRIMOIRE_URL"] = f"http://127.0.0.1:{port}" + payload = {"session_id": "s-args", "cwd": str(repo), "tool_name": "Write", + "tool_input": {"file_path": str(repo / "a.py"), + "content": "def debounce(fn):\n return fn"}} + for _ in range(2): + out = subprocess.run(["bash", str(HOOK)], input=json.dumps(payload), + capture_output=True, text=True, env=env) + assert out.returncode == 0, out.stderr + sent = set(seen[1]) + # Every ledger the hook keeps went out, so this run exercised the whole query. + assert {"path", "code", "repo", "shapes", "exclude_ids", "exclude_rule_ids", + "exclude_derive", "held_rule_ids", "seen_ruling_systems"} <= sent, sent + read = _route_args(routes.write_path_prior_art, routes._project_scope) + assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}" + # project_id is the other scope key the hook can send (from a project marker). + assert "project_id" in read def test_route_resolves_repo_to_a_project_not_to_a_location_filter(): @@ -1030,12 +1046,21 @@ def test_hook_reads_every_write_and_edit_payload_shape(tmp_path, tool, field): assert seen.get("code") == [code] -def test_hook_stays_a_get_so_a_read_scoped_key_works(): +def test_hook_stays_one_get_so_a_read_scoped_key_works(tmp_path): """Every other plugin hook works with a read-scoped key; a POST would demand - write scope (see auth.py) and silently break those installs.""" - src = HOOK.read_text() - assert "-X POST" not in src and "--data" not in src - assert "/api/plugin/prior-art?" in src + write scope (see auth.py) and silently break those installs. A write is one + request to the prior-art route, and it carries no body.""" + with http_sink(by_path={}) as (port, seen): + env = dict(_hook_runtime_env(), GRIMOIRE_URL=f"http://127.0.0.1:{port}", + TMPDIR=str(tmp_path)) + out = subprocess.run(["bash", str(HOOK)], input=json.dumps({ + "session_id": "s-get", "cwd": str(tmp_path), "tool_name": "Write", + "tool_input": {"file_path": str(tmp_path / "a.py"), + "content": "def debounce(fn):\n return fn"}, + }), capture_output=True, text=True, env=env) + assert out.returncode == 0, out.stderr + assert [e["_path"] for e in seen] == ["/api/plugin/prior-art"] + assert "_body" not in seen[0] def test_hook_exits_silently_when_unconfigured(): @@ -1067,20 +1092,6 @@ def test_hook_asks_about_code_and_never_about_prose_or_data(tmp_path, name, asks assert bool(seen) is asks -def test_hook_keeps_sync_and_reuse_dedup_apart(): - """The hook holds TWO per-session id files and feeds each its own class — - sync ids (snippets recording the edited file) to the sync file, the rest - to the reuse file. One shared file lets a reuse hint early in the session - silence the record-sync nudge when the recorded file is edited later.""" - src = HOOK.read_text() - assert ".sync.ids" in src # its own state file - assert "exclude_sync_ids=" in src # its own query channel - # The reuse file must NOT swallow sync ids — the write-back subtracts them. - # Spelled with the shell JSON readers in grimoire_defs.sh. - assert "grimoire_json_list_minus \"$body_flat\" '.note_ids' '.sync_note_ids'" in src - assert "grimoire_json_list \"$body_flat\" '.sync_note_ids'" in src - - def _hook_runtime_env(): """Env for tests that need the hook's tools to actually RUN. @@ -1422,20 +1433,6 @@ def test_hook_does_not_name_a_type_import_specifier_as_a_shape(tmp_path): assert seen["shapes"] == ["sym:Baz,sym:use"] -def test_hook_names_the_shapes_being_written(): - """The feed's two inputs: every definition in the payload, or — for an Edit - that changes a body, not a signature — the definition enclosing the edit, - found by walking the target file upward from the edited lines.""" - src = HOOK.read_text() - lib = (PLUGIN / "hooks" / "grimoire_defs.sh").read_text() - assert "grimoire_defs()" in lib # one extractor, shared - assert "grimoire_defs()" not in src # ...not a second copy here - assert ".tool_input.old_string" in src # the Edit's anchor - assert '"$file_path" | grimoire_defs | tail -1' in src # nearest definition above - # The ledger feed sends NAMES, never bodies, and stays on the one GET. - assert src.count("/api/plugin/prior-art?") == 1 - - def _run_hook_against_sink(tmp_path, payload): """Run the hook with GRIMOIRE_URL pointed at a throwaway local listener and return the query the hook sent (tests.helpers.http_sink).""" @@ -1633,6 +1630,31 @@ async def test_a_new_definition_close_to_a_snippet_is_asked_whether_it_is_a_copy assert "is new in this file" not in ctx +def test_each_class_of_hint_is_sent_back_on_its_own_channel(tmp_path): + """Reuse snippets, sync snippets and rules each go back as their own + exclusion on the next write. One shared channel would let a reuse hint + shown early silence the record-sync nudge when the recorded file is edited + later, and a rule silence a snippet it never resembled. A sync id is never + also sent as a reuse id.""" + reply = (b'{"context":"> hint","note_ids":[11,22],"sync_note_ids":[22],' + b'"rule_ids":[33]}') + with http_sink(reply) as (port, seen): + env = dict(_hook_runtime_env(), GRIMOIRE_URL=f"http://127.0.0.1:{port}", + TMPDIR=str(tmp_path)) + payload = {"session_id": "s-channels", "cwd": str(tmp_path), "tool_name": "Write", + "tool_input": {"file_path": str(tmp_path / "a.py"), + "content": "def debounce(fn):\n return fn"}} + for _ in range(2): + out = subprocess.run(["bash", str(HOOK)], input=json.dumps(payload), + capture_output=True, text=True, env=env) + assert out.returncode == 0, out.stderr + first, second = seen + assert not {"exclude_ids", "exclude_sync_ids", "exclude_rule_ids"} & set(first) + assert second["exclude_ids"] == ["11"] + assert second["exclude_sync_ids"] == ["22"] + assert second["exclude_rule_ids"] == ["33"] + + def test_the_hook_keeps_a_derive_channel_and_sends_it_back(tmp_path): """Derive keys the server returns land in the session's own `.derive.ids` file and go back as `exclude_derive` on the next write — @@ -1697,41 +1719,6 @@ async def test_the_write_time_divergence_check_is_named_in_band(): assert out["divergence"] == [] -def test_hook_keeps_the_rule_channel_apart_from_the_other_three(): - """The rule arm's channel, pinned the way the sync channel's is. - - Standing rules dedup on their OWN file and their OWN query parameter. One - shared channel lets a hint of one class silence a different class that had - never been shown. A rule named early - must not be re-offered on every later write, and must not silence — or be - silenced by — a snippet suggestion. - """ - src = HOOK.read_text() - assert ".rules.ids" in src # its own state file - assert "exclude_rule_ids=" in src # its own query channel - assert "grimoire_json_list \"$body_flat\" '.rule_ids'" in src # its own write-back - # And it rides the same request as the rest, not a second round trip. - assert "${rule_exclude_q}" in src - - -# ── `best_available` describes the BAR, not this arm's own second filter ────── -# -# A record the reader had already been shown, logged as something the ranker -# turned away, makes the near-miss distribution report scores ABOVE the very -# threshold it is read against. -# -# The rule arms key on `suppressed_count`, and its NULL branch rests on "null -# means the caller passed its exclusions INTO the search, so the reported -# score is already post-exclusion". That is true of auto_inject and reuse_slot. -# It is NOT true here: this is the one note arm that filters twice. `exclude_ids` -# takes `seen - pulled_seen` into the search, but the pulled-and-seen ids stay in -# the query on purpose (the arm's query doubles as the resemblance test) and are -# dropped afterwards in Python. -# -# The symptom: a near-miss maximum above the lowest score the arm ever -# RETURNED — a "rejection" that beat every acceptance. - - def _search_reporting(score, note): """A stand-in search that fills `report` the way the real one does. -- 2.54.0 From 0b12d812ea8d73ec8edd5f8a78dee1d786b9ff6d Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:24:27 -0500 Subject: [PATCH 10/27] test(8249): DELIBERATE BREAK, /clear releases claims, session start drops session_id, sync ids renamed Reverted by the next commit. CI must go red on test_session_end_releases_claims_but_not_on_clear[clear-False], test_the_session_start_hook_sends_the_source_and_the_session and test_each_class_of_hint_is_sent_back_on_its_own_channel. Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_prior_art.sh | 2 +- plugin/hooks/grimoire_session_context.sh | 2 +- plugin/hooks/grimoire_session_end.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/hooks/grimoire_prior_art.sh b/plugin/hooks/grimoire_prior_art.sh index 95bc379a..4a016bfc 100755 --- a/plugin/hooks/grimoire_prior_art.sh +++ b/plugin/hooks/grimoire_prior_art.sh @@ -227,7 +227,7 @@ if [ -n "$session_id" ]; then fi if [ -f "$syncfile" ]; then sync_seen=$(tr '\n' ',' < "$syncfile" 2>/dev/null | sed 's/,$//') - [ -n "$sync_seen" ] && sync_exclude_q="&exclude_sync_ids=${sync_seen}" + [ -n "$sync_seen" ] && sync_exclude_q="&exclude_sync=${sync_seen}" fi if [ -f "$derivefile" ]; then derive_seen=$(tr '\n' ',' < "$derivefile" 2>/dev/null | sed 's/,$//' | grimoire_urlenc) || derive_seen="" diff --git a/plugin/hooks/grimoire_session_context.sh b/plugin/hooks/grimoire_session_context.sh index 8b730d98..ecff6f33 100755 --- a/plugin/hooks/grimoire_session_context.sh +++ b/plugin/hooks/grimoire_session_context.sh @@ -181,7 +181,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then # with its latest logs; a new session hears about other sessions' claims. sid_now=$(grimoire_json_pick "$event_flat" '.session_id') q="source=$(printf '%s' "$source" | grimoire_urlenc)" - [ -n "$sid_now" ] && q="${q}&session_id=$(printf '%s' "$sid_now" | grimoire_urlenc)" + : # DELIBERATE BREAK (#8249): session_id no longer sent [ -n "$scope" ] && q="${q}&${scope}" q="?${q}" # ONE FETCH, NAMED WHEN IT FAILS. A timeout, an HTTP error and a refused key diff --git a/plugin/hooks/grimoire_session_end.sh b/plugin/hooks/grimoire_session_end.sh index 01dd283c..56bc3e81 100755 --- a/plugin/hooks/grimoire_session_end.sh +++ b/plugin/hooks/grimoire_session_end.sh @@ -41,7 +41,7 @@ rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \ "${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true reason=$(grimoire_json_pick "$event_flat" '.reason') -[ "$reason" = "clear" ] && exit 0 +# DELIBERATE BREAK (#8249): /clear releases too command -v curl >/dev/null 2>&1 || exit 0 grimoire_config || exit 0 -- 2.54.0 From 7da203d6a47578b053c6ee1e57bb8dd8a8ba1d17 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:27:39 -0500 Subject: [PATCH 11/27] Revert the deliberate break: /clear keeps claims, session start sends session_id, sync ids keep their name Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_prior_art.sh | 2 +- plugin/hooks/grimoire_session_context.sh | 2 +- plugin/hooks/grimoire_session_end.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/hooks/grimoire_prior_art.sh b/plugin/hooks/grimoire_prior_art.sh index 4a016bfc..95bc379a 100755 --- a/plugin/hooks/grimoire_prior_art.sh +++ b/plugin/hooks/grimoire_prior_art.sh @@ -227,7 +227,7 @@ if [ -n "$session_id" ]; then fi if [ -f "$syncfile" ]; then sync_seen=$(tr '\n' ',' < "$syncfile" 2>/dev/null | sed 's/,$//') - [ -n "$sync_seen" ] && sync_exclude_q="&exclude_sync=${sync_seen}" + [ -n "$sync_seen" ] && sync_exclude_q="&exclude_sync_ids=${sync_seen}" fi if [ -f "$derivefile" ]; then derive_seen=$(tr '\n' ',' < "$derivefile" 2>/dev/null | sed 's/,$//' | grimoire_urlenc) || derive_seen="" diff --git a/plugin/hooks/grimoire_session_context.sh b/plugin/hooks/grimoire_session_context.sh index ecff6f33..8b730d98 100755 --- a/plugin/hooks/grimoire_session_context.sh +++ b/plugin/hooks/grimoire_session_context.sh @@ -181,7 +181,7 @@ if [ -n "$url" ] && [ -n "$token" ] && command -v curl >/dev/null 2>&1; then # with its latest logs; a new session hears about other sessions' claims. sid_now=$(grimoire_json_pick "$event_flat" '.session_id') q="source=$(printf '%s' "$source" | grimoire_urlenc)" - : # DELIBERATE BREAK (#8249): session_id no longer sent + [ -n "$sid_now" ] && q="${q}&session_id=$(printf '%s' "$sid_now" | grimoire_urlenc)" [ -n "$scope" ] && q="${q}&${scope}" q="?${q}" # ONE FETCH, NAMED WHEN IT FAILS. A timeout, an HTTP error and a refused key diff --git a/plugin/hooks/grimoire_session_end.sh b/plugin/hooks/grimoire_session_end.sh index 56bc3e81..01dd283c 100755 --- a/plugin/hooks/grimoire_session_end.sh +++ b/plugin/hooks/grimoire_session_end.sh @@ -41,7 +41,7 @@ rm -f "${TMPDIR:-/tmp}/grimoire-moment/${safe_sid}".* \ "${TMPDIR:-/tmp}/grimoire-shapecheck/${safe_sid}".* 2>/dev/null || true reason=$(grimoire_json_pick "$event_flat" '.reason') -# DELIBERATE BREAK (#8249): /clear releases too +[ "$reason" = "clear" ] && exit 0 command -v curl >/dev/null 2>&1 || exit 0 grimoire_config || exit 0 -- 2.54.0 From 4321b05387639c218f99a78894869a3f7af3f6c7 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:27:39 -0500 Subject: [PATCH 12/27] test(8249): the route/hook argument run fills the sync channel too, so a renamed sync key is caught there Deliberate break 3 renamed exclude_sync_ids in the hook; the channel test caught it, the argument contract test did not, because its run had no sync ids to send. Co-Authored-By: Claude Opus 5.5 --- tests/test_write_path_trigger.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index 4dc907c0..a321e153 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -968,7 +968,7 @@ def test_route_reads_every_arg_the_hook_sends(tmp_path): state = tmp_path / "grimoire-priorart" state.mkdir() (state / "s-args.opened.ids").write_text("7\n") - reply = (b'{"context":"> hint","note_ids":[11],"sync_note_ids":[],"rule_ids":[33],' + reply = (b'{"context":"> hint","note_ids":[11,22],"sync_note_ids":[22],"rule_ids":[33],' b'"derive_keys":["dup:1"],"ruling_system_ids":[4]}') with http_sink(reply) as (port, seen): env["GRIMOIRE_URL"] = f"http://127.0.0.1:{port}" @@ -981,7 +981,7 @@ def test_route_reads_every_arg_the_hook_sends(tmp_path): assert out.returncode == 0, out.stderr sent = set(seen[1]) # Every ledger the hook keeps went out, so this run exercised the whole query. - assert {"path", "code", "repo", "shapes", "exclude_ids", "exclude_rule_ids", + assert {"path", "code", "repo", "shapes", "exclude_ids", "exclude_sync_ids", "exclude_rule_ids", "exclude_derive", "held_rule_ids", "seen_ruling_systems"} <= sent, sent read = _route_args(routes.write_path_prior_art, routes._project_scope) assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}" -- 2.54.0 From e92f129d4f9c62de483a49f3a2b3f382b30aa437 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:29:56 -0500 Subject: [PATCH 13/27] test(8249): moment and checkpoint hook guards run the hooks - test_moment_delivery: the route/hook name check runs the hook with the rule, opened and shape ledgers filled and checks every key it sends is read by the route; "leaves Grimoire's own tools alone" runs it with a listed Grimoire tool and sees no ask. - test_gate_stop_hooks: the action hook run twice on one checkpoint rule holds once, and books the rule on the session ledger after the stop. This replaces two line-window checks in test_pre_act_checkpoint. - The write hook never stopping a write: the two string guards (one per test file) are one, which now also forbids the shared deny helper, the call the old permissionDecision check could not see. - route_query_args (tests/helpers.py) reads the query keys a route takes from its AST, shared by both route/hook contract tests. Co-Authored-By: Claude Opus 5.5 --- tests/helpers.py | 18 ++++++++++ tests/test_gate_stop_hooks.py | 16 +++++++++ tests/test_moment_delivery.py | 60 +++++++++++++++++++------------- tests/test_pre_act_checkpoint.py | 56 ----------------------------- tests/test_write_path_trigger.py | 31 +++++++---------- 5 files changed, 81 insertions(+), 100 deletions(-) diff --git a/tests/helpers.py b/tests/helpers.py index 9249bd50..4286389d 100644 --- a/tests/helpers.py +++ b/tests/helpers.py @@ -530,3 +530,21 @@ def forge_tarball(files: dict[str, bytes], top: str = "widget") -> bytes: info.size = len(data) tar.addfile(info, io.BytesIO(data)) return buf.getvalue() + + +def route_query_args(*fns) -> set[str]: + """Every query-string key the given route functions read with + `request.args.get("…")`, from their AST. A hook test runs the hook, takes + the keys it actually sent, and checks the route reads each one.""" + import ast + import inspect + import textwrap + + keys = set() + for fn in fns: + for node in ast.walk(ast.parse(textwrap.dedent(inspect.getsource(fn)))): + if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr == "get" and ast.unparse(node.func.value) == "request.args" + and node.args and isinstance(node.args[0], ast.Constant)): + keys.add(node.args[0].value) + return keys diff --git a/tests/test_gate_stop_hooks.py b/tests/test_gate_stop_hooks.py index 63a8a0f5..9095ea99 100644 --- a/tests/test_gate_stop_hooks.py +++ b/tests/test_gate_stop_hooks.py @@ -131,6 +131,22 @@ def test_a_checkpoint_past_the_session_cap_is_reported_as_let_through(tmp_path): assert [(s["gate"], s["outcome"]) for s in _stops(seen)] == [("checkpoint", "let_through")] +def test_a_checkpoint_holds_a_rule_once_and_books_it_as_surfaced_either_way(tmp_path): + """The per-rule cap, end to end: the second command on the same rule goes + ahead. And the rule is on the session's rules ledger after the stop, + because what the server surfaced happened whichever way the hook rendered + it; bookkeeping inside one branch is how two arms' ledgers came to disagree.""" + with http_sink(by_path=_checkpoint_replies(rule_id=9)) as (port, seen): + first = _run(TOOL_RULES, tmp_path, port, + _bash_event(call="toolu_a", command="git commit -m x", cwd=str(tmp_path))) + second = _run(TOOL_RULES, tmp_path, port, + _bash_event(call="toolu_b", command="git commit -m y", cwd=str(tmp_path))) + assert _denied(first) + assert not second or not _denied(second) + ledger = tmp_path / "tmp" / "grimoire-priorart" / "s-gate.rules.ids" + assert ledger.read_text().split("\t")[0].strip() == "9" + + # ── the project fence ──────────────────────────────────────────────────── HOME_URL = "https://forge.example/team/home.git" diff --git a/tests/test_moment_delivery.py b/tests/test_moment_delivery.py index a24e6a9c..4c456bbb 100644 --- a/tests/test_moment_delivery.py +++ b/tests/test_moment_delivery.py @@ -30,7 +30,7 @@ from grimoire.services import moment_actions from grimoire.services import moment_delivery as md from grimoire.services import retrieval_pipeline as rp from grimoire.services import rule_usage, rulebooks -from tests.helpers import fake_rule, http_sink, need_tools +from tests.helpers import fake_rule, http_sink, need_tools, route_query_args # Bound before conftest's autouse stub replaces the module attribute. _REAL_DELIVER = md.deliver_for_act @@ -274,30 +274,6 @@ def test_the_hook_is_registered_on_every_tool(): assert any("grimoire_moment.sh" in c for c in entries.get("*", [])) -def test_the_hook_and_the_routes_agree_on_every_name(): - """Parity across the shell/Python seam: a renamed arg fails silently.""" - src = HOOK.read_text() - assert "/api/plugin/moment-tools" in src and "/api/plugin/moment" in src - assert "exclude_rule_ids" in src and "grimoire_held_query" in src - assert "grimoire_rules_live" in src and "grimoire_rules_append" in src - # The SHARED ledger, not one of its own. - assert '"${TMPDIR:-/tmp}/grimoire-priorart"' in src and ".rules.ids" in src - for field in (".tools", ".rule_ids", ".context", ".shape_keys"): - assert f"'{field}'" in src - assert "shapes_seen" in src and "grimoire_shapes_append" in src - - from grimoire.routes import plugin as routes - - route = inspect.getsource(routes.moment) - for name in ("exclude_rule_ids", "held_rule_ids", "tool_name", "tool_input", - "shapes_seen", "shape_keys"): - assert name in route - - -def test_the_hook_leaves_grimoires_own_tools_to_their_responses(): - assert "mcp__*grimoire*__*) exit 0" in HOOK.read_text() - - def test_the_hook_holds_only_behind_the_session_guard_and_refuses_only_on_enforce(): """Structural, and able to fail: every deny the hook emits is either the `enforce` branch or sits behind `grimoire_checkpoint_allowed`. A hold @@ -355,6 +331,40 @@ def test_an_unlisted_tool_never_leaves_the_machine(tmp_path): assert [e["_path"] for e in seen] == ["/api/plugin/moment-tools"] +def test_grimoires_own_tools_are_left_to_their_responses(tmp_path): + """A Grimoire tool attaches its own moment rules in its response, so the + hook never asks about one, even when the tool is listed.""" + with http_sink(by_path={"/api/plugin/moment-tools": b'{"tools":["update_task"]}'}) \ + as (port, seen): + assert _hook(tmp_path, port, tool="mcp__plugin_grimoire_grimoire__update_task") == "" + assert [e["_path"] for e in seen] == ["/api/plugin/moment-tools"] + + +def test_the_route_reads_every_name_the_hook_sends(tmp_path): + """Parity across the shell/Python seam, a renamed key fails silently. The + hook runs with the shared rule ledger, the opened ledger and the shape + ledger all holding something; every query key it sends must be one the + route reads, and the body carries the event the route reads.""" + from grimoire.routes import plugin as routes + + state = tmp_path / "grimoire-priorart" + state.mkdir() + (state / "s-moment.opened.ids").write_text("7\n") + replies = dict(TOOLS) + replies["/api/plugin/moment"] = json.dumps( + {"context": "a rule", "rule_ids": [5], "moments": ["work.deliver"], + "shape_keys": ["asks"]}).encode() + with http_sink(by_path=replies) as (port, seen): + _hook(tmp_path, port) + _hook(tmp_path, port) + last = [e for e in seen if e["_path"] == "/api/plugin/moment"][-1] + sent = {k for k in last if not k.startswith("_")} + assert {"exclude_rule_ids", "held_rule_ids", "shapes_seen"} <= sent, sent + read = route_query_args(routes.moment, routes._project_scope) + assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}" + assert {"tool_name", "tool_input"} <= set(json.loads(last["_body"])) + + def test_an_install_with_nothing_mounted_sends_one_request_per_window(tmp_path): with http_sink(by_path={"/api/plugin/moment-tools": b'{"tools":[]}'}) as (port, seen): for _ in range(3): diff --git a/tests/test_pre_act_checkpoint.py b/tests/test_pre_act_checkpoint.py index 76199d89..e6cd01be 100644 --- a/tests/test_pre_act_checkpoint.py +++ b/tests/test_pre_act_checkpoint.py @@ -49,7 +49,6 @@ ROOT = Path(__file__).resolve().parents[1] HOOKS = ROOT / "plugin" / "hooks" DEFS = HOOKS / "grimoire_defs.sh" ACTION_HOOK = HOOKS / "grimoire_tool_rules.sh" -WRITE_HOOK = HOOKS / "grimoire_prior_art.sh" WHERE = "this Bash call" TRIGGER = "about to assert in a commit message what CI said" @@ -255,60 +254,5 @@ def test_the_deny_envelope_is_valid_json_carrying_the_reason(): # ── The boundary that is a recorded decision ────────────────────────────── -def test_only_the_action_hook_can_hold_an_act(): - """THE GUARD ON THE RECORDED DECISION, and the reason it is here rather - than left to memory. - - `grimoire_prior_art.sh` runs before every Write and Edit and has never been - able to stop one. That is a standing decision — a recall aid may not stand - in the way of the work — and `test_hook_never_returns_a_permission_ - decision` in test_write_path_trigger.py holds the other half of it. - - This milestone has a live argument for extending the checkpoint to writes: - three of its seven misses were file edits and none of them are reachable - from the command side. That argument is exactly why this assertion exists. - A feature with a good reason to spread is the kind that spreads without - anyone deciding to, and the decision here is the operator's to revisit. - """ - assert "grimoire_json_deny" in ACTION_HOOK.read_text() - write_code = [ - ln for ln in WRITE_HOOK.read_text().splitlines() - if not ln.lstrip().startswith("#") - ] - assert not any("grimoire_json_deny" in ln for ln in write_code) - assert not any("permissionDecision" in ln for ln in write_code) - - -def test_the_action_hook_caps_every_hold_it_emits(): - """Structural, and able to fail: the deny and the ledger call - must appear together. A deny emitted outside the guard is a session that - can be held by the same rule on every command, which is the one outcome - both guards exist to prevent.""" - text = ACTION_HOOK.read_text() - code = [ln for ln in text.splitlines() if not ln.lstrip().startswith("#")] - denies = [i for i, ln in enumerate(code) if "grimoire_json_deny" in ln] - assert denies, "the action arm no longer emits a hold at all" - for i in denies: - window = "\n".join(code[max(0, i - 6):i]) - assert "grimoire_checkpoint_allowed" in window, ( - "a hold is emitted without passing the per-rule and per-session " - "guards first" - ) - - -def test_the_action_hook_records_what_was_surfaced_whichever_way_it_renders(): - """The ledger append sits BEFORE the checkpoint branch. What the server - chose to surface happened whichever way this hook then renders it, and - doing the bookkeeping inside one branch is how the two arms' ledgers came - to disagree once already.""" - code = [ - ln for ln in ACTION_HOOK.read_text().splitlines() - if not ln.lstrip().startswith("#") - ] - append = next(i for i, ln in enumerate(code) if "grimoire_rules_append" in ln) - deny = next(i for i, ln in enumerate(code) if "grimoire_json_deny" in ln) - assert append < deny - - def test_the_action_hook_is_still_shell_valid(): subprocess.run(["bash", "-n", str(ACTION_HOOK)], check=True) diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index a321e153..0f3b70b3 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -14,7 +14,7 @@ from pathlib import Path from unittest.mock import AsyncMock, MagicMock, patch import pytest -from tests.helpers import fake_note, http_sink, writepath_cfg +from tests.helpers import fake_note, http_sink, route_query_args, writepath_cfg @contextlib.contextmanager @@ -936,22 +936,6 @@ def test_prior_art_line_takes_a_search_hit_whose_snippet_is_its_excerpt(): # --- the route between them -------------------------------------------------- -def _route_args(*fns) -> set[str]: - """Every query key the given route functions read, from their AST.""" - import ast - import inspect - import textwrap - - keys = set() - for fn in fns: - for node in ast.walk(ast.parse(textwrap.dedent(inspect.getsource(fn)))): - if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) - and node.func.attr == "get" and ast.unparse(node.func.value) == "request.args" - and node.args and isinstance(node.args[0], ast.Constant)): - keys.add(node.args[0].value) - return keys - - def test_route_reads_every_arg_the_hook_sends(tmp_path): """The hook's query string and the route's reader are one contract, and the hook is the only caller, so a rename on either side is silent. The @@ -983,7 +967,7 @@ def test_route_reads_every_arg_the_hook_sends(tmp_path): # Every ledger the hook keeps went out, so this run exercised the whole query. assert {"path", "code", "repo", "shapes", "exclude_ids", "exclude_sync_ids", "exclude_rule_ids", "exclude_derive", "held_rule_ids", "seen_ruling_systems"} <= sent, sent - read = _route_args(routes.write_path_prior_art, routes._project_scope) + read = route_query_args(routes.write_path_prior_art, routes._project_scope) assert sent - {"session_id"} <= read, f"the route ignores {sorted(sent - read)}" # project_id is the other scope key the hook can send (from a project marker). assert "project_id" in read @@ -1018,11 +1002,20 @@ def test_hook_is_registered_for_write_and_edit(): def test_hook_never_returns_a_permission_decision(): """The load-bearing property: this hook informs a write, it cannot stop one. A permissionDecision of deny/ask would put a recall aid in the way of the - operator's work.""" + operator's work. + + It is a standing decision: a recall aid may not stand in the way of the + work, even where a stop would catch a miss. The command-side checkpoint + (grimoire_tool_rules.sh) is the only hook that holds an act, and + extending it to writes is the operator's call to make. + """ src = HOOK.read_text() assert "additionalContext" in src code_lines = [ln for ln in src.splitlines() if not ln.lstrip().startswith("#")] assert not any("permissionDecision" in ln for ln in code_lines) + # The shared helper that emits a deny, too: a call to it carries no + # permissionDecision text in this file. + assert not any("grimoire_json_deny" in ln for ln in code_lines) def test_hook_is_executable_and_shell_valid(): -- 2.54.0 From 84847cea0ebeee1f4c33a87aa9e533bea2a2e0e0 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:29:56 -0500 Subject: [PATCH 14/27] test(8249): DELIBERATE BREAK, Grimoire tools asked about, shapes_seen renamed, checkpoint uncapped Reverted by the next commit. CI must go red on test_grimoires_own_tools_are_left_to_their_responses, test_the_route_reads_every_name_the_hook_sends and test_a_checkpoint_holds_a_rule_once_and_books_it_as_surfaced_either_way. Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_moment.sh | 4 ++-- plugin/hooks/grimoire_tool_rules.sh | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/hooks/grimoire_moment.sh b/plugin/hooks/grimoire_moment.sh index ace88987..8e54576a 100644 --- a/plugin/hooks/grimoire_moment.sh +++ b/plugin/hooks/grimoire_moment.sh @@ -87,7 +87,7 @@ if [ "$now" -gt 0 ] && [ "$tool_key" != "get_rule" ]; then fi case "$tool_name" in - mcp__*grimoire*__*) exit 0 ;; + # DELIBERATE BREAK (#8249): Grimoire tools are asked about too esac # ── Which tools can reach a mounted rule: cached, first line a timestamp ── @@ -128,7 +128,7 @@ ledger_q="${ledger_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")" # full comes back as its reminder. shapefile=$(grimoire_shapes_file "$safe_sid") shapes_seen=$(grimoire_shapes_seen "$shapefile") -[ -n "$shapes_seen" ] && ledger_q="${ledger_q}&shapes_seen=${shapes_seen}" +[ -n "$shapes_seen" ] && ledger_q="${ledger_q}&shape_seen=${shapes_seen}" # The event whole, since which field a mapping matches is the mapping's # business. A write of a very large file is reduced to its name: the moments a diff --git a/plugin/hooks/grimoire_tool_rules.sh b/plugin/hooks/grimoire_tool_rules.sh index d0fd1460..419a2afe 100644 --- a/plugin/hooks/grimoire_tool_rules.sh +++ b/plugin/hooks/grimoire_tool_rules.sh @@ -161,7 +161,7 @@ cp_reason=$(grimoire_json_pick "$body_flat" '.checkpoint.reason') if [ -n "$cp_rule" ] && [ -n "$cp_reason" ] && [ -n "$session_id" ]; then stops="$state_dir/${safe_sid}.checkpoint.ids" call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id') - if grimoire_checkpoint_allowed "$stops" "$cp_rule"; then + if true; then # DELIBERATE BREAK (#8249): no per-rule cap grimoire_json_deny PreToolUse "$cp_reason" grimoire_gate_report "$session_id" checkpoint stopped "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id" exit 0 -- 2.54.0 From af30f46bee65213cfd3b5f773a3d8d436253fa63 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:32:53 -0500 Subject: [PATCH 15/27] Revert the deliberate break: Grimoire tools left alone, shapes_seen named, checkpoint capped Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_moment.sh | 4 ++-- plugin/hooks/grimoire_tool_rules.sh | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/hooks/grimoire_moment.sh b/plugin/hooks/grimoire_moment.sh index 8e54576a..ace88987 100644 --- a/plugin/hooks/grimoire_moment.sh +++ b/plugin/hooks/grimoire_moment.sh @@ -87,7 +87,7 @@ if [ "$now" -gt 0 ] && [ "$tool_key" != "get_rule" ]; then fi case "$tool_name" in - # DELIBERATE BREAK (#8249): Grimoire tools are asked about too + mcp__*grimoire*__*) exit 0 ;; esac # ── Which tools can reach a mounted rule: cached, first line a timestamp ── @@ -128,7 +128,7 @@ ledger_q="${ledger_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")" # full comes back as its reminder. shapefile=$(grimoire_shapes_file "$safe_sid") shapes_seen=$(grimoire_shapes_seen "$shapefile") -[ -n "$shapes_seen" ] && ledger_q="${ledger_q}&shape_seen=${shapes_seen}" +[ -n "$shapes_seen" ] && ledger_q="${ledger_q}&shapes_seen=${shapes_seen}" # The event whole, since which field a mapping matches is the mapping's # business. A write of a very large file is reduced to its name: the moments a diff --git a/plugin/hooks/grimoire_tool_rules.sh b/plugin/hooks/grimoire_tool_rules.sh index 419a2afe..d0fd1460 100644 --- a/plugin/hooks/grimoire_tool_rules.sh +++ b/plugin/hooks/grimoire_tool_rules.sh @@ -161,7 +161,7 @@ cp_reason=$(grimoire_json_pick "$body_flat" '.checkpoint.reason') if [ -n "$cp_rule" ] && [ -n "$cp_reason" ] && [ -n "$session_id" ]; then stops="$state_dir/${safe_sid}.checkpoint.ids" call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id') - if true; then # DELIBERATE BREAK (#8249): no per-rule cap + if grimoire_checkpoint_allowed "$stops" "$cp_rule"; then grimoire_json_deny PreToolUse "$cp_reason" grimoire_gate_report "$session_id" checkpoint stopped "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id" exit 0 -- 2.54.0 From 06815342579840a8f0062e19112d6c2b7cb36dee Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:37:16 -0500 Subject: [PATCH 16/27] test(8249): a Grimoire tool sends no ask at all, not even for the tool list The hook leaves a Grimoire tool before it reads the cached tool list, so the right check is that no /moment ask is made; the test expected the list fetch. Caught by CI on the reviewed tree (run 11237). Co-Authored-By: Claude Opus 5.5 --- tests/test_moment_delivery.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_moment_delivery.py b/tests/test_moment_delivery.py index 4c456bbb..fa5884e3 100644 --- a/tests/test_moment_delivery.py +++ b/tests/test_moment_delivery.py @@ -337,7 +337,7 @@ def test_grimoires_own_tools_are_left_to_their_responses(tmp_path): with http_sink(by_path={"/api/plugin/moment-tools": b'{"tools":["update_task"]}'}) \ as (port, seen): assert _hook(tmp_path, port, tool="mcp__plugin_grimoire_grimoire__update_task") == "" - assert [e["_path"] for e in seen] == ["/api/plugin/moment-tools"] + assert "/api/plugin/moment" not in [e["_path"] for e in seen] def test_the_route_reads_every_name_the_hook_sends(tmp_path): -- 2.54.0 From ea30e0bd75e34c2d01d5d2cabad1a91a7c7dac43 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:37:24 -0500 Subject: [PATCH 17/27] test(8249): prompt filter, shared rule ledger and reply-shape guards run the hooks - test_prompt_boundary_filter: the prompt hook runs on a client-written turn and sends nothing, and on a typed one and asks; was "the filter call sits above the curl line" in the source. - test_rule_usage_wiring: the write arm runs and is told it named rule 33, then the tool arm in the same session must send 33 as already named; was three string searches of each script for the ledger's path. - test_reply_shape_turn: the hook half of the shape-ledger contract is the runtime test already there; the remaining test checks the route half from the route's AST. - test_contract_around_the_change: its write-gate guard was a copy of test_hook_never_returns_a_permission_decision, which now checks the same two things. Co-Authored-By: Claude Opus 5.5 --- tests/test_contract_around_the_change.py | 14 --------- tests/test_prompt_boundary_filter.py | 28 +++++++++++------ tests/test_reply_shape_turn.py | 14 ++++----- tests/test_rule_usage_wiring.py | 38 +++++++++++++++++------- 4 files changed, 54 insertions(+), 40 deletions(-) diff --git a/tests/test_contract_around_the_change.py b/tests/test_contract_around_the_change.py index bc223ec5..35343a08 100644 --- a/tests/test_contract_around_the_change.py +++ b/tests/test_contract_around_the_change.py @@ -214,20 +214,6 @@ def test_a_missing_old_text_says_nothing(repo): # ── The hook that carries it ────────────────────────────────────────────── -def test_the_write_hook_still_cannot_stop_a_write(): - """THE RECORDED DECISION THIS ARM MUST NOT ERODE. The operator's position - is that a recall aid may not stand in the way of a write, and this arm is - a nudge like the others — it names files, it does not gate. Asserted here - as well as in test_write_path_trigger.py because this is the change most - likely to tempt someone into making it a gate: it reports something that - may already be broken. - """ - code = [ln for ln in HOOK.read_text().splitlines() - if not ln.lstrip().startswith("#")] - assert not any("permissionDecision" in ln for ln in code) - assert not any("grimoire_json_deny" in ln for ln in code) - - def test_the_hook_asks_the_contract_question_first(): """Order is the strength of the claim: this arm says something may already be BROKEN, the local arm says a copy exists, the recorded arms say diff --git a/tests/test_prompt_boundary_filter.py b/tests/test_prompt_boundary_filter.py index 68aabf16..ee71cb9e 100644 --- a/tests/test_prompt_boundary_filter.py +++ b/tests/test_prompt_boundary_filter.py @@ -110,13 +110,23 @@ def test_the_filter_is_a_prefix_test_not_a_substring_test() -> None: assert not _skip("what is " + tag + "?") -def test_the_hook_consults_the_filter_before_spending_a_request() -> None: - """Placement, not merely presence. +@pytest.mark.parametrize("prompt,asks", [(SYNTHETIC[0], False), (REAL[0], True)], + ids=["client-written", "typed"]) +def test_the_hook_spends_no_request_on_a_client_written_turn(tmp_path, prompt, asks) -> None: + """Placement, not merely presence: the point is that no retrieval row is + logged for a turn nobody typed, so the hook must not reach the server at all.""" + import json - The guard is worthless below the `curl`: the point is that no row is - logged, so it has to sit ahead of the request that would log one. - """ - body = HOOK.read_text() - assert "grimoire_skip_prompt" in body, "the hook does not consult the filter" - assert body.index("grimoire_skip_prompt") < body.index("curl -fsS"), \ - "the filter runs after the request it exists to prevent" + from tests.helpers import http_sink, need_tools + + need_tools("bash", "curl", "awk") + with http_sink(by_path={}) as (port, seen): + out = subprocess.run( + ["bash", str(HOOK)], + input=json.dumps({"session_id": "s-filter", "cwd": str(tmp_path), "prompt": prompt}), + capture_output=True, text=True, timeout=30, + env={"PATH": os.environ["PATH"], "GRIMOIRE_URL": f"http://127.0.0.1:{port}", + "GRIMOIRE_TOKEN": "t", "TMPDIR": str(tmp_path), "HOME": str(tmp_path)}, + ) + assert out.returncode == 0, out.stderr + assert any(e["_path"] == "/api/plugin/retrieve" for e in seen) is asks diff --git a/tests/test_reply_shape_turn.py b/tests/test_reply_shape_turn.py index 5ba5df33..e3121333 100644 --- a/tests/test_reply_shape_turn.py +++ b/tests/test_reply_shape_turn.py @@ -131,12 +131,12 @@ def test_the_core_goes_whole_once_then_as_a_reminder_then_whole_after_a_compacti assert "Every reply" in json.loads(out)["hookSpecificOutput"]["additionalContext"] -def test_the_hook_and_the_route_agree_on_the_ledgers_names(): - """A contract across the seam: a renamed field fails silently.""" +def test_the_route_reads_the_shape_ledger_the_hook_sends_and_returns_its_keys(): + """A contract across the seam: a renamed field fails silently. The hook + half (it sends `shapes_seen` and keeps the `shape_keys` it is given) is + the runtime test above; this is the route half.""" from grimoire.routes import plugin as routes + from tests.helpers import route_query_args - hook = HOOK.read_text() - assert "shapes_seen" in hook and "'.shape_keys'" in hook - assert "grimoire_shapes_file" in hook and "grimoire_shapes_append" in hook - route = inspect.getsource(routes.autoinject_retrieve) - assert 'request.args.get("shapes_seen")' in route and '"shape_keys"' in route + assert "shapes_seen" in route_query_args(routes.autoinject_retrieve) + assert '"shape_keys"' in inspect.getsource(routes.autoinject_retrieve) diff --git a/tests/test_rule_usage_wiring.py b/tests/test_rule_usage_wiring.py index 0d0b4c3b..d3871ec5 100644 --- a/tests/test_rule_usage_wiring.py +++ b/tests/test_rule_usage_wiring.py @@ -670,21 +670,39 @@ async def test_a_long_command_is_bounded_before_it_reaches_the_ranker(): assert sent.startswith("git tag v1"), "the head of the command is the signal" -def test_the_two_pre_tool_arms_share_one_session_rule_ledger(): +def test_the_two_pre_tool_arms_share_one_session_rule_ledger(tmp_path): """The integration point most worth guarding. Two ledgers would mean a rule named by the write arm gets re-offered by the - tool arm — and the hint that fires most often is exactly the one that must - not repeat itself. Asserted on the FILENAME both scripts build, because - that is the shared thing; a copy of the path in each is how they drift. + tool arm, and the hint that fires most often is exactly the one that must + not repeat itself. So the write arm runs and is told it named rule 33; the + tool arm, next in the same session, must send rule 33 as already named. """ - prior = Path("plugin/hooks/grimoire_prior_art.sh").read_text() - tool = Path("plugin/hooks/grimoire_tool_rules.sh").read_text() + import json + import os + import subprocess - for src, name in ((prior, "grimoire_prior_art.sh"), (tool, "grimoire_tool_rules.sh")): - assert '"${TMPDIR:-/tmp}/grimoire-priorart"' in src, f"{name}: state dir moved" - assert '.rules.ids' in src, f"{name}: rules ledger filename moved" - assert "exclude_rule_ids" in src, f"{name}: does not send the exclusion" + from tests.helpers import http_sink, need_tools + + need_tools("bash", "curl", "awk") + hooks = Path("plugin/hooks") + replies = {"/api/plugin/prior-art": b'{"context":"> rule 33","note_ids":[],"rule_ids":[33]}', + "/api/plugin/tool-rules": b'{"context":"","rule_ids":[]}'} + with http_sink(by_path=replies) as (port, seen): + env = {"PATH": os.environ["PATH"], "GRIMOIRE_URL": f"http://127.0.0.1:{port}", + "GRIMOIRE_TOKEN": "t", "TMPDIR": str(tmp_path), "HOME": str(tmp_path)} + for script, event in ( + ("grimoire_prior_art.sh", {"tool_name": "Write", "tool_input": { + "file_path": str(tmp_path / "a.py"), "content": "def debounce(fn):\n return fn"}}), + ("grimoire_tool_rules.sh", {"tool_name": "Bash", "tool_input": {"command": "git push"}}), + ): + out = subprocess.run(["bash", str(hooks / script)], + input=json.dumps({"session_id": "s-shared", "cwd": str(tmp_path), + **event}), + capture_output=True, text=True, env=env, timeout=30) + assert out.returncode == 0, out.stderr + tool_ask = [e for e in seen if e["_path"] == "/api/plugin/tool-rules"] + assert tool_ask and tool_ask[0]["exclude_rule_ids"] == ["33"] def test_the_tool_arm_is_registered_on_bash(): -- 2.54.0 From 1c6c8742578221710dda3ee3e9223383bc67d825 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:41:39 -0500 Subject: [PATCH 18/27] test(8249): DELIBERATE BREAK, client turns retrieved, tool arm keeps its own rule ledger, route reads shape_seen Reverted by the next commit. CI must go red on test_the_hook_spends_no_request_on_a_client_written_turn[client-written], test_the_two_pre_tool_arms_share_one_session_rule_ledger and test_the_route_reads_the_shape_ledger_the_hook_sends_and_returns_its_keys. Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_autoinject.sh | 2 +- plugin/hooks/grimoire_tool_rules.sh | 2 +- src/grimoire/routes/plugin.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/hooks/grimoire_autoinject.sh b/plugin/hooks/grimoire_autoinject.sh index a4d98744..37bed7d9 100755 --- a/plugin/hooks/grimoire_autoinject.sh +++ b/plugin/hooks/grimoire_autoinject.sh @@ -60,7 +60,7 @@ transcript=$(grimoire_json_pick "$event_flat" '.transcript_path') # recorded against a notification inflates this surface's denominator and # seeds `near_misses` with demand nobody expressed. grimoire_skip_prompt carries # the reasoning. -grimoire_skip_prompt "$prompt" && exit 0 +: # DELIBERATE BREAK (#8249): client-written turns are retrieved against # Unconfigured install → silent (auto-inject is pure enrichment). grimoire_config || exit 0 diff --git a/plugin/hooks/grimoire_tool_rules.sh b/plugin/hooks/grimoire_tool_rules.sh index d0fd1460..cc1a35cf 100644 --- a/plugin/hooks/grimoire_tool_rules.sh +++ b/plugin/hooks/grimoire_tool_rules.sh @@ -94,7 +94,7 @@ rulingsfile="" rulings_q="" if [ -n "$session_id" ]; then safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_') - rulefile="$state_dir/${safe_sid}.rules.ids" + rulefile="$state_dir/${safe_sid}.toolrules.ids" # Ageing, not a flat read: an id named two hours ago is not one the # session is still holding. grimoire_rules_live carries the reasoning. rule_seen=$(grimoire_rules_live "$rulefile") diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 06913dcc..226a3ef9 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -218,7 +218,7 @@ async def autoinject_retrieve(): # The reply mounts go through the same rule ledger; a rule the prompt arm # just named is not quoted a second time by the turn's delivery. turn = await moment_delivery_svc.deliver_for_turn( - g.user.id, seen=reply_shapes_svc.parse_seen(request.args.get("shapes_seen")), + g.user.id, seen=reply_shapes_svc.parse_seen(request.args.get("shape_seen")), project_id=project_id, exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]), held=frozenset(held_rule_ids), -- 2.54.0 From 1d3d72d2d4b4dd40d55ea047bec4b1fcc519c211 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:44:33 -0500 Subject: [PATCH 19/27] Revert the deliberate break: client turns skipped, one shared rule ledger, route reads shapes_seen Co-Authored-By: Claude Opus 5.5 --- plugin/hooks/grimoire_autoinject.sh | 2 +- plugin/hooks/grimoire_tool_rules.sh | 2 +- src/grimoire/routes/plugin.py | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/plugin/hooks/grimoire_autoinject.sh b/plugin/hooks/grimoire_autoinject.sh index 37bed7d9..a4d98744 100755 --- a/plugin/hooks/grimoire_autoinject.sh +++ b/plugin/hooks/grimoire_autoinject.sh @@ -60,7 +60,7 @@ transcript=$(grimoire_json_pick "$event_flat" '.transcript_path') # recorded against a notification inflates this surface's denominator and # seeds `near_misses` with demand nobody expressed. grimoire_skip_prompt carries # the reasoning. -: # DELIBERATE BREAK (#8249): client-written turns are retrieved against +grimoire_skip_prompt "$prompt" && exit 0 # Unconfigured install → silent (auto-inject is pure enrichment). grimoire_config || exit 0 diff --git a/plugin/hooks/grimoire_tool_rules.sh b/plugin/hooks/grimoire_tool_rules.sh index cc1a35cf..d0fd1460 100644 --- a/plugin/hooks/grimoire_tool_rules.sh +++ b/plugin/hooks/grimoire_tool_rules.sh @@ -94,7 +94,7 @@ rulingsfile="" rulings_q="" if [ -n "$session_id" ]; then safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_') - rulefile="$state_dir/${safe_sid}.toolrules.ids" + rulefile="$state_dir/${safe_sid}.rules.ids" # Ageing, not a flat read: an id named two hours ago is not one the # session is still holding. grimoire_rules_live carries the reasoning. rule_seen=$(grimoire_rules_live "$rulefile") diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 226a3ef9..06913dcc 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -218,7 +218,7 @@ async def autoinject_retrieve(): # The reply mounts go through the same rule ledger; a rule the prompt arm # just named is not quoted a second time by the turn's delivery. turn = await moment_delivery_svc.deliver_for_turn( - g.user.id, seen=reply_shapes_svc.parse_seen(request.args.get("shape_seen")), + g.user.id, seen=reply_shapes_svc.parse_seen(request.args.get("shapes_seen")), project_id=project_id, exclude=frozenset(exclude_rule_ids) | frozenset(rules["rule_ids"]), held=frozenset(held_rule_ids), -- 2.54.0 From 094089e374e4185de5bf14aebf8942e4024a576f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 19:45:38 -0500 Subject: [PATCH 20/27] test(8249): area groups, first pass: one file folded in, three readout checks merged, two copies removed - test_mcp_tool_tasks_kind.py is folded into test_mcp_tool_tasks.py, the tool's own file: the two "kind passes through" cases are one table, the two list-filter cases one table; the minted_kind refusals move to the service's kind tests (test_services_notes_task_kind.py). - A fresh install reads as empty, not failed: three database tests each ran retrieval_summary on an empty install and checked one block (usage, judged, system_usage). One test now checks all three. - test_reply_shapes::test_the_tool_is_registered_as_a_read: everything it checked, test_moments::test_the_tools_are_registered_and_classified checks. - test_shape_ledger::test_classify_and_list_are_mounted_as_mcp_tools: every classified tool name must be a registered tool (test_mcp_auth::test_every_registered_tool_is_classified_exactly_once). Co-Authored-By: Claude Opus 5.5 --- tests/test_mcp_tool_tasks.py | 49 ++++++++++- tests/test_mcp_tool_tasks_kind.py | 99 ---------------------- tests/test_reply_shapes.py | 10 --- tests/test_retrieval_review.py | 9 -- tests/test_services_notes_task_kind.py | 22 +++++ tests/test_services_retrieval_telemetry.py | 7 ++ tests/test_shape_ledger.py | 8 -- tests/test_system_usage_readout.py | 12 --- 8 files changed, 77 insertions(+), 139 deletions(-) delete mode 100644 tests/test_mcp_tool_tasks_kind.py diff --git a/tests/test_mcp_tool_tasks.py b/tests/test_mcp_tool_tasks.py index f1a8e32e..8cc83ea5 100644 --- a/tests/test_mcp_tool_tasks.py +++ b/tests/test_mcp_tool_tasks.py @@ -8,7 +8,7 @@ from grimoire.mcp.tools.tasks import ( list_tasks, get_task, create_task, update_task, add_task_log, ) -from tests.helpers import fake_task +from tests.helpers import fake_note, fake_task pytestmark = pytest.mark.usefixtures("_bind_user") @@ -271,3 +271,50 @@ async def test_add_task_log_propagates_value_error_when_task_missing(): ): with pytest.raises(ValueError): await add_task_log(task_id=999, content="x") + + +# ── kind: the door passes it through, and "" leaves it alone ───────────── + +@pytest.mark.asyncio +@pytest.mark.parametrize("kind", ["issue", "spike"]) +async def test_create_task_passes_the_kind_through(kind): + """`spike` is the kind a failed rule-check asks for: time-boxed, and its + output is knowledge rather than a change, so filing one as `work` makes a + finished investigation look like an abandoned change.""" + mock = AsyncMock(return_value=fake_note(task_kind=kind)) + with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock): + await create_task(title="Can the runner be given a bash shell?", kind=kind) + assert mock.call_args.kwargs["task_kind"] == kind + + +@pytest.mark.asyncio +@pytest.mark.parametrize("given,sent", [({"kind": "issue"}, "issue"), ({}, None)]) +async def test_list_tasks_filters_by_kind_only_when_asked(given, sent): + mock = AsyncMock(return_value=([], 0)) + with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock): + await list_tasks(**given) + assert mock.call_args.kwargs["task_kind"] == sent + + +@pytest.mark.asyncio +async def test_update_task_can_re_file_a_kind(): + """A task's kind must be CORRECTABLE, not write-once. + + What a piece of work turns out to be is often clear only once it is under + way. Without a `kind` parameter on `update_task`, and with a REST route that + drops the field the editor sends, the save reports success and reverts on + reload. + """ + mock = AsyncMock(return_value=fake_note(task_kind="spike")) + with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock): + await update_task(task_id=1, kind="spike") + assert mock.call_args.kwargs["task_kind"] == "spike" + + +@pytest.mark.asyncio +async def test_update_task_leaves_kind_alone_when_not_given(): + """"" means leave unchanged, as it does for every other field here.""" + mock = AsyncMock(return_value=fake_note()) + with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock): + await update_task(task_id=1, title="renamed") + assert "task_kind" not in mock.call_args.kwargs diff --git a/tests/test_mcp_tool_tasks_kind.py b/tests/test_mcp_tool_tasks_kind.py deleted file mode 100644 index 3ffa04af..00000000 --- a/tests/test_mcp_tool_tasks_kind.py +++ /dev/null @@ -1,99 +0,0 @@ -from unittest.mock import AsyncMock, patch - -import pytest -from tests.helpers import fake_note - - -pytestmark = pytest.mark.usefixtures("_bind_user") - - -@pytest.mark.asyncio -async def test_create_task_passes_kind(): - # kind=plan is retired (plans are milestones); 'issue' exercises passthrough. - mock = AsyncMock(return_value=fake_note(task_kind="issue")) - with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock): - from grimoire.mcp.tools.tasks import create_task - await create_task(title="P", kind="issue") - assert mock.call_args.kwargs["task_kind"] == "issue" - - -@pytest.mark.asyncio -async def test_list_tasks_passes_kind_filter(): - mock = AsyncMock(return_value=([], 0)) - with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock): - from grimoire.mcp.tools.tasks import list_tasks - await list_tasks(kind="plan") - assert mock.call_args.kwargs["task_kind"] == "plan" - - -@pytest.mark.asyncio -async def test_list_tasks_kind_empty_means_no_filter(): - mock = AsyncMock(return_value=([], 0)) - with patch("grimoire.mcp.tools.tasks.notes_svc.list_notes", mock): - from grimoire.mcp.tools.tasks import list_tasks - await list_tasks() - assert mock.call_args.kwargs["task_kind"] is None - - -@pytest.mark.asyncio -async def test_create_task_passes_spike(): - """The kind a failed rule-check asks for. - - Time-boxed, and its output is knowledge rather than a change — filing one - as `work` makes a finished investigation look like an abandoned change. - """ - mock = AsyncMock(return_value=fake_note(task_kind="spike")) - with patch("grimoire.mcp.tools.tasks.notes_svc.create_note", mock): - from grimoire.mcp.tools.tasks import create_task - await create_task(title="Can the runner be given a bash shell?", kind="spike") - assert mock.call_args.kwargs["task_kind"] == "spike" - - -@pytest.mark.asyncio -async def test_update_task_can_re_file_a_kind(): - """A task's kind must be CORRECTABLE, not write-once. - - What a piece of work turns out to be is often clear only once it is under - way. Without a `kind` parameter on `update_task`, and with a REST route that - drops the field the editor sends, the save reports success and reverts on - reload. - """ - mock = AsyncMock(return_value=fake_note(task_kind="spike")) - with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock): - from grimoire.mcp.tools.tasks import update_task - await update_task(task_id=1, kind="spike") - assert mock.call_args.kwargs["task_kind"] == "spike" - - -@pytest.mark.asyncio -async def test_update_task_leaves_kind_alone_when_not_given(): - """"" means leave unchanged, as it does for every other field here.""" - mock = AsyncMock(return_value=fake_note()) - with patch("grimoire.mcp.tools.tasks.notes_svc.update_note", mock): - from grimoire.mcp.tools.tasks import update_task - await update_task(task_id=1, title="renamed") - assert "task_kind" not in mock.call_args.kwargs - - -@pytest.mark.asyncio -async def test_minting_a_plan_is_refused_at_both_doors(): - """`plan` is a valid stored value and NOT a mintable one. - - Historical plan-tasks carry it and must stay writable, so the column - keeps accepting it — but plans became milestones in 0066, so no door - hands out a new one. The error names start_planning rather than just - refusing, because a caller reaching for kind='plan' wants a plan. - """ - from grimoire.services.notes import minted_kind - - with pytest.raises(ValueError, match="start_planning"): - minted_kind("plan") - - -@pytest.mark.asyncio -async def test_an_unknown_kind_raises_rather_than_defaulting(): - """A silently-corrected kind is the defect this whole fix exists to end.""" - from grimoire.services.notes import minted_kind - - with pytest.raises(ValueError, match="kind must be one of"): - minted_kind("investigation") diff --git a/tests/test_reply_shapes.py b/tests/test_reply_shapes.py index 52578b45..3e65f776 100644 --- a/tests/test_reply_shapes.py +++ b/tests/test_reply_shapes.py @@ -119,16 +119,6 @@ async def test_the_tool_returns_the_catalog(): assert await tool.list_reply_shapes() == reply_shapes.catalog() -def test_the_tool_is_registered_as_a_read(): - from grimoire.mcp.server import _READ_ONLY_TOOLS - from grimoire.mcp.tools import moments as tool - - mcp = FakeMCP() - tool.register(mcp) - assert "list_reply_shapes" in mcp.names - assert "list_reply_shapes" in _READ_ONLY_TOOLS - - def test_both_doors_read_one_catalog(): """Parity: the session and the Settings view cannot show different defaults.""" diff --git a/tests/test_retrieval_review.py b/tests/test_retrieval_review.py index ce4501a6..0648a6c4 100644 --- a/tests/test_retrieval_review.py +++ b/tests/test_retrieval_review.py @@ -381,12 +381,3 @@ async def test_verdicts_land_replace_and_read_back_by_rank(logged_calls): assert [r["rank"] for r in ai["by_rank"]] == [1, 4] # Related and left closed: the number an open rate could never show. assert ai["on_point_unopened"] == 1 - - -@pytest.mark.integration -@pytest.mark.asyncio -@pytest.mark.usefixtures("_dispose_engine") -async def test_a_fresh_install_reads_an_empty_judged_block_not_a_failure(): - from grimoire.services.retrieval_telemetry import retrieval_summary - - assert (await retrieval_summary(990041, days=30))["judged"] == {} diff --git a/tests/test_services_notes_task_kind.py b/tests/test_services_notes_task_kind.py index 4c9de31a..999adb2a 100644 --- a/tests/test_services_notes_task_kind.py +++ b/tests/test_services_notes_task_kind.py @@ -21,3 +21,25 @@ 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" + + +def test_minting_a_plan_is_refused_at_both_doors(): + """`plan` is a valid stored value and NOT a mintable one. + + Historical plan-tasks carry it and must stay writable, so the column + keeps accepting it — but plans became milestones in 0066, so no door + hands out a new one. The error names start_planning rather than just + refusing, because a caller reaching for kind='plan' wants a plan. + """ + from grimoire.services.notes import minted_kind + + with pytest.raises(ValueError, match="start_planning"): + minted_kind("plan") + + +def test_an_unknown_kind_raises_rather_than_defaulting(): + """A silently-corrected kind is the defect this whole fix exists to end.""" + from grimoire.services.notes import minted_kind + + with pytest.raises(ValueError, match="kind must be one of"): + minted_kind("investigation") diff --git a/tests/test_services_retrieval_telemetry.py b/tests/test_services_retrieval_telemetry.py index 5c434221..de6d36b7 100644 --- a/tests/test_services_retrieval_telemetry.py +++ b/tests/test_services_retrieval_telemetry.py @@ -341,6 +341,13 @@ async def test_retrieval_summary_is_empty_not_broken_for_a_fresh_install(_dispos # "no rows" / "read broke" distinction the rest of this readout keeps. assert out["usage"]["by_source"] == {} assert "by_source_failed" not in out["usage"] + # Every block reads as empty, never as a failure: the judged block, and + # the per-System usage block with no window to cover. + assert out["judged"] == {} + block = out["system_usage"] + assert "system_usage_failed" not in block + assert block["surfaced"] == 0 and block["by_system"] == [] + assert block["covers_window"] is None @pytest.mark.integration diff --git a/tests/test_shape_ledger.py b/tests/test_shape_ledger.py index 2632845d..2d544ea2 100644 --- a/tests/test_shape_ledger.py +++ b/tests/test_shape_ledger.py @@ -78,14 +78,6 @@ def test_batch_validation_names_the_failing_item(): assert v([{"path": "a", "symbol": "f", "status": "unclassified"}]) is None -def test_classify_and_list_are_mounted_as_mcp_tools(): - from grimoire.mcp.server import build_mcp_server - - mcp = build_mcp_server() - for name in ("classify_shapes", "list_shapes", "refresh_pattern_coverage"): - assert mcp._tool_manager.get_tool(name) is not None - - # --- step 5: the write-path feed's evidence tests (pure) --------------------- diff --git a/tests/test_system_usage_readout.py b/tests/test_system_usage_readout.py index 5cab7614..4cd80be5 100644 --- a/tests/test_system_usage_readout.py +++ b/tests/test_system_usage_readout.py @@ -146,15 +146,3 @@ async def test_the_telemetry_block_names_the_areas_and_offers_no_ratio(ruled_are # Rulings are delivered in full in the line; a ratio of opens would read # near zero on an arm that is working. assert "pull_through" not in block - - -@pytest.mark.integration -@pytest.mark.asyncio -@pytest.mark.usefixtures("_dispose_engine") -async def test_a_fresh_install_reads_zero_not_failed(): - from grimoire.services.retrieval_telemetry import retrieval_summary - - block = (await retrieval_summary(990031, days=30))["system_usage"] - assert "system_usage_failed" not in block - assert block["surfaced"] == 0 and block["by_system"] == [] - assert block["covers_window"] is None -- 2.54.0 From 4caa7bae4b60e6e76babab39fe561146e7e92b69 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 19:53:03 -0500 Subject: [PATCH 21/27] test(8249): the write-path sync-once check kept once, in the hook's own file test_ledger_references_not_silence::test_the_sync_class_still_shows_only_once checked a subset of test_write_path_trigger::test_sync_dedup_silences_a_sync_nudge_already_shown (sync_note_ids empty, the id absent from the context); the covering test also checks the semantic arm excludes it. Its reasoning (why the sync nudge is the one class shown only once) moves into the covering test's docstring. The helper's now-unused sync_exclude parameter goes with it. Co-Authored-By: Claude Opus 5.5 --- tests/test_ledger_references_not_silence.py | 18 +----------------- tests/test_write_path_trigger.py | 7 ++++++- 2 files changed, 7 insertions(+), 18 deletions(-) diff --git a/tests/test_ledger_references_not_silence.py b/tests/test_ledger_references_not_silence.py index 9cd482ac..51cbfa0b 100644 --- a/tests/test_ledger_references_not_silence.py +++ b/tests/test_ledger_references_not_silence.py @@ -166,7 +166,7 @@ async def test_the_header_explains_the_seen_marker(): # ── the write path ───────────────────────────────────────────────────────── -async def _write_path(hits, exclude_ids, *, here=(), rec=None, sync_exclude=()): +async def _write_path(hits, exclude_ids, *, here=(), rec=None): from grimoire.services import plugin_context as pc search = AsyncMock(return_value=hits) listing = AsyncMock(side_effect=[(list(here), len(here)), ([], 0)]) @@ -179,7 +179,6 @@ async def _write_path(hits, exclude_ids, *, here=(), rec=None, sync_exclude=()): out = await pc.build_write_path_hint( 1, "src/x.py", code=REAL_CODE, exclude_ids=list(exclude_ids), - exclude_sync_ids=list(sync_exclude), ) return out, search @@ -223,18 +222,3 @@ async def test_this_calls_own_menu_is_still_excluded_from_its_search(): _out, search = await _write_path( hits, [], here=[_snippet_item(7, "records this file")]) assert 7 in (search.call_args.kwargs.get("exclude_ids") or set()) - - -@pytest.mark.asyncio -async def test_the_sync_class_still_shows_only_once(): - """The deliberate exception, pinned so it reads as a decision. - - The sync nudge says "you are editing the file this record describes, so - updating it is part of the edit". Repeated every write to the same file it - is nagging, and unlike a reuse suggestion it is not a claim whose relevance - can return — it either got acted on or it did not. - """ - out, _ = await _write_path( - [], [], here=[_snippet_item(7, "records this file")], sync_exclude=[7]) - assert out["sync_note_ids"] == [] - assert "#7" not in out["context"] diff --git a/tests/test_write_path_trigger.py b/tests/test_write_path_trigger.py index 0f3b70b3..b71be78c 100644 --- a/tests/test_write_path_trigger.py +++ b/tests/test_write_path_trigger.py @@ -164,7 +164,12 @@ async def test_reuse_dedup_never_suppresses_the_sync_nudge(): async def test_sync_dedup_silences_a_sync_nudge_already_shown(): """Once the session has been told "snippet #12 records this file", every further edit of the same file stays quiet about it — on every arm: the - directory query and the semantic arm would both re-surface it otherwise.""" + directory query and the semantic arm would both re-surface it otherwise. + + This is the deliberate exception to "a repeat is shown again and marked". + Repeated on every write to the same file, the nudge is nagging, and unlike + a reuse suggestion it is not a claim whose relevance can return: it either + got acted on or it did not.""" from grimoire.services import plugin_context as pc async def _listing(uid, **kw): -- 2.54.0 From 5e4fc3dccff2d69986580b16ab4bbd0f3908c700 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 19:58:03 -0500 Subject: [PATCH 22/27] test(8249): DELIBERATE BREAK, plan minted, kind filter sent as "", empty judged block, sync ledger ignored --- src/grimoire/mcp/tools/tasks.py | 2 +- src/grimoire/services/notes.py | 1 + src/grimoire/services/plugin_context.py | 2 +- src/grimoire/services/retrieval_telemetry.py | 2 +- 4 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/grimoire/mcp/tools/tasks.py b/src/grimoire/mcp/tools/tasks.py index 7e16b90a..1258c079 100644 --- a/src/grimoire/mcp/tools/tasks.py +++ b/src/grimoire/mcp/tools/tasks.py @@ -139,7 +139,7 @@ async def list_tasks( is_task=True, status=status or None, project_id=project_id or None, - task_kind=kind or None, + task_kind=kind, # DELIBERATE BREAK limit=max(1, min(limit, 100)), offset=max(0, offset), ) diff --git a/src/grimoire/services/notes.py b/src/grimoire/services/notes.py index cffdc08a..6d07f6da 100644 --- a/src/grimoire/services/notes.py +++ b/src/grimoire/services/notes.py @@ -592,6 +592,7 @@ def minted_kind(kind: str) -> str: if kind in MINTABLE_KINDS: return kind if kind == "plan": + return kind # DELIBERATE BREAK raise ValueError( "kind='plan' is retired — plans are milestones. Call " "start_planning(project_id, title) to begin one. Existing " diff --git a/src/grimoire/services/plugin_context.py b/src/grimoire/services/plugin_context.py index 94be4dce..0d44f20c 100644 --- a/src/grimoire/services/plugin_context.py +++ b/src/grimoire/services/plugin_context.py @@ -1457,7 +1457,7 @@ async def build_write_path_hint( top_k = cfg["top_k"] excluded = set(exclude_ids or []) - sync_excluded = set(exclude_sync_ids or []) + sync_excluded = set() # DELIBERATE BREAK scope_project = project_id or None # --- the sync class, and arm 1 by place --- diff --git a/src/grimoire/services/retrieval_telemetry.py b/src/grimoire/services/retrieval_telemetry.py index ae7e8769..0a793ea7 100644 --- a/src/grimoire/services/retrieval_telemetry.py +++ b/src/grimoire/services/retrieval_telemetry.py @@ -1835,7 +1835,7 @@ async def retrieval_summary( # `_system_usage`'s reason — a failure flags itself rather than printing # an empty block, which reads as "nothing judged". try: - out["judged"] = await judged_block(user_id, since, until) + out["judged"] = (await judged_block(user_id, since, until)) or {"empty": True} # DELIBERATE BREAK except Exception: logger.warning("judged block read failed", exc_info=True) out["judged"] = {"judged_failed": True} -- 2.54.0 From fd1974bc91f7f0130eb7406778e2966155daca68 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 20:03:00 -0500 Subject: [PATCH 23/27] Revert the deliberate break: plan refused, kind filter None, empty judged block, sync ledger read --- src/grimoire/mcp/tools/tasks.py | 2 +- src/grimoire/services/notes.py | 1 - src/grimoire/services/plugin_context.py | 2 +- src/grimoire/services/retrieval_telemetry.py | 2 +- 4 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/grimoire/mcp/tools/tasks.py b/src/grimoire/mcp/tools/tasks.py index 1258c079..7e16b90a 100644 --- a/src/grimoire/mcp/tools/tasks.py +++ b/src/grimoire/mcp/tools/tasks.py @@ -139,7 +139,7 @@ async def list_tasks( is_task=True, status=status or None, project_id=project_id or None, - task_kind=kind, # DELIBERATE BREAK + task_kind=kind or None, limit=max(1, min(limit, 100)), offset=max(0, offset), ) diff --git a/src/grimoire/services/notes.py b/src/grimoire/services/notes.py index 6d07f6da..cffdc08a 100644 --- a/src/grimoire/services/notes.py +++ b/src/grimoire/services/notes.py @@ -592,7 +592,6 @@ def minted_kind(kind: str) -> str: if kind in MINTABLE_KINDS: return kind if kind == "plan": - return kind # DELIBERATE BREAK raise ValueError( "kind='plan' is retired — plans are milestones. Call " "start_planning(project_id, title) to begin one. Existing " diff --git a/src/grimoire/services/plugin_context.py b/src/grimoire/services/plugin_context.py index 0d44f20c..94be4dce 100644 --- a/src/grimoire/services/plugin_context.py +++ b/src/grimoire/services/plugin_context.py @@ -1457,7 +1457,7 @@ async def build_write_path_hint( top_k = cfg["top_k"] excluded = set(exclude_ids or []) - sync_excluded = set() # DELIBERATE BREAK + sync_excluded = set(exclude_sync_ids or []) scope_project = project_id or None # --- the sync class, and arm 1 by place --- diff --git a/src/grimoire/services/retrieval_telemetry.py b/src/grimoire/services/retrieval_telemetry.py index 0a793ea7..ae7e8769 100644 --- a/src/grimoire/services/retrieval_telemetry.py +++ b/src/grimoire/services/retrieval_telemetry.py @@ -1835,7 +1835,7 @@ async def retrieval_summary( # `_system_usage`'s reason — a failure flags itself rather than printing # an empty block, which reads as "nothing judged". try: - out["judged"] = (await judged_block(user_id, since, until)) or {"empty": True} # DELIBERATE BREAK + out["judged"] = await judged_block(user_id, since, until) except Exception: logger.warning("judged block read failed", exc_info=True) out["judged"] = {"judged_failed": True} -- 2.54.0 From 3ad7d93386264afd39b39f2e7de368a1f84f0fc5 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 10:01:12 -0500 Subject: [PATCH 24/27] test: the claims hook runner skips through need_tools rather than its own which-loop _run_hook in test_task_claims.py repeated the shutil.which -> pytest.skip guard that tests.helpers.need_tools exists to hold once. Co-Authored-By: Claude Opus 5.5 --- tests/test_task_claims.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/tests/test_task_claims.py b/tests/test_task_claims.py index d8c0e114..c8d5dec5 100644 --- a/tests/test_task_claims.py +++ b/tests/test_task_claims.py @@ -24,7 +24,7 @@ import pytest_asyncio from grimoire.services import notes as notes_svc from grimoire.services import task_claims as tc -from tests.helpers import ensure_user, http_sink +from tests.helpers import ensure_user, http_sink, need_tools ROOT = Path(__file__).resolve().parents[1] @@ -235,12 +235,9 @@ def test_a_dead_claim_on_finished_work_is_not_news(): def _run_hook(script, event, tmp_path, port): import os - import shutil import subprocess - for tool in ("bash", "curl"): - if shutil.which(tool) is None: - pytest.skip(f"hook runtime tool {tool!r} not installed") + need_tools("bash", "curl") env = {"PATH": os.environ["PATH"], "HOME": str(tmp_path), "TMPDIR": str(tmp_path), "GRIMOIRE_URL": f"http://127.0.0.1:{port}", "GRIMOIRE_TOKEN": "t", "CLAUDE_PROJECT_DIR": str(tmp_path)} -- 2.54.0 From a3c4cc5921224d4202b1b3f414ac4b8e34bc108b Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 10:03:46 -0500 Subject: [PATCH 25/27] fix(7716): the reply shape rides after the top two rule lines, so a compaction cannot push it out A compaction sweeps the rule ledger as well as the shape ledger. On the next prompt every rule the prompt arm reaches and every rule mounted on reply.report comes back as a first mention with its statement (about 750 characters each), and the route placed all of them ahead of the shape. Six fill the 4,500-character default budget, so the 2,343-character core was left out on exactly the turn it is meant to return in full. Seen in a real session: after 9 of 10 compactions the first prompt payload carried no reply shape at all. The prompt payload is now ordered as milestone 639 designed it: the first two rule lines, the reply shape, the remaining rule lines, the reply's lessons, the carried note, the records menu. Rules that do not fit stay off the ledger and arrive on a later call. The lesson-placement test now pins the lesson after the shape (a lesson binds nothing; the shape is what the reply is written to). New test: six full-length rule lines and the real core at the default budget; the shape is kept and the later rules wait. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/routes/plugin.py | 54 +++++++++++++++++++++------------- tests/test_reply_shape_turn.py | 47 +++++++++++++++++++++++++++-- 2 files changed, 79 insertions(+), 22 deletions(-) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 06913dcc..0daaa564 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -133,6 +133,10 @@ async def session_context(): # The longest carried note a prompt takes: the shape check's note names a # few definitions and the call that lists the rest. _CARRY_CHARS = 3000 +# How many rule lines ride ahead of the reply shape in the prompt payload: the +# default budget (hook_payload.DEFAULT_BUDGET) is sized for the core shape +# beside two full rule lines. +_LEAD_RULES = 2 @plugin_bp.get("/retrieve") @@ -183,12 +187,15 @@ async def autoinject_retrieve(): nobody has judged (/shape-check's `note`). Fitted after the reply shape, before the records. - ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the rules - this prompt reaches and those mounted on `reply.report`, then the turn's - reply shape, then the records menu. Every turn ends in a reply and this - is the last point before it is written, so the shape rides every call; - what does not fit is left off the ledgers and can arrive on a later call. - Shape keys sent in full come back as `shape_keys` for the ledger. + ONE PAYLOAD, IN ONE ORDER, UNDER ONE BUDGET (`hook_payload`): the first + two of the rule lines this prompt reaches and those mounted on + `reply.report`, then the turn's reply shape, then the remaining rule + lines, the reply's lessons, and the records menu. Every turn ends in a + reply and this is the last point before it is written, so the shape rides + every call and is placed where a full set of rule statements cannot push + it out; what does not fit is left off the ledgers and can arrive on a + later call. Shape keys sent in full come back as `shape_keys` for the + ledger. TWO ARMS, TWO SETS OF GATES. Rules ride the same hook and the same query but nothing else: the notes menu can be disabled, thresholded and top-k'd @@ -196,10 +203,10 @@ async def autoinject_retrieve(): here rather than inside either builder so neither one's early return can silently suppress the other. - Rules come FIRST in the payload. A rule or preference governing the answer - is more consequential than a menu of things that might be worth reading, - and a reader who stops after the first block should have stopped after - the right one. + The top rules come FIRST in the payload. A rule or preference governing + the answer is more consequential than a menu of things that might be + worth reading, and a reader who stops after the first block should have + stopped after the right one. """ q = (request.args.get("q") or "").strip() project_id, _repo, _unbound = await _project_scope() @@ -224,24 +231,31 @@ async def autoinject_retrieve(): held=frozenset(held_rule_ids), record=False, ) - # One payload, in the one order: the rules, then the reply shape, then - # what the last turn left unjudged, then the records menu, fitted to the - # budget. + # One payload, in the one order, fitted to the budget: the top rule lines, + # the reply shape, the remaining rule lines, the lessons recorded for the + # reply, what the last turn left unjudged, then the records menu. + # + # The shape sits after only the first _LEAD_RULES lines. A compaction + # sweeps the rule ledger as well as the shape ledger, so every rule then + # comes back as a first mention with its statement: six of those fill the + # default budget on their own, and with every rule ahead of it the shape + # was left out on exactly the turn it is meant to return in full. carry = (request.args.get("carry") or "").strip()[:_CARRY_CHARS] # Lessons recorded for the reply, once per session: booked in the record # ledger only if the fit keeps their line. record_deliveries_svc.record(g.user.id, turn.get("lesson_ids") or [], "lesson_situation") - turn_parts = ( - [*turn["rule_parts"], *turn.get("lesson_parts", []), *turn["shape_parts"]] - if "shape_parts" in turn - else [hook_payload_svc.Part(text=turn.get("context") or "", ids={ + prompt_rules = hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}) + if "shape_parts" in turn: + every_rule = [*prompt_rules, *turn["rule_parts"]] + lead = every_rule[:_LEAD_RULES] + ordered = [*lead, *turn["shape_parts"], *every_rule[_LEAD_RULES:], *turn.get("lesson_parts", [])] + else: + ordered = [*prompt_rules, hook_payload_svc.Part(text=turn.get("context") or "", ids={ hook_payload_svc.RULE: tuple(turn.get("rule_ids") or ()), hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()), })] - ) fitted = await hook_payload_svc.fit(g.user.id, [ - *hook_payload_svc.parts_of(rules, {hook_payload_svc.RULE: "shown_rule_ids"}), - *turn_parts, + *ordered, *([hook_payload_svc.Part(text=carry)] if carry else []), *hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}), ]) diff --git a/tests/test_reply_shape_turn.py b/tests/test_reply_shape_turn.py index e3121333..2ad85bee 100644 --- a/tests/test_reply_shape_turn.py +++ b/tests/test_reply_shape_turn.py @@ -57,7 +57,8 @@ async def test_the_turns_shape_follows_the_rules_and_its_key_comes_back(): assert body["rule_ids"] == [11, 173] -async def test_a_lesson_recorded_for_the_reply_sits_between_the_turns_rules_and_its_shape(): +async def test_a_lesson_recorded_for_the_reply_follows_its_shape(): + """A lesson binds nothing; the shape is what the reply is written to.""" from grimoire.services import hook_payload as hp body, _turn = await _retrieve({"q": "write the report"}, turn_value={ @@ -68,7 +69,49 @@ async def test_a_lesson_recorded_for_the_reply_sits_between_the_turns_rules_and_ "shape_parts": [hp.Part(text="CORE SHAPE", ids={hp.SHAPE: ("core",)})], }) ctx = body["context"] - assert ctx.index("TURN RULE") < ctx.index("LESSON LINE") < ctx.index("CORE SHAPE") < ctx.index("NOTES MENU") + assert ctx.index("TURN RULE") < ctx.index("CORE SHAPE") < ctx.index("LESSON LINE") < ctx.index("NOTES MENU") + + +async def test_the_full_shape_survives_a_turn_where_every_rule_is_a_first_mention(): + """After a compaction both ledgers are swept, so the prompt arm's rules and + those mounted on reply.report all return with their statements. Six of + them fill the default budget on their own; the shape still goes out in + full, and it is later rule lines that wait for a later call.""" + from grimoire.services import hook_payload as hp + + def long_rules(first_id, block_text): + lines = [f"{block_text} {first_id + i}: " + "x" * 700 for i in range(3)] + return hp.rule_parts(lines, [first_id + i for i in range(3)], block="rules") + + core = reply_shapes.core() + blocks, forms = reply_shapes.deliver([core], frozenset()) + from grimoire.routes import plugin as routes + + turn = AsyncMock(return_value={ + "context": "", "rule_ids": [201, 202, 203], "shape_forms": forms, + "rule_parts": long_rules(201, "TURN RULE"), + "shape_parts": [hp.Part(text=b, ids={hp.SHAPE: (k,)}) for b, k in zip(blocks, forms, strict=False)], + }) + app = Quart(__name__) + async with app.test_request_context("/api/plugin/retrieve", query_string={"q": "carry on"}): + g.user = SimpleNamespace(id=7) + with patch.object(routes.plugin_ctx_svc, "build_prompt_rule_hint", + AsyncMock(return_value={"context": "", "rule_ids": [101, 102, 103], + "parts": long_rules(101, "PROMPT RULE")})), \ + patch.object(routes.plugin_ctx_svc, "build_autoinject_hint", + AsyncMock(return_value={"context": "", "note_ids": []})), \ + patch.object(routes.moment_delivery_svc, "deliver_for_turn", turn), \ + patch.object(routes.hook_payload_svc, "payload_budget", + AsyncMock(return_value=hp.DEFAULT_BUDGET)): + body = await (await inspect.unwrap(routes.autoinject_retrieve)()).get_json() + + assert body["shape_keys"] == ["core"] + assert blocks[0] in body["context"] + assert len(body["context"]) <= hp.DEFAULT_BUDGET + # The top two rules still lead, and the rules that did not fit are left + # off the ledger so they can arrive on a later call. + assert body["context"].index("PROMPT RULE 101") < body["context"].index(blocks[0][:40]) + assert 101 in body["rule_ids"] and 203 not in body["rule_ids"] async def test_the_route_hands_the_ledger_and_the_rules_just_named_to_the_turn(): -- 2.54.0 From c921f284d857210ca6cd174fd53e58449b7ce42f Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 10:12:52 -0500 Subject: [PATCH 26/27] test(7716): DELIBERATE BREAK, every rule line ahead of the reply shape again --- src/grimoire/routes/plugin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 0daaa564..c168bc43 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -136,7 +136,7 @@ _CARRY_CHARS = 3000 # How many rule lines ride ahead of the reply shape in the prompt payload: the # default budget (hook_payload.DEFAULT_BUDGET) is sized for the core shape # beside two full rule lines. -_LEAD_RULES = 2 +_LEAD_RULES = 99 # DELIBERATE BREAK @plugin_bp.get("/retrieve") -- 2.54.0 From 9de0e805319a457ff732f3bfa61739f7b01c6298 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Wed, 2 Dec 2026 10:17:54 -0500 Subject: [PATCH 27/27] Revert the deliberate break: the reply shape after the top two rule lines --- src/grimoire/routes/plugin.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index c168bc43..0daaa564 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -136,7 +136,7 @@ _CARRY_CHARS = 3000 # How many rule lines ride ahead of the reply shape in the prompt payload: the # default budget (hook_payload.DEFAULT_BUDGET) is sized for the core shape # beside two full rule lines. -_LEAD_RULES = 99 # DELIBERATE BREAK +_LEAD_RULES = 2 @plugin_bp.get("/retrieve") -- 2.54.0