Files
FabledGrimoire/plugin/hooks/grimoire_tool_rules.sh
T
bvandeusenandClaude Opus 5.5 65f1be80b6 feat(8141): every gate that stops a tool call is recorded, with what followed
A rule set to enforce or hold, the act checkpoint and the project fence
stopped work and left no record. The hook that makes each stop now reports
it to POST /api/plugin/gate-stop; the hook decides, not the server, because
the per-rule and per-session caps are kept in the plugin.

- gate_stops table (migration 0138): gate, outcome (stopped / let_through /
  asked), rule, where it was reached, tool, target project, call id.
- An open of the rule stamps the stop as cleared (rule-opened). A fenced
  call that then runs stamps ran: grimoire_fence_ran.sh, a PostToolUse on
  the fenced tools, matches the call id the fence left pending. That is
  the operator's yes.
- A hold or checkpoint the spent session budget lets through is reported
  as let_through; the per-rule once is not.
- The readout: by gate and by rule, stops, cleared by a read, misfired
  (rule_misfired after it), let through by the cap, ran. In
  retrieval_telemetry as `gates`, at /api/retrieval/gate-stops, and on the
  Moments settings page ("When a rule stopped the work").
- act_decision carries `at`, the moment the deciding rule was reached at.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:12:14 -05:00

177 lines
8.7 KiB
Bash

