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 <noreply@anthropic.com>
This commit is contained in:
@@ -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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user