From 72ef1bb45d9ef7edc54f5340666265616e3b8abc Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 5 Dec 2026 22:17:30 -0500 Subject: [PATCH 1/3] fix(8816): a hold rule holds the first write to a file its own path trigger names A rule set to hold never held a file edit, so rule 198 (services run on the orchestrator's defaults), even at hold, could only sit beside the compose-file edit that broke it. The trigger board now names the rules whose path trigger matched the act, and a write is held only for those: a mount or a keyword alone still lets a write through. Tool descriptions and the using-grimoire skill say so. Co-Authored-By: Claude Opus 5.5 --- plugin/.claude-plugin/plugin.json | 2 +- plugin/skills/using-grimoire/moments.md | 3 ++- src/grimoire/mcp/tools/moments.py | 3 ++- src/grimoire/mcp/tools/rulebooks.py | 6 ++--- src/grimoire/services/moment_delivery.py | 15 ++++++++----- src/grimoire/services/rule_triggers.py | 5 +++++ tests/test_moment_delivery.py | 28 +++++++++++++++++++++--- 7 files changed, 48 insertions(+), 14 deletions(-) diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index cd452eb3..48c65d75 100644 --- a/plugin/.claude-plugin/plugin.json +++ b/plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "grimoire", "description": "Grimoire for Claude Code: connects the grimoire MCP server, adds the hooks that deliver live project state and relevant records at the right moment, ships the shared client-neutral Grimoire skills (using-grimoire, writing-plans, reporting-back, systematic-debugging, verification, brainstorming, reusing-code, shape-accounting, family-canon, reviewing-tests), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.12.04.1944", + "version": "2026.12.06.0317", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/skills/using-grimoire/moments.md b/plugin/skills/using-grimoire/moments.md index 06db6425..97a4a77e 100644 --- a/plugin/skills/using-grimoire/moments.md +++ b/plugin/skills/using-grimoire/moments.md @@ -48,7 +48,8 @@ declared `enforce` refuses the call every time, in its own words: that is a boundary the operator drew, and it moves only when they change the rule, so tell them what you were doing and what the rule said. A rule with triggers of its own holds or refuses only the acts those triggers match; at the rest of -its moments it arrives as a line. +its moments it arrives as a line. A file edit is held only by a rule whose +path trigger names that file. A moment sends a few lines, not every rule mounted there: ordered by enforcement, then salience, then how exactly the act reached the rule, then diff --git a/src/grimoire/mcp/tools/moments.py b/src/grimoire/mcp/tools/moments.py index 338d302c..364367b6 100644 --- a/src/grimoire/mcp/tools/moments.py +++ b/src/grimoire/mcp/tools/moments.py @@ -255,7 +255,8 @@ async def rules_to_weigh(limit: int = 25, offset: int = 0) -> dict: - `enforcement`: `inform` is a line beside the work, and is right for most rules. `hold` makes the act or reply wait until the rule has been - read once in the session (file edits are never held). `enforce` refuses + read once in the session (a file edit only through a path trigger + naming that file). `enforce` refuses the act the rule governs, in the rule's own words, every time — for a rule whose breach an act commits and that must never be crossed without the operator (pushing to a protected branch, a destructive command). A diff --git a/src/grimoire/mcp/tools/rulebooks.py b/src/grimoire/mcp/tools/rulebooks.py index c8ddcb51..7e774542 100644 --- a/src/grimoire/mcp/tools/rulebooks.py +++ b/src/grimoire/mcp/tools/rulebooks.py @@ -553,7 +553,7 @@ async def create_rule( enforcement: What this rule does when it arrives. `inform` (the default) puts a line beside the work. `hold` makes the reply or act it governs wait until the session has read the rule once - (file edits are never held) — for a rule whose miss costs a + (a file edit only through a path trigger naming that file) — for a rule whose miss costs a rewrite. `enforce` refuses the act it governs, in the rule's own words, every time — for a boundary only the operator moves; it needs a trigger, or a mount on a moment an act reaches, to have @@ -691,7 +691,7 @@ async def create_project_rule( enforcement: What this rule does when it arrives. `inform` (the default) puts a line beside the work. `hold` makes the reply or act it governs wait until the session has read the rule once - (file edits are never held) — for a rule whose miss costs a + (a file edit only through a path trigger naming that file) — for a rule whose miss costs a rewrite. `enforce` refuses the act it governs, in the rule's own words, every time — for a boundary only the operator moves; it needs a trigger, or a mount on a moment an act reaches, to have @@ -814,7 +814,7 @@ async def update_rule( enforcement: What this rule does when it arrives. `inform` (the default for a new rule) puts a line beside the work. `hold` makes the reply or act it governs wait until the session has read the rule once - (file edits are never held) — for a rule whose miss costs a + (a file edit only through a path trigger naming that file) — for a rule whose miss costs a rewrite. `enforce` refuses the act it governs, in the rule's own words, every time — for a boundary only the operator moves; it needs a trigger, or a mount on a moment an act reaches, to have diff --git a/src/grimoire/services/moment_delivery.py b/src/grimoire/services/moment_delivery.py index 49933966..14ab7a38 100644 --- a/src/grimoire/services/moment_delivery.py +++ b/src/grimoire/services/moment_delivery.py @@ -126,11 +126,15 @@ async def deliver_for_act( result = await deliver_moments( user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board, ) - # A write is never held for a read: a recall aid does not stand in the - # way of the work. A rule set to enforce still refuses one — that is a - # boundary the operator drew, not a reminder. + # A write is held only by a rule whose own path trigger names the file: + # a rule about a kind of file, set to hold, is read before that file + # changes. Reached by a mount or a keyword alone, a write goes ahead, so a + # recall aid does not stand in the way of ordinary work. A rule set to + # enforce still refuses one. Rules & Governance carries this as a ruling. if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS: - result.decision = {} + holding = set(result.decision.get("rule_ids") or []) + if not (board is not None and holding & board.path_hits): + result.decision = {} return reached, result @@ -159,7 +163,8 @@ async def lessons_for_act( return [lesson_situations.line(a) for a in arrivals], [a.lesson_id for a in arrivals] -# The file-writing tools, as tool keys: a `hold` rule never holds these. +# The file-writing tools, as tool keys: a `hold` rule holds these only through +# a path trigger that names the file. WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"}) diff --git a/src/grimoire/services/rule_triggers.py b/src/grimoire/services/rule_triggers.py index e70cceb6..34421085 100644 --- a/src/grimoire/services/rule_triggers.py +++ b/src/grimoire/services/rule_triggers.py @@ -250,12 +250,15 @@ class Board: `triggered` — every in-scope rule that has a trigger at all, whether or not this act met it: such a rule names the acts it governs, so a mount alone shows it beside the work and only its trigger can stop an act. + `path_hits` — rules with a `path` trigger, scoped or not, that names the + file this act touches: the only rules a hold may hold a write for. """ gated: set[tuple[int, str]] = field(default_factory=set) matched: set[tuple[int, str]] = field(default_factory=set) fired: list[tuple[object, Trigger]] = field(default_factory=list) triggered: set[int] = field(default_factory=set) + path_hits: set[int] = field(default_factory=set) async def board( @@ -270,6 +273,8 @@ async def board( first_unscoped = None for trig in triggers: hit = matches(trig, tool, tool_input, text) + if hit and trig.kind == PATH: + out.path_hits.add(rule.id) if trig.moment: pair = (rule.id, trig.moment) if hit: diff --git a/tests/test_moment_delivery.py b/tests/test_moment_delivery.py index c80b000b..f937e89f 100644 --- a/tests/test_moment_delivery.py +++ b/tests/test_moment_delivery.py @@ -563,23 +563,45 @@ async def test_an_inform_rule_and_a_preference_never_stop_the_act(): assert (await _arm(pairs)).decision == {} -async def _deliver_for(tool, decision): +async def _deliver_for(tool, decision, board=None): 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, "_board", AsyncMock(return_value=board)), \ 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(): +async def test_a_write_is_refused_by_an_enforced_rule_and_held_only_through_a_path_trigger(): + from grimoire.services.rule_triggers import Board + 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 + # Rule 7's own path trigger names the file: the write waits for one read. + assert await _deliver_for("Edit", hold, Board(path_hits={7})) == hold + # Another rule's path trigger matched; rule 7 reached the write otherwise. + assert await _deliver_for("Write", hold, Board(path_hits={8})) == {} + + +async def test_the_board_names_the_rules_a_path_trigger_matched(monkeypatch): + from grimoire.services import rule_triggers as rt + + compose = fake_rule(id=198, title="defaults") + keyword = fake_rule(id=5, title="keyword only") + monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[ + (compose, [rt.Trigger("keyword", "update_config"), rt.Trigger("path", "**/compose*.yml")]), + (keyword, [rt.Trigger("keyword", "update_config")]), + ])) + edit = {"file_path": "/repo/deploy/compose.deploy.yml", "new_string": "update_config:"} + board = await rt.board(1, 2, tool="Edit", tool_input=edit) + assert board.path_hits == {198} + other = await rt.board(1, 2, tool="Edit", tool_input={**edit, "file_path": "/repo/README.md"}) + assert other.path_hits == set() def _decided(tmp_path, decision, session="s-decide"): From 58991038d81b4f3ea1cd750e98404b574c8b34b7 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sat, 5 Dec 2026 22:21:49 -0500 Subject: [PATCH 2/3] feat(8815): a message that reads as another project's work asks the session to check before acting An operator running one session per project can type into the wrong window, and nothing caught it: the message usually asks for work the session can do in its own repo, so the project fence never fires. The prompt lookup (/api/plugin/retrieve) now ranks the operator's own words against every project's records (services/project_check.py). When another project's records clearly win (best match >= 0.78, ahead of this project's by 0.05, with at least 3 of the 12 nearest), a line leads the payload, ahead of every rule, telling the session to ask the operator whether the message was meant for it. Naming the other project halves the margin but never flags alone; naming this project rules a flag out. A message with no subject, or a session with no project, is not checked. Each flag is a new `project_check` gate stop with both scores, asked once per session per other project, read back in retrieval_telemetry's gates block and in the web UI's gate readout. Co-Authored-By: Claude Opus 5.5 --- frontend/src/api/moments.ts | 4 +- frontend/src/components/GateStops.vue | 15 +++ src/grimoire/models/gate_stop.py | 8 +- src/grimoire/routes/plugin.py | 13 ++ src/grimoire/services/gate_stops.py | 35 ++++- src/grimoire/services/project_check.py | 171 +++++++++++++++++++++++++ tests/test_integration_gate_stops.py | 14 ++ tests/test_project_check.py | 131 +++++++++++++++++++ 8 files changed, 386 insertions(+), 5 deletions(-) create mode 100644 src/grimoire/services/project_check.py create mode 100644 tests/test_project_check.py diff --git a/frontend/src/api/moments.ts b/frontend/src/api/moments.ts index dd9c7778..0b5800d1 100644 --- a/frontend/src/api/moments.ts +++ b/frontend/src/api/moments.ts @@ -354,7 +354,7 @@ export function getRecordReach(days = 30): Promise { } /** The gates that can stop a tool call. */ -export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply"; +export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply" | "project_check"; export interface GateCounts { /** Calls denied, or for the fence, put to the operator. */ @@ -385,6 +385,8 @@ export interface GateStopsPayload { by_gate: Record; by_rule: GateRuleRow[]; fence: { tool: string; target: string | null; asks: number; ran: number }[]; + /** Messages flagged as reading like another project's work, per that project. */ + project_check: { target: string | null; asks: number; last_asked_at: string | null }[]; /** The first stop ever recorded; null when none has been. */ complete_from: string | null; covers_window: boolean | null; diff --git a/frontend/src/components/GateStops.vue b/frontend/src/components/GateStops.vue index 0553c15d..b0192eac 100644 --- a/frontend/src/components/GateStops.vue +++ b/frontend/src/components/GateStops.vue @@ -24,6 +24,7 @@ const GATES: [GateName, string][] = [ ["checkpoint", "Command checkpoint"], ["fence", "Project fence"], ["reply", "Reply held for a read"], + ["project_check", "Message meant for another project?"], ]; const any = computed(() => @@ -32,6 +33,8 @@ const any = computed(() => function gateText(gate: GateName, c: GateCounts): string[] { if (gate === "fence") return [`asked ${c.stops}`, `approved ${c.ran}`]; + // The session is told to check with the operator; nothing is stopped. + if (gate === "project_check") return [`asked ${c.stops}`]; const parts = [`stopped ${c.stops}`, `cleared by a read ${c.cleared}`, `misfired ${c.misfired}`]; // An enforced refusal has no cap, and the reply's cap is applied by the // server before anything holds, so neither can let a call through. @@ -101,6 +104,18 @@ function gateText(gate: GateName, c: GateCounts): string[] { +
+ Messages that read as another project's +
    +
  • + project {{ p.target }} + + asked {{ p.asks }} + last {{ fmtDate(p.last_asked_at) }} + +
  • +
+
diff --git a/src/grimoire/models/gate_stop.py b/src/grimoire/models/gate_stop.py index c59fbef4..9f74ae3d 100644 --- a/src/grimoire/models/gate_stop.py +++ b/src/grimoire/models/gate_stop.py @@ -12,7 +12,13 @@ HOLD = "hold" # a moment rule set to hold: one read before the act CHECKPOINT = "checkpoint" # the act checkpoint on a command (tool-rules) FENCE = "fence" # the project fence: the operator is asked REPLY = "reply" # a rule holding the finished reply for one read -GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY) +# The operator's message reads as another project's: the session is asked to +# check with them before acting (`services/project_check.py`). `tool` is +# "prompt", `target` the other project, `at` the two scores. +PROJECT_CHECK = "project_check" +GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY, PROJECT_CHECK) +# The gates that stand in front of something other than a rule. +RULELESS_GATES = (FENCE, PROJECT_CHECK) # What the hook did with it. STOPPED = "stopped" # the call was denied, the reason shown instead diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 32d198c5..57befc12 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -18,6 +18,7 @@ from grimoire.services import gate_stops as gate_stops_svc from grimoire.services import hook_payload as hook_payload_svc from grimoire.services import moment_delivery as moment_delivery_svc from grimoire.services import plugin_context as plugin_ctx_svc +from grimoire.services import project_check as project_check_svc from grimoire.services import reply_shapes as reply_shapes_svc from grimoire.services import repo_bindings as repo_bindings_svc from grimoire.services import rule_adherence as rule_adherence_svc @@ -223,6 +224,15 @@ async def autoinject_retrieve(): held_rule_ids = _int_list(request.args.get("held_rule_ids")) ctx = request.args.get("ctx") or "" + # Whether the message is this project's at all. The operator's own words + # only: the conversation tail is this session's, so it would always vote + # for this project. A message with no subject ("yes, go ahead") says + # nothing about where it belongs. + wrong_project = "" + if project_id and not plugin_ctx_svc.is_harness_turn(q) and plugin_ctx_svc._has_subject(q): + wrong_project = await project_check_svc.check( + g.user.id, q, project_id, request.args.get("session_id"), + ) rules = await plugin_ctx_svc.build_prompt_rule_hint( g.user.id, q, project_id=project_id, exclude_rule_ids=exclude_rule_ids, held_rule_ids=held_rule_ids, context=ctx, @@ -263,6 +273,9 @@ async def autoinject_retrieve(): hook_payload_svc.SHAPE: tuple(turn.get("shape_forms") or ()), })] fitted = await hook_payload_svc.fit(g.user.id, [ + # First, ahead of every rule: if the message was meant for another + # session, nothing after it should be acted on yet. + *([hook_payload_svc.Part(text=wrong_project)] if wrong_project else []), *ordered, *([hook_payload_svc.Part(text=carry)] if carry else []), *hook_payload_svc.parts_of(result, {hook_payload_svc.NOTE: "note_ids"}), diff --git a/src/grimoire/services/gate_stops.py b/src/grimoire/services/gate_stops.py index 0af5accd..a54de1fb 100644 --- a/src/grimoire/services/gate_stops.py +++ b/src/grimoire/services/gate_stops.py @@ -29,7 +29,8 @@ from sqlalchemy import and_, case, delete, exists, func, select, update from grimoire.models import async_session from grimoire.models.gate_stop import ( - ASKED, FENCE, GATES, LET_THROUGH, OUTCOMES, STOPPED, GateStop, + ASKED, FENCE, GATES, LET_THROUGH, OUTCOMES, PROJECT_CHECK, RULELESS_GATES, STOPPED, + GateStop, ) from grimoire.models.rule_adherence import MISFIRE, RuleAdherence from grimoire.models.rulebook import Rule @@ -59,7 +60,7 @@ async def record( sid = rule_deliveries.clean_session(session_id) if not sid or gate not in GATES or outcome not in OUTCOMES or not _field(tool): return False - if gate != FENCE and not rule_id: + if gate not in RULELESS_GATES and not rule_id: return False async with async_session() as session: session.add(GateStop( @@ -112,6 +113,21 @@ async def mark_ran(user_id: int, session_id: str | None, call_id: str | None) -> return bool(result.rowcount) +async def asked(user_id: int, session_id: str | None, *, gate: str, target: str) -> bool: + """Whether this gate already stood in front of this session about this + target, so a session is asked about one other project once.""" + sid = rule_deliveries.clean_session(session_id) + if not sid: + return False + async with async_session() as session: + return (await session.execute( + select(exists().where( + GateStop.user_id == user_id, GateStop.session_id == sid, + GateStop.gate == gate, GateStop.target == _field(target), + )) + )).scalar_one() + + def _misfired(): """Whether the session reported the stopped rule as a misfire.""" return exists().where( @@ -139,7 +155,9 @@ async def summary(user_id: int, days: int = 30, *, since: datetime | None = None for the fence, the operator's yes) and `sessions`. `by_rule`: the same per rule and place, most stops first. `fence`: the - asks per tool and target project. `complete_from` is the first stop ever + asks per tool and target project. `project_check`: per other project, how + often a message was flagged as reading like its work rather than the + session's. `complete_from` is the first stop ever recorded, so a window reaching further back says so. """ until = until or datetime.now(timezone.utc) @@ -180,6 +198,12 @@ async def summary(user_id: int, days: int = 30, *, since: datetime | None = None .group_by(GateStop.tool, GateStop.target) .order_by(func.count(GateStop.id).desc(), GateStop.tool) )).all() + check_rows = (await session.execute( + select(GateStop.target, func.count(GateStop.id), func.max(GateStop.stopped_at)) + .where(window, GateStop.gate == PROJECT_CHECK) + .group_by(GateStop.target) + .order_by(func.count(GateStop.id).desc(), GateStop.target) + )).all() first = (await session.execute( select(func.min(GateStop.stopped_at)).where(GateStop.user_id == user_id) )).scalar_one_or_none() @@ -205,6 +229,11 @@ async def summary(user_id: int, days: int = 30, *, since: datetime | None = None {"tool": tool, "target": target, "asks": int(n or 0), "ran": int(ran or 0)} for tool, target, n, ran in fence_rows ], + "project_check": [ + {"target": target, "asks": int(n or 0), + "last_asked_at": last.isoformat() if last else None} + for target, n, last in check_rows + ], "complete_from": first.isoformat() if first else None, "covers_window": None if first is None else first <= since, } diff --git a/src/grimoire/services/project_check.py b/src/grimoire/services/project_check.py new file mode 100644 index 00000000..a2a3de2c --- /dev/null +++ b/src/grimoire/services/project_check.py @@ -0,0 +1,171 @@ +"""Does the operator's message belong to the project this session is in? + +An operator who runs one session per project can type a message into the +wrong window. Such a message usually reads as an ordinary request the session +could carry out in its own repo, so nothing crosses a project line and the +project fence never fires. This check reads where the message lands among the +operator's own records: when the nearest ones clearly belong to another +project, the session is told so, first in the prompt's payload, and asked to +confirm with the operator before acting. It asks; it never blocks. + +Each flag is recorded as a `project_check` gate stop (`gate_stops`), with the +two scores in `at`, so the bars below can be tuned from real prompts, and a +session is asked about one other project once. +""" +from __future__ import annotations + +import logging +import re +from dataclasses import dataclass + +logger = logging.getLogger(__name__) + +# How many of the nearest records are read: enough for one project's records +# to show up as a group, few enough to stay one exact cut. +NEAREST = 12 +# The search's own floor. Low on purpose, so this project's best match is +# known even when it is weak, which is when a message most likely is not its. +SEARCH_FLOOR = 0.5 +# The other project's nearest record must score at least this. Below it the +# message matches no project's records well, and "it belongs elsewhere" is +# a guess. +FLOOR = 0.78 +# How far the other project's nearest record must beat this project's. +MARGIN = 0.05 +# How many of the nearest records must be the other project's, so a single +# stray record cannot call a message another project's. +SUPPORT = 3 +# A message that names the other project, and not this one, needs only this +# share of the margin. A name alone never flags: many project names are +# ordinary words ("portal", "interpreter"), and naming another project on +# purpose is common. +NAMED_MARGIN_SHARE = 0.5 +# The operator's words that are read; a long paste adds nothing to where the +# message lands. +QUERY_CHARS = 2000 + + +@dataclass(frozen=True) +class Verdict: + other_id: int + other_score: float + here_score: float + + +def judge( + hits: list[tuple[float, int | None]], project_id: int, *, + named: frozenset[int] = frozenset(), +) -> Verdict | None: + """Whether the nearest records say the message is another project's. + + `hits` are (score, project id) for the nearest records, any order; a + record in no project is left out. `named` holds the projects the message + names by title. Naming this project rules out a flag. + """ + if project_id in named: + return None + best: dict[int, float] = {} + count: dict[int, int] = {} + for score, pid in hits: + if pid is None: + continue + best[pid] = max(best.get(pid, score), score) + count[pid] = count.get(pid, 0) + 1 + here = best.get(project_id, 0.0) + others = [(score, pid) for pid, score in best.items() if pid != project_id] + if not others: + return None + other_score, other_id = max(others) + margin = MARGIN * (NAMED_MARGIN_SHARE if other_id in named else 1.0) + if other_score < FLOOR or other_score - here < margin or count[other_id] < SUPPORT: + return None + return Verdict(other_id=other_id, other_score=other_score, here_score=here) + + +def _name_forms(title: str) -> set[str]: + """The ways a message names a project: its title, and its title without a + leading "Fabled" ("Fabled Librarian" is called "Librarian").""" + title = " ".join((title or "").split()) + forms = {title.lower()} if title else set() + bare = re.sub(r"^fabled[\s-]*", "", title, flags=re.IGNORECASE) + if bare and len(bare) >= 4: + forms.add(bare.lower()) + return forms + + +def named_projects(prompt: str, titles: dict[int, str]) -> frozenset[int]: + """The projects whose title the message contains as a whole phrase.""" + text = (prompt or "").lower() + return frozenset( + pid for pid, title in titles.items() + if any(re.search(r"(? str: + other = titles.get(verdict.other_id, f"project {verdict.other_id}") + here = titles.get(project_id, f"project {project_id}") + return ( + f"> **This message may be meant for another session.** It reads as " + f"{other}'s work rather than {here}'s, the project this session is in: " + f"its nearest records are {other}'s ({verdict.other_score:.2f}, against " + f"{verdict.here_score:.2f} for {here}). The operator runs one session per " + f"project and can type into the wrong one. Before acting on it, ask them " + f"whether it was meant for this session, naming {other}; if it was, carry on." + ) + + +async def _titles(user_id: int) -> dict[int, str]: + from sqlalchemy import select + + from grimoire.models import async_session + from grimoire.models.project import Project + + async with async_session() as session: + return dict((await session.execute( + select(Project.id, Project.title).where(Project.user_id == user_id) + )).all()) + + +async def _asked_before(user_id: int, session_id: str | None, other_id: int) -> bool: + from grimoire.services import gate_stops + + return await gate_stops.asked(user_id, session_id, gate="project_check", + target=str(other_id)) + + +async def check(user_id: int, prompt: str, project_id: int, session_id: str | None = None) -> str: + """The line to lead the prompt's payload with, or "" when the message + fits this session's project, or nothing can be said. Fails open.""" + if not project_id or not (prompt or "").strip(): + return "" + from grimoire.services import gate_stops + from grimoire.services.embeddings import semantic_search_notes + + try: + hits = await semantic_search_notes( + user_id, prompt[:QUERY_CHARS], limit=NEAREST, threshold=SEARCH_FLOOR, + project_id=None, scope="own", demote_superseded=False, + ) + if not hits: + return "" + titles = await _titles(user_id) + verdict = judge( + [(score, getattr(note, "project_id", None)) for score, note in hits], + project_id, named=named_projects(prompt, titles), + ) + if verdict is None or verdict.other_id not in titles: + return "" + if session_id and await _asked_before(user_id, session_id, verdict.other_id): + return "" + if session_id: + await gate_stops.record( + user_id, session_id, gate="project_check", outcome="asked", tool="prompt", + target=str(verdict.other_id), + at=f"{verdict.other_score:.3f} vs {verdict.here_score:.3f}", + ) + return line(verdict, titles, project_id) + except Exception: # noqa: BLE001 - a hint never costs the operator their prompt + logger.warning("project check failed", exc_info=True) + return "" diff --git a/tests/test_integration_gate_stops.py b/tests/test_integration_gate_stops.py index d4d34578..1badffaf 100644 --- a/tests/test_integration_gate_stops.py +++ b/tests/test_integration_gate_stops.py @@ -111,6 +111,20 @@ async def test_the_readout_counts_stops_reads_misfires_and_the_cap_per_gate_and_ assert out["complete_from"] is not None +async def test_a_project_check_needs_no_rule_is_asked_once_per_session_and_is_read_back(): + uid = await _user() + assert not await gate_stops.asked(uid, "s-1", gate="project_check", target="6") + assert await gate_stops.record(uid, "s-1", gate="project_check", outcome="asked", + tool="prompt", target="6", at="0.860 vs 0.740") + assert await gate_stops.asked(uid, "s-1", gate="project_check", target="6") + # Another session, or another project, has not been asked. + assert not await gate_stops.asked(uid, "s-2", gate="project_check", target="6") + assert not await gate_stops.asked(uid, "s-1", gate="project_check", target="9") + out = await gate_stops.summary(uid, days=1) + assert out["by_gate"]["project_check"]["stops"] == 1 + assert [(p["target"], p["asks"]) for p in out["project_check"]] == [("6", 1)] + + async def test_stops_age_out_with_the_deliveries(): uid = await _user() await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash", rule_id=RULE) diff --git a/tests/test_project_check.py b/tests/test_project_check.py new file mode 100644 index 00000000..2b1ce50e --- /dev/null +++ b/tests/test_project_check.py @@ -0,0 +1,131 @@ +"""The check on whether the operator's message belongs to the session's project. + +Pins, with the database stubbed: +- the nearest records decide: another project flags only when its best match + is high, clearly ahead of this project's, and backed by several records; +- a name helps but never flags alone, and naming this project rules a flag out; +- a session is asked about one other project once, and the ask is recorded; +- the line leads the prompt's payload, and a session with no project is never + checked. +""" +from __future__ import annotations + +import inspect +from types import SimpleNamespace +from unittest.mock import AsyncMock, patch + +from quart import Quart, g + +from grimoire.services import project_check as pc + +HERE, OTHER, THIRD = 2, 6, 9 +TITLES = {HERE: "FabledGrimoire", OTHER: "Steward", THIRD: "Fabled Librarian"} + + +def _hits(*pairs): + return [(score, pid) for score, pid in pairs] + + +def test_a_message_whose_nearest_records_are_another_projects_is_flagged(): + verdict = pc.judge(_hits((0.86, OTHER), (0.84, OTHER), (0.83, OTHER), (0.74, HERE)), HERE) + assert verdict == pc.Verdict(other_id=OTHER, other_score=0.86, here_score=0.74) + + +def test_a_message_that_fits_this_project_is_not_flagged(): + assert pc.judge(_hits((0.86, HERE), (0.85, OTHER), (0.84, OTHER), (0.83, OTHER)), HERE) is None + + +def test_each_bar_on_its_own_keeps_a_flag_back(): + # Below the floor: nobody's records match the message well. + assert pc.judge(_hits((0.76, OTHER), (0.75, OTHER), (0.75, OTHER)), HERE) is None + # Ahead by less than the margin. + assert pc.judge(_hits((0.85, OTHER), (0.84, OTHER), (0.84, OTHER), (0.82, HERE)), HERE) is None + # One stray record is not a project's worth of support. + assert pc.judge(_hits((0.90, OTHER), (0.80, THIRD), (0.79, THIRD), (0.70, HERE)), HERE) is None + + +def test_records_in_no_project_say_nothing_about_where_a_message_belongs(): + assert pc.judge(_hits((0.95, None), (0.94, None), (0.93, None)), HERE) is None + + +def test_a_name_narrows_the_margin_but_naming_this_project_rules_a_flag_out(): + hits = _hits((0.85, OTHER), (0.84, OTHER), (0.83, OTHER), (0.82, HERE)) + assert pc.judge(hits, HERE) is None + assert pc.judge(hits, HERE, named=frozenset({OTHER})) is not None + assert pc.judge(hits, HERE, named=frozenset({OTHER, HERE})) is None + + +def test_names_are_matched_as_whole_phrases_with_or_without_fabled(): + assert pc.named_projects("the librarian sidebar flickers", TITLES) == {THIRD} + assert pc.named_projects("check Steward's backups", TITLES) == {OTHER} + assert pc.named_projects("stewardship of the data", TITLES) == frozenset() + + +def test_the_line_names_both_projects_and_asks_before_acting(): + text = pc.line(pc.Verdict(OTHER, 0.86, 0.74), TITLES, HERE) + assert "Steward" in text and "FabledGrimoire" in text + assert "0.86" in text and "0.74" in text + assert "ask them" in text + + +async def _check(hits, *, asked=False, session="s-1"): + record = AsyncMock(return_value=True) + notes = [(score, SimpleNamespace(project_id=pid)) for score, pid in hits] + with patch("grimoire.services.embeddings.semantic_search_notes", AsyncMock(return_value=notes)), \ + patch.object(pc, "_titles", AsyncMock(return_value=TITLES)), \ + patch.object(pc, "_asked_before", AsyncMock(return_value=asked)), \ + patch("grimoire.services.gate_stops.record", record): + out = await pc.check(1, "the backup job missed last night", HERE, session) + return out, record + + +async def test_a_flag_is_recorded_as_a_project_check_ask_with_both_scores(): + out, record = await _check(_hits((0.86, OTHER), (0.84, OTHER), (0.83, OTHER), (0.74, HERE))) + assert out.startswith("> **This message may be meant for another session.**") + kw = record.await_args.kwargs + assert kw["gate"] == "project_check" and kw["outcome"] == "asked" + assert kw["target"] == str(OTHER) and kw["at"] == "0.860 vs 0.740" + + +async def test_a_session_is_asked_about_one_other_project_once(): + out, record = await _check(_hits((0.86, OTHER), (0.84, OTHER), (0.83, OTHER)), asked=True) + assert out == "" + record.assert_not_awaited() + + +async def test_a_failed_search_lets_the_prompt_through_silently(): + with patch("grimoire.services.embeddings.semantic_search_notes", AsyncMock(side_effect=RuntimeError)): + assert await pc.check(1, "the backup job", HERE, "s-1") == "" + assert await pc.check(1, "the backup job", 0, "s-1") == "" + + +async def _retrieve(query_string, wrong="WRONG PROJECT LINE"): + from grimoire.routes import plugin as routes + + check = AsyncMock(return_value=wrong) + app = Quart(__name__) + async with app.test_request_context("/api/plugin/retrieve", query_string=query_string): + g.user = SimpleNamespace(id=7) + with patch.object(routes.project_check_svc, "check", check), \ + patch.object(routes.plugin_ctx_svc, "build_prompt_rule_hint", + AsyncMock(return_value={"context": "RULE LINE", "rule_ids": [11], + "shown_rule_ids": [11]})), \ + patch.object(routes.plugin_ctx_svc, "build_autoinject_hint", + AsyncMock(return_value={"context": "NOTES MENU", "note_ids": []})), \ + patch.object(routes.moment_delivery_svc, "deliver_for_turn", + AsyncMock(return_value={"context": "", "rule_ids": [], "shape_forms": {}})): + resp = await inspect.unwrap(routes.autoinject_retrieve)() + return await resp.get_json(), check + + +async def test_the_flag_leads_the_payload_ahead_of_every_rule(): + body, check = await _retrieve({"q": "the backup job missed", "project_id": "2", "session_id": "s-1"}) + assert body["context"].index("WRONG PROJECT LINE") < body["context"].index("RULE LINE") + assert check.await_args.args == (7, "the backup job missed", 2, "s-1") + + +async def test_a_session_with_no_project_or_a_message_with_no_subject_is_not_checked(): + _body, check = await _retrieve({"q": "the backup job missed"}) + check.assert_not_awaited() + _body, check = await _retrieve({"q": "yes go ahead", "project_id": "2"}) + check.assert_not_awaited() From 9cfa07a8845e679fa7725a73749163f7293b7aa4 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sun, 6 Dec 2026 00:21:20 -0500 Subject: [PATCH 3/3] feat: a tool that takes its search term as q also takes it as query query was the most common misnamed argument in the live logs, and on a tool that declares q it cannot mean anything else. Passing both is still refused by the unknown-argument check. Co-Authored-By: Claude Opus 5.5 --- src/grimoire/mcp/server.py | 18 +++++++++++++++++ tests/test_mcp_strict_args.py | 38 +++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) diff --git a/src/grimoire/mcp/server.py b/src/grimoire/mcp/server.py index c2359d41..840f0ea1 100644 --- a/src/grimoire/mcp/server.py +++ b/src/grimoire/mcp/server.py @@ -295,6 +295,23 @@ def _body_calls_write_tool(body: bytes) -> bool: return False +# Spellings callers reach for that mean exactly one declared argument. A tool +# that declares the canonical name and not the alias takes the alias in its +# place: `query` is the most common miss for the search tools' `q`, and it +# cannot mean anything else. Passing both is left to the unknown-argument check. +_ALIASES = {"query": "q"} + + +def _with_aliases(arguments: dict | None, declared: set[str]) -> dict | None: + if not arguments: + return arguments + out = dict(arguments) + for alias, name in _ALIASES.items(): + if alias in out and alias not in declared and name in declared and name not in out: + out[name] = out.pop(alias) + return out + + class StrictArgsMCPServer(MCPServer): """An MCPServer that REJECTS tool calls carrying undeclared arguments. @@ -323,6 +340,7 @@ class StrictArgsMCPServer(MCPServer): tool = None # unknown tool → let upstream produce its own error if tool is not None: declared = set((tool.parameters or {}).get("properties", {})) + arguments = _with_aliases(arguments, declared) unknown = sorted(set(arguments or {}) - declared) if unknown: hints = [] diff --git a/tests/test_mcp_strict_args.py b/tests/test_mcp_strict_args.py index 7cbfd588..eeb391b2 100644 --- a/tests/test_mcp_strict_args.py +++ b/tests/test_mcp_strict_args.py @@ -44,6 +44,44 @@ async def test_unknown_argument_is_an_error_not_a_silent_drop(): assert "Nothing was created or changed" in msg +def _query_server() -> StrictArgsMCPServer: + mcp = StrictArgsMCPServer("alias-test") + + @mcp.tool() + def find(q: str = "") -> str: + return f"found:{q}" + + @mcp.tool() + def own(query: str = "") -> str: + return f"own:{query}" + + return mcp + + +async def test_query_is_taken_as_q_by_a_tool_that_declares_q(): + mcp = _query_server() + assert "found:backups" in str(await mcp.call_tool("find", {"query": "backups"})) + # A tool that declares `query` itself keeps it. + assert "own:backups" in str(await mcp.call_tool("own", {"query": "backups"})) + + +async def test_query_beside_q_is_still_refused(): + mcp = _query_server() + with pytest.raises(ToolError) as exc: + await mcp.call_tool("find", {"q": "a", "query": "b"}) + assert "'query'" in str(exc.value) + + +async def test_the_real_search_tool_takes_query(): + """Against the REAL server: search declares `q`, so `query` is renamed + before the unknown-argument check rather than refused by it.""" + from grimoire.mcp.server import _with_aliases, build_mcp_server + + tool = build_mcp_server()._tool_manager.get_tool("search") + declared = set(tool.parameters["properties"]) + assert _with_aliases({"query": "x"}, declared) == {"q": "x"} + + async def test_empty_arguments_pass(): mcp = _echo_server() assert await mcp.call_tool("echo", {}) is not None