Merge pull request 'Reply shape survives a compaction (#7716); test review pass (#8249); detector fix (#8292)' (#239) from dev into main
CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 14s
CI & Build / TypeScript typecheck (push) Successful in 32s
CI & Build / Python tests (push) Successful in 2m19s
CI & Build / integration (push) Successful in 2m14s
CI & Build / Build & push image (push) Successful in 16s

This commit was merged in pull request #239.
This commit is contained in:
2026-12-02 13:09:44 -05:00
31 changed files with 537 additions and 552 deletions
+34 -20
View File
@@ -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"}),
])
+7 -1
View File
@@ -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:
+18
View File
@@ -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
-14
View File
@@ -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
+16
View File
@@ -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"
+1 -17
View File
@@ -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"]
+48 -1
View File
@@ -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
-99
View File
@@ -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")
+35 -25
View File
@@ -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 "/api/plugin/moment" not in [e["_path"] for e in seen]
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):
-56
View File
@@ -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)
+19 -9
View File
@@ -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
+52 -9
View File
@@ -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():
@@ -131,12 +174,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)
-10
View File
@@ -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."""
-9
View File
@@ -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"] == {}
-15
View File
@@ -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.
+3 -13
View File
@@ -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/<int:project_id>/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
-18
View File
@@ -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
-26
View File
@@ -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
@@ -86,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)."""
-11
View File
@@ -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
+11 -29
View File
@@ -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/<batch_id>/restore", "POST"),
("/api/trash/<batch_id>", "DELETE")):
assert route in rules, route
+12 -7
View File
@@ -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)
+28 -10
View File
@@ -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():
+71
View File
@@ -0,0 +1,71 @@
"""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": {},
"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",
},
}
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}"
+22
View File
@@ -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")
@@ -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
-8
View File
@@ -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) ---------------------
+6 -1
View File
@@ -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():
-12
View File
@@ -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
+30 -9
View File
@@ -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, need_tools
ROOT = Path(__file__).resolve().parents[1]
@@ -233,12 +233,30 @@ 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 subprocess
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)}
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 +278,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
+3
View File
@@ -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"]
+114 -123
View File
@@ -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
@@ -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):
@@ -936,41 +941,41 @@ 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."""
import inspect
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,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}"
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_sync_ids", "exclude_rule_ids",
"exclude_derive", "held_rule_ids", "seen_ruling_systems"} <= sent, sent
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
def test_route_resolves_repo_to_a_project_not_to_a_location_filter():
@@ -1002,11 +1007,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():
@@ -1014,21 +1028,37 @@ 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.
(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},
})
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():
@@ -1046,33 +1076,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
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
@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 _hook_runtime_env():
@@ -1416,20 +1431,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)."""
@@ -1627,6 +1628,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 —
@@ -1691,41 +1717,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.