From 82ffd9a2357d06fb7155c7ad0c457f34c5381ed4 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 14:32:46 -0500 Subject: [PATCH] feat(8141): a rule holding the finished reply is recorded as a gate stop too The end-of-turn reply hold was the one gate the gate_stops table left out. The server applies the per-session cap before anything holds and the Stop hook blocks on every reason it is given, so the hook reports each held rule after blocking, as the tool-call gates do: gate `reply`, tool `reply`, and where the rule was reached (`rule_at`, new beside `rule_ids` in the /reply-rules answer: the moment it is mounted on, or `reply_rule` for the backstop). A section hold names no rule and stays counted by report_check. Opening the rule clears the stop, and rule_misfired marks it, unchanged. The readout, the telemetry docstring and the Settings panel name the new gate. Co-Authored-By: Claude Opus 5.5 --- frontend/src/api/moments.ts | 2 +- frontend/src/components/GateStops.vue | 11 ++++--- plugin/.claude-plugin/plugin.json | 2 +- plugin/PACKAGING.md | 2 +- plugin/hooks/grimoire_reply_check.sh | 11 +++++++ src/grimoire/mcp/tools/search.py | 5 +-- src/grimoire/models/gate_stop.py | 8 +++-- src/grimoire/routes/plugin.py | 5 ++- src/grimoire/services/moment_delivery.py | 6 +++- tests/test_gate_stop_hooks.py | 39 ++++++++++++++++++++++++ tests/test_reply_moment.py | 12 +++++--- 11 files changed, 85 insertions(+), 18 deletions(-) diff --git a/frontend/src/api/moments.ts b/frontend/src/api/moments.ts index e02bb439..b4628a8c 100644 --- a/frontend/src/api/moments.ts +++ b/frontend/src/api/moments.ts @@ -341,7 +341,7 @@ export function getRecordReach(days = 30): Promise { } /** The gates that can stop a tool call. */ -export type GateName = "enforce" | "hold" | "checkpoint" | "fence"; +export type GateName = "enforce" | "hold" | "checkpoint" | "fence" | "reply"; export interface GateCounts { /** Calls denied, or for the fence, put to the operator. */ diff --git a/frontend/src/components/GateStops.vue b/frontend/src/components/GateStops.vue index 98cf2717..0553c15d 100644 --- a/frontend/src/components/GateStops.vue +++ b/frontend/src/components/GateStops.vue @@ -4,9 +4,9 @@ import type { GateCounts, GateName, GateStopsPayload } from "@/api/moments"; import { fmtDate } from "@/utils/dateFormat"; /** - * Every time Grimoire stood in front of a tool call instead of commenting - * beside it: a rule set to enforce or hold, the checkpoint on a command, or - * the project fence asking the operator. Per gate and per rule, how often it + * Every time Grimoire stood in front of the work instead of commenting + * beside it: a rule set to enforce or hold, the checkpoint on a command, the + * project fence asking the operator, or a rule holding the finished reply. Per gate and per rule, how often it * stopped work and what followed — the rule opened (the stop cleared the way * it is meant to), the rule reported as a misfire (a stop at the wrong * moment), or a hold let through because the session's stop budget was @@ -23,6 +23,7 @@ const GATES: [GateName, string][] = [ ["hold", "Held for a read (hold)"], ["checkpoint", "Command checkpoint"], ["fence", "Project fence"], + ["reply", "Reply held for a read"], ]; const any = computed(() => @@ -32,7 +33,9 @@ const any = computed(() => function gateText(gate: GateName, c: GateCounts): string[] { if (gate === "fence") return [`asked ${c.stops}`, `approved ${c.ran}`]; const parts = [`stopped ${c.stops}`, `cleared by a read ${c.cleared}`, `misfired ${c.misfired}`]; - if (gate !== "enforce") parts.push(`let through by the cap ${c.let_through}`); + // 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. + if (gate === "hold" || gate === "checkpoint") parts.push(`let through by the cap ${c.let_through}`); return parts; } diff --git a/plugin/.claude-plugin/plugin.json b/plugin/.claude-plugin/plugin.json index ad9d2317..0ab4aef7 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), and syncs your saved Grimoire Processes as skills (/grimoire:sync).", - "version": "2026.11.27.1912", + "version": "2026.11.27.1932", "author": { "name": "Bryan Van Deusen" }, diff --git a/plugin/PACKAGING.md b/plugin/PACKAGING.md index d7b15586..c41ca8d2 100644 --- a/plugin/PACKAGING.md +++ b/plugin/PACKAGING.md @@ -42,7 +42,7 @@ another one means adding files, not moving or rewriting any. | `hooks/grimoire_project_fence.sh` | PreToolUse on editor writes, shell commands and Grimoire's tools: `GET /api/plugin/write-scope` for an act aimed at another project, answered `ask` with the reason, and each ask reported to `POST /api/plugin/gate-stop` with the tool call's id; PostToolUse on `enter_project` remembers the project a session without one entered. | | `hooks/grimoire_fence_ran.sh` | PostToolUse on the tools the fence checks: when the call that ran is the one the fence asked about, `POST /api/plugin/gate-ran`, the operator's yes. Exits at once when no ask is pending. | | `hooks/grimoire_moment.sh` | PreToolUse on every tool: the rules mounted on the moments the call reaches, `POST /api/plugin/moment`; skips tools `GET /api/plugin/moment-tools` says reach nothing mounted, and Grimoire's own (their responses carry `moment_rules`). Denies the call when the response's `decision` is `enforce` (every time) or `hold` (once per rule and session), and reports each stop, and each hold the session's budget let through, to `POST /api/plugin/gate-stop`. | -| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite. | +| `hooks/grimoire_reply_check.sh` | Stop: sends the finished reply to `POST /api/plugin/reply-rules` — the rules mounted on the reply moments, and the reply against every rule's trigger, and — when the turn closed a task — the completion-section check; holds once per rule, with the reason the server returns, and never holds the rewrite; reports each rule that held to `POST /api/plugin/gate-stop`. | | `hooks/grimoire_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `.written.ids` ledger) to `GET /api/plugin/shape-check` and keeps the `note` it returns for the next prompt, which `grimoire_autoinject.sh` carries as `carry`, so the agent judges what it built. Never blocks. | | `hooks/grimoire_record_opened.sh` | PostToolUse on `get_rule`: notes the rule as read in the session ledger and `POST /api/plugin/rule-opened`. | | `hooks/grimoire_record_outcome.sh` | PostToolUse on `rule_outcome`: notes the rule as acted on, locally, for the session-scoped readout. | diff --git a/plugin/hooks/grimoire_reply_check.sh b/plugin/hooks/grimoire_reply_check.sh index a2b1eead..e3a4118c 100644 --- a/plugin/hooks/grimoire_reply_check.sh +++ b/plugin/hooks/grimoire_reply_check.sh @@ -126,4 +126,15 @@ done grimoire_json_list "$answer_flat" '.rule_ids' | grimoire_rules_append "$rulefile" printf '{"decision":"block","reason":"%s"}\n' "$(printf '%s' "$reason" | grimoire_json_escape)" + +# Each rule that held the reply, reported as a gate stop with where it was +# reached, as the tool-call gates report theirs. The server already applied +# the per-session cap, so a reason here is a hold. A section hold names no +# rule and is counted by its own check (`report_check`). +i=0 +for id in $(grimoire_json_list "$answer_flat" '.rule_ids'); do + grimoire_gate_report "$session_id" reply stopped reply "$id" \ + "$(grimoire_json_pick "$answer_flat" ".rule_at[$i]")" "" "" + i=$((i + 1)) +done exit 0 diff --git a/src/grimoire/mcp/tools/search.py b/src/grimoire/mcp/tools/search.py index 18fac785..be29efbc 100644 --- a/src/grimoire/mcp/tools/search.py +++ b/src/grimoire/mcp/tools/search.py @@ -540,8 +540,9 @@ async def retrieval_telemetry( `gates` — every time a Grimoire gate stood in front of a tool call, from `gate_stops`, as the plugin hook that made the stop reported it. In `by_gate`, for each of `enforce` and `hold` (a moment rule's - enforcement), `checkpoint` (the act checkpoint on a command) and - `fence` (the project fence asking the operator), it gives: + enforcement), `checkpoint` (the act checkpoint on a command), `fence` + (the project fence asking the operator) and `reply` (a rule holding the + finished reply for one read), it gives: - `stops`: calls denied or put to the operator; - `cleared`: stops the session cleared by opening the rule, which is how a hold is meant to clear; diff --git a/src/grimoire/models/gate_stop.py b/src/grimoire/models/gate_stop.py index 588bad1a..c59fbef4 100644 --- a/src/grimoire/models/gate_stop.py +++ b/src/grimoire/models/gate_stop.py @@ -11,7 +11,8 @@ ENFORCE = "enforce" # a moment rule set to enforce: refused every time 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 -GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE) +REPLY = "reply" # a rule holding the finished reply for one read +GATES = (ENFORCE, HOLD, CHECKPOINT, FENCE, REPLY) # What the hook did with it. STOPPED = "stopped" # the call was denied, the reason shown instead @@ -23,8 +24,9 @@ OUTCOMES = (STOPPED, LET_THROUGH, ASKED) class GateStop(Base): """One time a Grimoire gate stood in front of a tool call. - WHY IT EXISTS. A rule set to enforce or hold, the act checkpoint and the - project fence are the only places Grimoire stops work rather than + WHY IT EXISTS. A rule set to enforce or hold, the act checkpoint, the + project fence and the hold on a finished reply (the Stop hook, `tool` = + "reply") are the only places Grimoire stops work rather than commenting on it, and a stop that fires at the wrong moment costs a round trip every time. Whether the plugin actually stops a call is decided client-side (the per-rule and per-session caps in diff --git a/src/grimoire/routes/plugin.py b/src/grimoire/routes/plugin.py index 817a8a73..06913dcc 100644 --- a/src/grimoire/routes/plugin.py +++ b/src/grimoire/routes/plugin.py @@ -624,7 +624,9 @@ async def reply_rules(): holds once, and the per-session cap counts these). Returns `reason` — the words the hook blocks with, empty when nothing - holds — plus `rule_ids` for the hook's ledger, `moments` reached and + holds — plus `rule_ids` for the hook's ledger, `rule_at` beside them + (where each was reached, which the hook reports with the hold), + `moments` reached and `report_check` (the recorded outcome, or "" when nothing was checked). """ data = await request.get_json(silent=True) or {} @@ -656,6 +658,7 @@ async def reply_rules(): return jsonify({ "reason": "\n\n".join(reasons), "rule_ids": held.get("rule_ids", []), + "rule_at": held.get("rule_at", []), "moments": held.get("moments", []), "report_check": checked.get("outcome", ""), }) diff --git a/src/grimoire/services/moment_delivery.py b/src/grimoire/services/moment_delivery.py index 58f0e7f4..49933966 100644 --- a/src/grimoire/services/moment_delivery.py +++ b/src/grimoire/services/moment_delivery.py @@ -406,7 +406,7 @@ async def reply_hold( holds a session once. Past the act checkpoint's per-session cap nothing holds — a mis-set bar degrades to a quiet session, never a stuck one. - Returns {} or {"reason", "rule_ids", "moments"}. Fails open to {}. + Returns {} or {"reason", "rule_ids", "rule_at", "moments"}. Fails open to {}. """ from grimoire.services import plugin_context as pc from grimoire.services import rule_usage, rulebooks @@ -470,6 +470,10 @@ async def reply_hold( return { "reason": reply_hold_reason(out), "rule_ids": [item["rule_id"] for item in out], + # Where each held rule was reached, beside `rule_ids`: the moment + # it is mounted on, or the reply arm that matched it. The hook + # reports each hold with it (`gate_stops`). + "rule_at": [item.get("moment") or rp.REPLY_RULE.source for item in out], "moments": names, } except Exception: # noqa: BLE001 - a recall aid never stops a session by failing diff --git a/tests/test_gate_stop_hooks.py b/tests/test_gate_stop_hooks.py index d5b49a79..63a8a0f5 100644 --- a/tests/test_gate_stop_hooks.py +++ b/tests/test_gate_stop_hooks.py @@ -23,6 +23,7 @@ FENCE = HOOKS / "grimoire_project_fence.sh" FENCE_RAN = HOOKS / "grimoire_fence_ran.sh" STOP = "/api/plugin/gate-stop" RAN = "/api/plugin/gate-ran" +REPLY_CHECK = HOOKS / "grimoire_reply_check.sh" TOOLS = {"/api/plugin/moment-tools": b'{"tools":["bash"]}'} @@ -194,3 +195,41 @@ def test_the_after_call_hook_is_registered_only_after_calls_and_on_the_fenced_to for h in m["hooks"] if "grimoire_project_fence.sh" in h["command"]] assert matchers("PreToolUse") == [] assert matchers("PostToolUse") == fence_pre + + +# ── the reply hold ─────────────────────────────────────────────────────── + +def _transcript(tmp_path, reply): + lines = [ + {"type": "user", "message": {"role": "user", "content": "is it finished?"}}, + {"type": "assistant", "message": {"content": [{"type": "text", "text": reply}]}}, + ] + path = tmp_path / "t.jsonl" + path.write_text("\n".join(json.dumps(x, separators=(",", ":")) for x in lines) + "\n") + return path + + +def _stop(tmp_path, transcript): + return {"session_id": "s-gate", "transcript_path": str(transcript), "cwd": str(tmp_path), + "hook_event_name": "Stop", "stop_hook_active": False} + + +def test_each_rule_that_holds_a_reply_is_reported_with_where_it_was_reached(tmp_path): + held = json.dumps({"reason": "Held for one read.", "rule_ids": [11, 40], + "rule_at": ["reply.report", "reply_rule"], + "moments": ["reply.report"]}).encode() + with http_sink(by_path={"/api/plugin/reply-rules": held}) as (port, seen): + out = _run(REPLY_CHECK, tmp_path, port, _stop(tmp_path, _transcript(tmp_path, "All done."))) + assert json.loads(out)["decision"] == "block" + assert [(s["gate"], s["outcome"], s["tool"], s["rule_id"], s["at"]) for s in _stops(seen)] == [ + ("reply", "stopped", "reply", 11, "reply.report"), + ("reply", "stopped", "reply", 40, "reply_rule"), + ] + + +def test_a_section_hold_names_no_rule_and_reports_no_gate_stop(tmp_path): + """The completion-section check has its own record (`report_check`).""" + sections = b'{"reason":"Add the sections.","rule_ids":[],"moments":[],"report_check":"blocked"}' + with http_sink(by_path={"/api/plugin/reply-rules": sections}) as (port, seen): + _run(REPLY_CHECK, tmp_path, port, _stop(tmp_path, _transcript(tmp_path, "All done."))) + assert _stops(seen) == [] diff --git a/tests/test_reply_moment.py b/tests/test_reply_moment.py index 0ac94d3f..7687150f 100644 --- a/tests/test_reply_moment.py +++ b/tests/test_reply_moment.py @@ -123,6 +123,9 @@ async def test_the_semantic_backstop_holds_and_never_names_a_mounted_rule_twice( arm, _surfaced, _lookup, stack = _stubs(mounted=[(DONE, "reply.report")], checkpoint=cp) out = await _hold(stack) assert out["rule_ids"] == [11, 40] + # Where each was reached, for the hook's gate report: a mount names its + # moment, the backstop names its arm. + assert out["rule_at"] == ["reply.report", rp.REPLY_RULE.source] assert "scores 0.84 against this reply" in out["reason"] spec, moment = arm.await_args.args assert spec is rp.REPLY_RULE @@ -207,7 +210,7 @@ async def test_the_route_passes_the_reply_and_all_three_ledgers(): with patch.object(routes.moment_delivery_svc, "reply_hold", hold): resp = await routes.reply_rules.__wrapped__() body = await resp.get_json() - assert body == {"reason": "Held.", "rule_ids": [11], "moments": ["reply.report"], + assert body == {"reason": "Held.", "rule_ids": [11], "rule_at": [], "moments": ["reply.report"], "report_check": ""} assert hold.await_args.args == (7, "done") assert hold.await_args.kwargs == { @@ -304,11 +307,12 @@ def test_the_hook_blocks_in_the_servers_words_and_records_the_hold(tmp_path): out = json.loads(_run(tmp_path, port, t)) _run(tmp_path, port, t) assert out == {"decision": "block", "reason": "Held for one read: get_rule(11)."} - sent = json.loads(seen[0]["_body"]) + asks = [e for e in seen if e["_path"] == "/api/plugin/reply-rules"] + sent = json.loads(asks[0]["_body"]) assert sent["reply"] == "All done.\nLet me know if it works on your end?" # The second turn tells the server what already held. - assert seen[1]["stopped_rule_ids"] == ["11"] - assert seen[1]["exclude_rule_ids"] == ["11"] + assert asks[1]["stopped_rule_ids"] == ["11"] + assert asks[1]["exclude_rule_ids"] == ["11"] def _closing_transcript(tmp_path, *replies):