#!/usr/bin/env bash
# Grimoire — PreToolUse rule arm for ACTIONS.
#
# The sibling of grimoire_prior_art.sh. That hook is registered on Write|Edit and
# asks "what is recorded about the file being written". This one asks "does a
# standing rule speak to the command about to be run" — which is how a rule
# about which tool to reach for arrives at all.
#
# WHY A HOOK AND NOT AN INSTRUCTION. A reflex generates no query:
# you reach for `curl` confidently, with no moment of doubt, so a surface that
# waits to be asked never fires. Here nothing is asked — the tool call IS the
# query, and the reflex has to become a tool call before it can do anything.
#
# SILENT ON OUTAGE, deliberately, unlike the prior-art hook. A write is
# occasional; a Bash call is not, and an "instance did not answer" line before
# every command is the noise that gets a channel muted. grimoire_prior_art.sh
# still speaks for both when the instance is down.
#
# Env:
# GRIMOIRE_URL / GRIMOIRE_TOKEN override for the settings.json dogfooding path.
command -v curl >/dev/null 2>&1 || exit 0
# Sourced FIRST, because the JSON reader below lives there. It defines
# functions and clears `url`/`token`; nothing here runs before it is needed.
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
# PreToolUse delivers { session_id, cwd, tool_name, tool_input: {...}, ... }
event=$(cat 2>/dev/null || true)
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
tool_name=$(grimoire_json_pick "$event_flat" '.tool_name')
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
event_cwd=$(grimoire_json_pick "$event_flat" '.cwd')
[ -n "$tool_name" ] || exit 0
# The action, as text. `.command` is Bash's field; the fallbacks let the matcher
# in hooks.json widen to other tools without this script changing — which is the
# whole reason the server side takes a name and a string rather than a schema.
command_text=$(grimoire_json_pick "$event_flat" '.tool_input.command')
[ -n "$command_text" ] || command_text=$(grimoire_json_pick "$event_flat" '.tool_input.url')
[ -n "$command_text" ] || command_text=$(grimoire_json_pick "$event_flat" '.tool_input.prompt')
[ -n "$command_text" ] || exit 0
# grimoire_config, not a hand-rolled pair of parameter expansions: it also treats
# an UNEXPANDED `${...}` placeholder as unset, which would otherwise be sent as
# a garbage Bearer token and 401 on every call.
grimoire_config || exit 0
# Bounded before encoding: a heredoc or a pasted script can be enormous, and
# the verb and its target — the part a rule is about — sit at the front. The
# server bounds it again; this keeps a huge payload off the wire in the first
# place. `head -c`, never `cut -c`: cut truncates each LINE and caps nothing.
command_text=$(printf '%s' "$command_text" | head -c 2000)
# Whole, never line by line: per-line encoding joins a multi-line command with
# raw newlines — an invalid URL.
# grimoire_urlenc reads bytes and has no notion of a line.
cmd_enc=$(printf '%s' "$command_text" | grimoire_urlenc)
tool_enc=$(printf '%s' "$tool_name" | grimoire_urlenc)
[ -n "$cmd_enc" ] && [ -n "$tool_enc" ] || exit 0
repo_q=""
lookup_dir=${event_cwd:-${CLAUDE_PROJECT_DIR:-$PWD}}
scope=$(grimoire_scope_query "$lookup_dir")
[ -n "$scope" ] && repo_q="&${scope}"
# Where the command runs, against the repo's root: the paths a
# command names are relative to its cwd or absolute, and a System's patterns
# are relative to the root. The server does the arithmetic; this sends both.
where_q=""
repo_root=$(git -C "$lookup_dir" rev-parse --show-toplevel 2>/dev/null || true)
if [ -n "$repo_root" ]; then
where_q="&root=$(printf '%s' "$repo_root" | grimoire_urlenc)&cwd=$(printf '%s' "$lookup_dir" | grimoire_urlenc)"
fi
# THE SHARED SESSION LEDGER, and the thing most worth getting right here.
#
# grimoire_prior_art.sh keeps the rules it has already named in
# <state>/<sid>.rules.ids and passes them as exclude_rule_ids. This hook reads
# and appends to that SAME file rather than keeping its own: two ledgers would
# mean a rule named by one arm gets re-offered by the other, and the hint that
# fires most often is exactly the one that must not repeat itself.
#
# The directory keeps the prior-art name on purpose — renaming it would orphan
# every live session's state for a cosmetic gain.
state_dir="${TMPDIR:-/tmp}/grimoire-priorart"
mkdir -p "$state_dir" 2>/dev/null || true
rulefile=""
rule_exclude_q=""
rulingsfile=""
rulings_q=""
if [ -n "$session_id" ]; then
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
rulefile="$state_dir/${safe_sid}.rules.ids"
# Ageing, not a flat read: an id named two hours ago is not one the
# session is still holding. grimoire_rules_live carries the reasoning.
rule_seen=$(grimoire_rules_live "$rulefile")
[ -n "$rule_seen" ] && rule_exclude_q="&exclude_rule_ids=${rule_seen}"
# What the session actually OPENED, as against what it was shown.
rule_exclude_q="${rule_exclude_q}$(grimoire_held_query "$state_dir/${safe_sid}.opened.ids")"
# Which session the rule lines go to, so each is recorded as a delivery.
rule_exclude_q="${rule_exclude_q}&session_id=${safe_sid}"
# The Systems whose rulings were shown in full — shared with the write-path
# hook, for the reason the rule file is.
rulingsfile="$state_dir/${safe_sid}.rulings.ids"
rulings_q=$(grimoire_rulings_query "$rulingsfile")
fi
# `|| exit 0` here, unlike the prior-art hook: there is no local arm whose
# finding would be discarded, and an outage line before every command is worse
# than silence. See the header.
body=$(curl -fsS --max-time 5 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
"${url%/}/api/plugin/tool-rules?tool=${tool_enc}&command=${cmd_enc}${repo_q}${where_q}${rule_exclude_q}${rulings_q}" 2>/dev/null) || exit 0
body_flat=$(printf '%s' "$body" | grimoire_json_flat)
context=$(grimoire_json_pick "$body_flat" '.context')
# Remember what was named so it is not repeated this session. BEFORE the
# checkpoint branch and before the empty-context exit: the ledger records what
# the server chose to surface, which happened whichever way this hook then
# renders it. Doing it inside one branch is how the two arms' ledgers came to
# disagree once already.
if [ -n "$rulefile" ]; then
grimoire_json_list "$body_flat" '.rule_ids' | grimoire_rules_append "$rulefile"
fi
if [ -n "$rulingsfile" ]; then
grimoire_json_list "$body_flat" '.ruling_system_ids' >> "$rulingsfile" || true
fi
# ── The pre-act checkpoint ───────────────────────────────────────────────
#
# WHY THIS ARM AND NOT THE WRITE PATH. grimoire_prior_art.sh carries an explicit,
# tested property that it never returns a permissionDecision — a recall aid may
# not stand in the way of a write, which is the operator's decision and is
# guarded by test_hook_never_returns_a_permission_decision. No equivalent
# decision covers this arm, and the command-side misses are the ones a stop
# actually reaches: a commit message asserting what CI said, a verification
# script that checks nothing.
#
# WHAT THE STOP IS FOR. Everything else this plugin emits is additionalContext,
# which Claude Code delivers alongside the tool RESULT — so the rule is read
# after the call is written and reads as commentary on a decision already made.
# A deny returns the reason to the
# model with the call unrun, so the rule's own text can be read before the act
# exists. It costs the operator nothing: no prompt reaches them, and the model
# clears it by reading one record and re-submitting.
#
# It cannot recur. `grimoire_checkpoint_allowed` holds at most one act per rule
# and at most five per session, so the worst case of a mis-set floor is a noisy
# session rather than one that cannot move.
#
# Each stop is reported to the server, and so is a checkpoint the session's
# budget let through: the cap is decided here, so only this hook knows.
cp_rule=$(grimoire_json_pick "$body_flat" '.checkpoint.rule_id')
cp_reason=$(grimoire_json_pick "$body_flat" '.checkpoint.reason')
if [ -n "$cp_rule" ] && [ -n "$cp_reason" ] && [ -n "$session_id" ]; then
stops="$state_dir/${safe_sid}.checkpoint.ids"
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
if grimoire_checkpoint_allowed "$stops" "$cp_rule"; then
grimoire_json_deny PreToolUse "$cp_reason"
grimoire_gate_report "$session_id" checkpoint stopped "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id"
exit 0
fi
if grimoire_checkpoint_spent "$stops" "$cp_rule"; then
grimoire_gate_report "$session_id" checkpoint let_through "$tool_name" "$cp_rule" pre_tool_rule "" "$call_id"
fi
fi
[ -n "$context" ] || exit 0
grimoire_json_out PreToolUse "$context"
exit 0