From 8fccaa0f3c3aeaafd292c62ddabfe2567e2a182b Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Tue, 1 Dec 2026 17:24:22 -0500 Subject: [PATCH] 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.