"""Delivering mounted rules when their moment happens. The database is stubbed: the lookup's scoping is pinned against Postgres in tests/test_integration_rule_moments.py. These pin what is decided above it: - the line names the moment AND the act that reached it, so a misfire is visible where it lands and can be unmapped in the session; - a rule the session was already shown is cited, not repeated, and only the fresh ones are recorded, each with its moment; - every door fails open; - a rule set to enforce refuses the act every time, one set to hold holds it once for a read (never a write), and an `inform` rule only sits beside it; - the plugin is told which tools can reach anything, and nothing more; - every Grimoire tool the shipped mappings name carries the attach, and the hook and the route agree on every name between them. """ from __future__ import annotations import ast import inspect import json import os import subprocess from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock, MagicMock, patch from quart import Quart, g 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 # Bound before conftest's autouse stub replaces the module attribute. _REAL_DELIVER = md.deliver_for_act ROOT = Path(__file__).resolve().parents[1] HOOK = ROOT / "plugin" / "hooks" / "grimoire_moment.sh" def _rule(rid, title="Done means delivered and checked"): return fake_rule(id=rid, title=title, kind="rule", when_to_apply="about to say a piece of work is finished") def _moment(**kw): return rp.RuleMoment(user_id=1, query="", project_id=kw.pop("project_id", 2), **kw) PUSH = [{"moment": "work.deliver", "tool": "Bash", "match": "git push", "via": "default"}] # ── the arm ───────────────────────────────────────────────────────────── async def test_a_line_names_the_moment_and_the_act_that_reached_it(): lookup = AsyncMock(return_value=[(_rule(5), "work.deliver")]) surfaced = MagicMock() result = await rp.run_moment_arm( PUSH, _moment(), io=rp.MomentIO(lookup=lookup, record_rule_surfaced=surfaced), ) assert len(result.lines) == 1 assert "at work.deliver, reached by `git push`" in result.lines[0] assert "get_rule(5)" in result.lines[0] assert result.rule_ids == [5] lookup.assert_awaited_once_with(1, ["work.deliver"], 2) surfaced.assert_called_once() kw = surfaced.call_args.kwargs assert kw["source"] == rp.MOMENT_RULE_SOURCE assert kw["rule_ids"] == [5] assert kw["detail"] == {5: "work.deliver"} async def test_a_rule_already_shown_is_cited_after_the_fresh_ones_and_not_recorded(): lookup = AsyncMock(return_value=[(_rule(5), "work.deliver"), (_rule(9, "Other"), "work.deliver")]) surfaced = MagicMock() result = await rp.run_moment_arm( PUSH, _moment(exclude=frozenset({5})), io=rp.MomentIO(lookup=lookup, record_rule_surfaced=surfaced), ) assert result.shown_rule_ids == [9, 5] assert result.rule_ids == [9] assert result.lines[1].startswith("Also") assert surfaced.call_args.kwargs["rule_ids"] == [9] async def test_an_unbound_session_asks_for_global_rules_only(): lookup = AsyncMock(return_value=[]) await rp.run_moment_arm(PUSH, _moment(project_id=0), io=rp.MomentIO(lookup=lookup, record_rule_surfaced=MagicMock())) assert lookup.await_args.args[2] is None async def test_the_arm_fails_open(): broken = AsyncMock(side_effect=RuntimeError("db down")) result = await rp.run_moment_arm( PUSH, _moment(), io=rp.MomentIO(lookup=broken, record_rule_surfaced=MagicMock()), ) assert result.lines == [] and result.rule_ids == [] # A recorder that fails costs the telemetry, never the lines. result = await rp.run_moment_arm( PUSH, _moment(), io=rp.MomentIO(lookup=AsyncMock(return_value=[(_rule(5), "work.deliver")]), record_rule_surfaced=MagicMock(side_effect=RuntimeError("x"))), ) assert len(result.lines) == 1 async def test_nothing_reached_asks_nothing(): lookup = AsyncMock() result = await rp.run_moment_arm([], _moment(), io=rp.MomentIO(lookup=lookup, record_rule_surfaced=MagicMock())) assert result.lines == [] lookup.assert_not_awaited() # ── the act → the moments → the rules ─────────────────────────────────── def _stub_db(pairs): async def _moments_for(user_id, tool, tool_input): return moment_actions.resolve(tool, tool_input, []) return [ patch.object(md, "deliver_for_act", _REAL_DELIVER), patch.object(moment_actions, "moments_for", _moments_for), patch.object(rulebooks, "rules_on_moments", AsyncMock(return_value=pairs)), patch.object(rule_usage, "record_rule_surfaced", MagicMock()), ] async def _with(stack, coro_fn): for p in stack: p.start() try: return await coro_fn() finally: for p in reversed(stack): p.stop() async def test_a_task_closed_through_the_tool_carries_its_mounted_rules(): data = {"id": 40, "status": "done", "project_id": 2} out = await _with(_stub_db([(_rule(11), "work.finish")]), lambda: md.attach_moment_rules( 1, "update_task", {"status": "done", "project_id": 7}, data, )) assert out is data assert out["moment_rules"]["rule_ids"] == [11] assert "at work.finish, reached by `status=done`" in out["moment_rules"]["lines"][0] assert out["moment_rules"]["open_with"] == "get_rule(id)" async def test_the_records_project_wins_over_the_callers_argument(): lookup = AsyncMock(return_value=[]) stack = _stub_db([]) stack[2] = patch.object(rulebooks, "rules_on_moments", lookup) await _with(stack, lambda: md.attach_moment_rules( 1, "update_task", {"status": "done", "project_id": 7}, {"project_id": 2}, )) assert lookup.await_args.args == (1, ["work.finish"], 2) async def test_an_act_that_reaches_nothing_mounted_adds_nothing(): data = {"id": 40} out = await _with(_stub_db([]), lambda: md.attach_moment_rules( 1, "update_task", {"status": "todo"}, data, )) assert "moment_rules" not in out async def test_the_attach_fails_open_and_passes_other_payloads_through(): data = {"id": 1} with patch.object(md, "deliver_for_act", AsyncMock(side_effect=RuntimeError("x"))): assert await md.attach_moment_rules(1, "create_note", {}, data) == {"id": 1} marker = object() assert await md.attach_moment_rules(1, "start_planning", {}, marker) is marker # ── which tools the plugin needs to ask about ─────────────────────────── async def _reachable(mounted, mappings=()): with patch.object(rulebooks, "mounted_moments", AsyncMock(return_value=set(mounted))), \ patch.object(moment_actions, "list_mappings", AsyncMock(return_value=list(mappings))): return await md.reachable_tools(1) # The tools the shipped defaults map onto a moment that carries a default reply # shape: closing work, a structured question, opening a plan. SHAPED = ["askuserquestion", "create_milestone", "enterplanmode", "exitplanmode", "skill", "start_planning", "update_milestone", "update_task"] async def test_an_install_with_nothing_mounted_still_asks_about_the_shaped_moments(): """The reply shapes are product, so every install has them: the hook asks about the acts that bring one, and about nothing else.""" assert await _reachable(set()) == SHAPED async def test_only_the_tools_whose_moments_carry_a_mount_or_a_shape_are_listed(): assert await _reachable({"work.deliver"}) == sorted([*SHAPED, "bash"]) assert await _reachable({"work.finish"}) == SHAPED assert await _reachable({"skill.release"}) == SHAPED assert "bash" not in await _reachable(set()) async def test_the_skill_loader_counts_whenever_anything_is_mounted(): """A stored process declares its own moments, resolved only when it loads — so a mount on any moment may be reached by loading a procedure.""" assert "skill" in await _reachable({"work.debug"}) async def test_an_installs_own_mapping_and_removal_both_count(): own = SimpleNamespace(tool="mcp__deploy__ship", match="", moment="work.deliver", effect="add") assert "ship" in await _reachable({"work.deliver"}, [own]) gone = SimpleNamespace(tool="AskUserQuestion", match="", moment="reply.ask", effect="remove") assert "askuserquestion" in await _reachable({"reply.ask"}) assert "askuserquestion" not in await _reachable({"reply.ask"}, [gone]) # ── the plugin routes ─────────────────────────────────────────────────── async def test_the_route_reads_the_event_and_the_ledger(): from grimoire.routes import plugin as routes deliver = AsyncMock(return_value=(PUSH, rp.RuleResult( lines=["a line"], rule_ids=[5], shown_rule_ids=[5, 9], ))) app = Quart(__name__) event = {"session_id": "s", "tool_name": "Bash", "tool_input": {"command": "git push"}} async with app.test_request_context( "/api/plugin/moment", method="POST", json=event, query_string={"project_id": "3", "exclude_rule_ids": "9", "held_rule_ids": "4"}, ): g.user = SimpleNamespace(id=7) with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver): resp = await routes.moment.__wrapped__() body = await resp.get_json() assert body == {"context": "a line", "rule_ids": [5], "moments": ["work.deliver"], "shape_keys": [], "decision": {}} args, kw = deliver.await_args assert args == (7, "Bash", {"command": "git push"}) assert kw == {"project_id": 3, "exclude": frozenset({9}), "held": frozenset({4})} async def test_the_route_answers_an_empty_event_with_nothing(): from grimoire.routes import plugin as routes app = Quart(__name__) async with app.test_request_context("/api/plugin/moment", method="POST", json={}): g.user = SimpleNamespace(id=7) resp = await routes.moment.__wrapped__() assert await resp.get_json() == {"context": "", "rule_ids": [], "moments": [], "shape_keys": [], "decision": {}} def test_both_routes_are_on_the_app(): from grimoire.app import create_app rules = {str(r.rule) for r in create_app().url_map.iter_rules()} assert {"/api/plugin/moment", "/api/plugin/moment-tools"} <= rules # ── the hook ──────────────────────────────────────────────────────────── def test_the_hook_is_registered_on_every_tool(): manifest = json.loads((ROOT / "plugin" / "hooks" / "hooks.json").read_text()) entries = {m.get("matcher"): [h["command"] for h in m["hooks"]] for m in manifest["hooks"]["PreToolUse"]} 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 emitted outside the guard is a session the same rule can stop on every call.""" code = [ln for ln in HOOK.read_text().splitlines() if not ln.lstrip().startswith("#")] denies = [i for i, ln in enumerate(code) if "grimoire_json_deny" in ln] assert len(denies) == 2, "one deny for enforce, one for hold" enforce, hold = denies assert "enforce)" in "\n".join(code[max(0, enforce - 3):enforce]) assert "grimoire_checkpoint_allowed" in "\n".join(code[max(0, hold - 4):hold]) assert "permissionDecision" not in "\n".join(code), "decisions go through grimoire_json_deny" def _hook(tmp_path, port, tool="Bash", command="git push origin dev", session="s-moment"): need_tools("bash", "curl", "awk") 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)} out = subprocess.run( ["bash", str(HOOK)], input=json.dumps({"session_id": session, "cwd": str(tmp_path), "tool_name": tool, "tool_input": {"command": command}}), capture_output=True, text=True, env=env, timeout=30, ) assert out.returncode == 0, out.stderr return out.stdout TOOLS = {"/api/plugin/moment-tools": b'{"tools":["bash"]}'} def test_a_listed_tool_is_asked_about_and_its_rules_injected(tmp_path): replies = dict(TOOLS) replies["/api/plugin/moment"] = json.dumps( {"context": "Standing rule that may apply at work.deliver", "rule_ids": [5], "moments": ["work.deliver"]}).encode() with http_sink(by_path=replies) as (port, seen): out = _hook(tmp_path, port) # The list is read once per window, not once per call. _hook(tmp_path, port) paths = [e["_path"] for e in seen] assert paths == ["/api/plugin/moment-tools", "/api/plugin/moment", "/api/plugin/moment"] sent = json.loads(seen[1]["_body"]) assert sent["tool_input"] == {"command": "git push origin dev"} # The first call's fresh rule is on the shared ledger for the second. assert seen[2]["exclude_rule_ids"] == ["5"] ctx = json.loads(out)["hookSpecificOutput"]["additionalContext"] assert "work.deliver" in ctx def test_an_unlisted_tool_never_leaves_the_machine(tmp_path): with http_sink(by_path=TOOLS) as (port, seen): assert _hook(tmp_path, port, tool="Read") == "" assert _hook(tmp_path, port, tool="mcp__plugin_grimoire_grimoire__update_task") == "" assert [e["_path"] for e in seen] == ["/api/plugin/moment-tools"] def test_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): assert _hook(tmp_path, port) == "" assert len(seen) == 1 # ── the MCP door: every shipped Grimoire action carries the attach ──────── def _attached_names(path: Path) -> dict[str, set[str]]: """{function name: {tool names passed to attach_moment_rules in it}}.""" out: dict[str, set[str]] = {} for node in ast.parse(path.read_text()).body: if not isinstance(node, ast.AsyncFunctionDef): continue for call in ast.walk(node): func = call.func if isinstance(call, ast.Call) else None name = (func.id if isinstance(func, ast.Name) else func.attr if isinstance(func, ast.Attribute) else "") if (name == "attach_moment_rules" and len(call.args) > 1 and isinstance(call.args[1], ast.Constant)): out.setdefault(node.name, set()).add(call.args[1].value) return out def test_every_grimoire_tool_the_defaults_name_attaches_its_moment_rules(): tools_dir = ROOT / "src" / "grimoire" / "mcp" / "tools" defined: dict[str, dict[str, set[str]]] = {} grimoire_tools: set[str] = set() for path in tools_dir.glob("*.py"): tree = ast.parse(path.read_text()) grimoire_tools |= {n.name for n in tree.body if isinstance(n, ast.AsyncFunctionDef)} defined[path.name] = _attached_names(path) shipped = {a.tool for a in moment_actions.DEFAULT_ACTIONS} & grimoire_tools assert {"update_task", "create_rule", "update_milestone"} <= shipped for tool in sorted(shipped): named = set().union(*(per_file.get(tool, set()) for per_file in defined.values())) assert tool in named, ( f"{tool} is mapped onto a moment by the shipped defaults but does not " f"attach its mounted rules — a client without the plugin would never " f"receive them" ) # ── reply shapes ride the moments ─────────────────────────────────────── from grimoire.services import reply_shapes # noqa: E402 FINISH = [{"moment": "work.finish", "tool": "update_task", "match": "status=done", "via": "default"}] ASK = [{"moment": "reply.ask", "tool": "AskUserQuestion", "match": "", "via": "default"}] def test_an_act_brings_the_shape_for_the_reply_it_comes_before(): blocks, forms = md.shapes_for_act(FINISH) assert forms == {"completion": reply_shapes.FULL} assert reply_shapes.SHAPES["completion"].text in blocks[0] _blocks, forms = md.shapes_for_act(ASK, frozenset({"asks"})) assert forms == {"asks": reply_shapes.POINTER} def test_an_act_at_an_unshaped_moment_brings_no_shape(): assert md.shapes_for_act(PUSH) == ([], {}) async def test_a_turn_carries_the_core_in_full_until_the_session_holds_it(): with patch.object(md, "deliver_moments", AsyncMock(return_value=rp.RuleResult())): first = await md.deliver_for_turn(1) later = await md.deliver_for_turn(1, seen=frozenset({"core"})) assert first["shape_forms"] == {"core": reply_shapes.FULL} assert reply_shapes.core().text in first["context"] assert later["shape_forms"] == {"core": reply_shapes.POINTER} assert reply_shapes.core().text not in later["context"] assert reply_shapes.core().reminder in later["context"] async def test_a_turn_brings_what_is_mounted_on_reply_report_after_the_core(): deliver = AsyncMock(return_value=rp.RuleResult(lines=["Preference that may apply"], rule_ids=[173])) with patch.object(md, "deliver_moments", deliver): out = await md.deliver_for_turn(1, project_id=2, exclude=frozenset({9}), held=frozenset({4})) assert out["context"].index(reply_shapes.core().title) < out["context"].index("Preference") assert out["rule_ids"] == [173] reached = deliver.await_args.args[1] assert [hit["moment"] for hit in reached] == ["reply.report"] assert deliver.await_args.kwargs == {"project_id": 2, "exclude": frozenset({9}), "held": frozenset({4})} async def test_a_failed_mount_lookup_still_delivers_the_core(): with patch.object(md, "deliver_moments", AsyncMock(side_effect=RuntimeError("db down"))): out = await md.deliver_for_turn(1) assert reply_shapes.core().text in out["context"] and out["rule_ids"] == [] async def test_a_turn_records_its_delivery(): with patch.object(md, "deliver_moments", AsyncMock(return_value=rp.RuleResult())): await md.deliver_for_turn(1, seen=frozenset({"core"})) reply_shapes.record_delivery.assert_awaited_with(1, {"core": reply_shapes.POINTER}, via="turn") async def test_a_task_closed_through_the_tool_carries_the_completion_shape(): data = {"id": 40, "status": "done", "project_id": 2} out = await _with(_stub_db([]), lambda: md.attach_moment_rules( 1, "update_task", {"status": "done"}, data, )) assert reply_shapes.SHAPES["completion"].text in out["reply_shape"] assert "moment_rules" not in out # nothing mounted, still shaped async def test_an_unshaped_act_through_a_tool_carries_no_shape(): out = await _with(_stub_db([]), lambda: md.attach_moment_rules( 1, "create_note", {"project_id": 2}, {"id": 3}, )) assert "reply_shape" not in out async def test_the_route_puts_the_rules_ahead_of_the_shape_and_returns_its_key(): from grimoire.routes import plugin as routes deliver = AsyncMock(return_value=(ASK, rp.RuleResult(lines=["a line"], rule_ids=[5]))) app = Quart(__name__) event = {"tool_name": "AskUserQuestion", "tool_input": {}} async with app.test_request_context("/api/plugin/moment", method="POST", json=event): g.user = SimpleNamespace(id=7) with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver): body = await (await routes.moment.__wrapped__()).get_json() assert body["shape_keys"] == ["asks"] assert body["context"].index("a line") < body["context"].index("Who decides what") async with app.test_request_context("/api/plugin/moment", method="POST", json=event, query_string={"shapes_seen": "asks"}): g.user = SimpleNamespace(id=7) with patch.object(routes.moment_delivery_svc, "deliver_for_act", deliver): body = await (await routes.moment.__wrapped__()).get_json() assert body["shape_keys"] == [] assert "Who decides what" not in body["context"] def test_the_hook_carries_the_shape_ledger_between_calls(tmp_path): replies = {"/api/plugin/moment-tools": b'{"tools":["askuserquestion"]}', "/api/plugin/moment": json.dumps( {"context": "Reply shape", "rule_ids": [], "moments": ["reply.ask"], "shape_keys": ["asks"]}).encode()} with http_sink(by_path=replies) as (port, seen): _hook(tmp_path, port, tool="AskUserQuestion") _hook(tmp_path, port, tool="AskUserQuestion") moment_calls = [e for e in seen if e["_path"] == "/api/plugin/moment"] assert "shapes_seen" not in moment_calls[0] assert moment_calls[1]["shapes_seen"] == ["asks"] # ── what the act itself is told ───────────────────────────────────────── def _forced(rid, enforcement, kind="rule"): return fake_rule(id=rid, title=f"rule {rid}", kind=kind, enforcement=enforcement, statement=f"The words of rule {rid}.", when_to_apply="when it applies") async def _arm(pairs, **moment): io = rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()) return await rp.run_moment_arm(PUSH, _moment(**moment), io=io) async def test_a_rule_set_to_enforce_refuses_the_act_in_its_own_words(): result = await _arm([(_forced(5, "inform"), "work.deliver"), (_forced(6, "enforce"), "work.deliver")]) d = result.decision assert d["kind"] == "enforce" and d["rule_ids"] == [6] assert "The words of rule 6." in d["reason"] assert "at work.deliver, reached by `git push`" in d["reason"] assert 'rule_misfired(6, "work.deliver", why)' in d["reason"] # The lines still go out beside it, for a door that shows them. assert result.lines async def test_opening_an_enforced_rule_does_not_lift_it(): result = await _arm([(_forced(6, "enforce"), "work.deliver")], held=frozenset({6}), exclude=frozenset({6})) assert result.decision["kind"] == "enforce" async def test_a_rule_set_to_hold_holds_until_the_session_opens_it(): pairs = [(_forced(7, "hold"), "work.deliver")] held = (await _arm(pairs)).decision assert held["kind"] == "hold" and held["rule_ids"] == [7] assert "get_rule(7)" in held["reason"] and "re-submit" in held["reason"] assert (await _arm(pairs, held=frozenset({7}))).decision == {} async def test_an_inform_rule_and_a_preference_never_stop_the_act(): pairs = [(_forced(8, "inform"), "work.deliver"), (_forced(9, "enforce", kind="preference"), "work.deliver")] assert (await _arm(pairs)).decision == {} async def _deliver_for(tool, decision): from grimoire.services import moment_actions as ma with patch.object(ma, "moments_for", AsyncMock(return_value=PUSH)), \ patch.object(md, "_board", AsyncMock(return_value=None)), \ patch.object(md, "deliver_moments", AsyncMock(return_value=rp.RuleResult(decision=dict(decision)))): _reached, result = await _REAL_DELIVER(1, tool, {}) return result.decision async def test_a_write_is_refused_by_an_enforced_rule_but_never_held(): hold = {"kind": "hold", "rule_ids": [7], "reason": "read it"} enforce = {"kind": "enforce", "rule_ids": [6], "reason": "not run"} assert await _deliver_for("Edit", hold) == {} assert await _deliver_for("Bash", hold) == hold assert await _deliver_for("Write", enforce) == enforce def _decided(tmp_path, decision, session="s-decide"): replies = dict(TOOLS) replies["/api/plugin/moment"] = json.dumps( {"context": "a line beside it", "rule_ids": [], "moments": ["work.deliver"], "decision": decision}).encode() with http_sink(by_path=replies) as (port, _seen): return [_hook(tmp_path, port, session=session) for _ in range(2)] def test_the_hook_refuses_an_enforced_act_every_time(tmp_path): outs = _decided(tmp_path, {"kind": "enforce", "rule_ids": [6], "reason": "Not run: rule 6"}) for out in outs: body = json.loads(out)["hookSpecificOutput"] assert body["permissionDecision"] == "deny" assert body["permissionDecisionReason"] == "Not run: rule 6" def test_the_hook_holds_an_act_once_then_lets_it_through_with_its_lines(tmp_path): first, second = _decided(tmp_path, {"kind": "hold", "rule_ids": [7], "reason": "Read rule 7"}) assert json.loads(first)["hookSpecificOutput"]["permissionDecision"] == "deny" after = json.loads(second)["hookSpecificOutput"] assert "permissionDecision" not in after assert after["additionalContext"] == "a line beside it" # ── reminders wait for the act ────────────────────────────────────────── async def test_the_prompt_arm_leaves_a_rule_that_arrives_at_an_act_to_the_act(): hits = [(0.9, _forced(21, "inform")), (0.89, _forced(22, "inform"))] io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(), record_rule_surfaced=MagicMock()) moment = rp.RuleMoment(user_id=1, query="merge it", project_id=2, where="to this request", elsewhere=frozenset({21})) result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io) assert result.shown_rule_ids == [22] async def test_a_rule_arrives_at_an_act_by_a_mount_off_the_reply_or_an_act_trigger(): from grimoire.services import rule_triggers lookup = AsyncMock(return_value=[(_forced(31, "inform"), "work.deliver")]) scoped = [ (_forced(32, "inform"), [rule_triggers.Trigger("path", "alembic/**")]), (_forced(33, "inform"), [rule_triggers.Trigger("keyword", "let me know")]), (_forced(34, "inform"), [rule_triggers.Trigger("command", "git push", "work.deliver")]), ] with patch.object(moment_actions, "list_mappings", AsyncMock(return_value=[])), \ patch.object(rulebooks, "rules_on_moments", lookup), \ patch.object(rule_triggers, "_in_scope", AsyncMock(return_value=scoped)): routed = await md.routed_to_acts(1, 2) # A keyword can match a reply; a trigger scoped to a moment is that moment's mount. assert routed == frozenset({31, 32}) moments = lookup.await_args.args[1] assert moments and not any(m.startswith("reply.") for m in moments)