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>
This commit is contained in:
2026-11-27 14:12:14 -05:00
co-authored by Claude Opus 5.5
parent 706f49a12a
commit 65f1be80b6
24 changed files with 1128 additions and 13 deletions
+49
View File
@@ -0,0 +1,49 @@
"""gate stops: each time a Grimoire gate stood in front of a tool call
Revision ID: 0138
Revises: 0137
Create Date: 2026-11-27
A row per stop the plugin made: a moment rule set to enforce or hold, the
act checkpoint, or the project fence asking the operator. With whether the
session then opened the rule (`cleared_at`) and whether the stopped call ran
after all (`ran_at`), so how often each gate stops work, for which rule, and
whether it cleared the way it is meant to can be read.
"""
import sqlalchemy as sa
from alembic import op
revision = "0138"
down_revision = "0137"
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table(
"gate_stops",
sa.Column("id", sa.BigInteger(), primary_key=True),
sa.Column("user_id", sa.BigInteger(), nullable=False),
sa.Column("session_id", sa.Text(), nullable=False),
sa.Column("gate", sa.Text(), nullable=False),
sa.Column("outcome", sa.Text(), nullable=False),
sa.Column("rule_id", sa.BigInteger(), nullable=True),
sa.Column("tool", sa.Text(), nullable=False),
sa.Column("at", sa.Text(), nullable=True),
sa.Column("target", sa.Text(), nullable=True),
sa.Column("call_id", sa.Text(), nullable=True),
sa.Column("stopped_at", sa.DateTime(timezone=True), nullable=False,
server_default=sa.func.now()),
sa.Column("cleared_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("ran_at", sa.DateTime(timezone=True), nullable=True),
sa.Column("plugin", sa.Text(), nullable=True),
)
op.create_index("ix_gate_stops_session_rule", "gate_stops",
["user_id", "session_id", "rule_id", "stopped_at"])
op.create_index("ix_gate_stops_stopped_at", "gate_stops", ["stopped_at"])
def downgrade() -> None:
op.drop_index("ix_gate_stops_stopped_at", table_name="gate_stops")
op.drop_index("ix_gate_stops_session_rule", table_name="gate_stops")
op.drop_table("gate_stops")
+42
View File
@@ -340,6 +340,48 @@ export function getRecordReach(days = 30): Promise<RecordReachPayload> {
return apiGet(`/api/retrieval/record-reach?days=${days}`);
}
/** The gates that can stop a tool call. */
export type GateName = "enforce" | "hold" | "checkpoint" | "fence";
export interface GateCounts {
/** Calls denied, or for the fence, put to the operator. */
stops: number;
/** Calls a hold would have stopped, let through because the session's
* stop budget was spent. */
let_through: number;
/** Stops the session cleared by opening the rule. */
cleared: number;
/** Stops whose rule the session then reported as a misfire. */
misfired: number;
/** Stopped calls that ran after all; for the fence, the operator's yes. */
ran: number;
}
export interface GateRuleRow extends GateCounts {
rule_id: number;
gate: GateName;
/** The moment or arm the rule was reached at. */
at: string | null;
title: string | null;
sessions: number;
last_stopped_at: string | null;
}
export interface GateStopsPayload {
days: number;
by_gate: Record<GateName, GateCounts & { sessions: number }>;
by_rule: GateRuleRow[];
fence: { tool: string; target: string | null; asks: number; ran: number }[];
/** The first stop ever recorded; null when none has been. */
complete_from: string | null;
covers_window: boolean | null;
}
/** How often each gate stood in front of a tool call, and what followed. */
export function getGateStops(days = 30): Promise<GateStopsPayload> {
return apiGet(`/api/retrieval/gate-stops?days=${days}`);
}
/** Whether the rules in force at each moment were followed there. */
export function getAdherence(days = 30): Promise<AdherencePayload> {
return apiGet(`/api/retrieval/adherence?days=${days}`);
+121
View File
@@ -0,0 +1,121 @@
<script setup lang="ts">
import { computed } from "vue";
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
* 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
* spent.
*/
const props = defineProps<{
data: GateStopsPayload | null;
failed: boolean;
}>();
const emit = defineEmits<{ retry: [] }>();
const GATES: [GateName, string][] = [
["enforce", "Refused (enforce)"],
["hold", "Held for a read (hold)"],
["checkpoint", "Command checkpoint"],
["fence", "Project fence"],
];
const any = computed(() =>
!!props.data && GATES.some(([g]) => (props.data!.by_gate[g]?.stops ?? 0) + (props.data!.by_gate[g]?.let_through ?? 0) > 0),
);
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}`);
return parts;
}
</script>
<template>
<section class="gates" aria-labelledby="gates-title">
<h3 id="gates-title" class="sub-title">When a rule stopped the work</h3>
<p v-if="failed" class="error-msg">
Gate stops could not be loaded.
<button type="button" class="btn-text" @click="emit('retry')">Try again</button>
</p>
<p v-else-if="!data" class="empty-msg">Loading gate stops…</p>
<p v-else-if="!any" class="empty-msg">
No gate stopped a tool call in the last {{ data.days }} days.
<template v-if="data.complete_from === null">
None has ever been recorded: a session reports its stops once its plugin is updated.
</template>
</p>
<template v-else>
<p class="field-hint">
Over the last {{ data.days }} days. “Cleared by a read” means the session opened the rule
after the stop; “misfired” means it then reported the rule as not applying there; “let
through by the cap” counts calls a hold would have stopped once the session’s budget of
stops was spent.
<template v-if="data.covers_window === false">
Recording began {{ fmtDate(data.complete_from!) }}, so earlier days are missing, not quiet.
</template>
</p>
<ul class="gate-list">
<li v-for="[gate, label] in GATES" :key="gate" class="gate-row">
<span class="gate-title">{{ label }}</span>
<span class="gate-counts" :class="{ 'way-none': !data.by_gate[gate]?.stops && !data.by_gate[gate]?.let_through }">
<span v-for="t in gateText(gate, data.by_gate[gate])" :key="t">{{ t }}</span>
</span>
</li>
</ul>
<details v-if="data.by_rule.length" class="gate-detail">
<summary>By rule</summary>
<ul class="gate-list">
<li v-for="r in data.by_rule" :key="`${r.rule_id}:${r.gate}:${r.at}`" class="gate-row">
<span class="gate-title">
Rule {{ r.rule_id }}<template v-if="r.title"> “{{ r.title }}”</template>
</span>
<code class="moment-name">{{ r.gate }}<template v-if="r.at"> · {{ r.at }}</template></code>
<span class="gate-counts">
<span v-for="t in gateText(r.gate, r)" :key="t">{{ t }}</span>
<span>{{ r.sessions }} {{ r.sessions === 1 ? "session" : "sessions" }}</span>
<span v-if="r.last_stopped_at" class="stat-when">last {{ fmtDate(r.last_stopped_at) }}</span>
</span>
</li>
</ul>
</details>
<details v-if="data.fence.length" class="gate-detail">
<summary>Fence asks by tool</summary>
<ul class="gate-list">
<li v-for="f in data.fence" :key="`${f.tool}:${f.target}`" class="gate-row">
<code class="moment-name">{{ f.tool }}</code>
<span v-if="f.target" class="gate-title">into project {{ f.target }}</span>
<span class="gate-counts">
<span>asked {{ f.asks }}</span>
<span>approved {{ f.ran }}</span>
</span>
</li>
</ul>
</details>
</template>
</section>
</template>
<style scoped>
.gates { display: flex; flex-direction: column; gap: var(--fs-space-2); }
.sub-title { margin: 0; font-size: 0.95rem; color: var(--fs-text-primary); }
.gate-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: var(--fs-space-1); }
.gate-detail .gate-list { margin: var(--fs-space-1) 0 var(--fs-space-2) var(--fs-space-4); }
.gate-detail summary { cursor: pointer; font-size: var(--fs-size-body-sm); color: var(--fs-text-secondary); }
.gate-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: var(--fs-space-2); }
.gate-title { font-size: var(--fs-size-body-sm); color: var(--fs-text-primary); }
.gate-counts {
display: inline-flex; flex-wrap: wrap; gap: var(--fs-space-2); margin-left: auto; justify-content: flex-end;
font-size: var(--fs-size-tiny); color: var(--fs-text-secondary); font-variant-numeric: tabular-nums;
}
/* A gate that stopped nothing is a gap, not a zero to read. */
.way-none { color: var(--fs-text-tertiary); }
</style>
<style src="@/assets/moments-shared.css" />
+20 -3
View File
@@ -7,9 +7,12 @@ import WeightProposals from "@/components/WeightProposals.vue";
import LessonSituationProposals from "@/components/LessonSituationProposals.vue";
import RecordKinds from "@/components/RecordKinds.vue";
import RecordReach from "@/components/RecordReach.vue";
import GateStops from "@/components/GateStops.vue";
import RuleAdherence from "@/components/RuleAdherence.vue";
import { getAdherence, getRecordReach } from "@/api/moments";
import type { AdherencePayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload } from "@/api/moments";
import { getAdherence, getGateStops, getRecordReach } from "@/api/moments";
import type {
AdherencePayload, GateStopsPayload, MomentAction, MomentAdherenceRow, MomentUsage, RecordReachPayload,
} from "@/api/moments";
import { fmtDate } from "@/utils/dateFormat";
/**
@@ -65,6 +68,19 @@ async function loadReach() {
}
}
// When a gate stopped a tool call, read on its own for the same reason.
const gates = ref<GateStopsPayload | null>(null);
const gatesFailed = ref(false);
async function loadGates() {
try {
gates.value = await getGateStops(days.value);
gatesFailed.value = false;
} catch {
gatesFailed.value = true;
}
}
function followed(moment: string): MomentAdherenceRow | null {
return adherence.value?.by_moment.find((m) => m.at === moment) ?? null;
}
@@ -145,7 +161,7 @@ async function addMapping() {
onMounted(async () => {
await store.load(true);
await Promise.all([loadAdherence(), loadReach()]);
await Promise.all([loadAdherence(), loadReach(), loadGates()]);
});
</script>
@@ -174,6 +190,7 @@ onMounted(async () => {
<WeightProposals />
<LessonSituationProposals />
<RuleAdherence :data="adherence" :failed="adherenceFailed" @retry="loadAdherence" />
<GateStops :data="gates" :failed="gatesFailed" @retry="loadGates" />
<RecordReach :data="reach" :failed="reachFailed" @retry="loadReach" />
<RecordKinds :days="days" />
+4 -3
View File
@@ -38,9 +38,10 @@ another one means adding files, not moving or rewriting any.
| `hooks/grimoire_autoinject.sh` | UserPromptSubmit: `GET /api/plugin/retrieve` for the message. |
| `hooks/grimoire_prior_art.sh` | PreToolUse on editor writes: `GET /api/plugin/prior-art`. |
| `hooks/grimoire_after_write.sh` | PostToolUse on shell commands: the same check for code written through the shell. |
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`. |
| `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; PostToolUse on `enter_project` remembers the project a session without one entered. |
| `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). |
| `hooks/grimoire_tool_rules.sh` | PreToolUse on shell commands: `GET /api/plugin/tool-rules`; denies the call on its `checkpoint`, under the same caps, and reports it to `POST /api/plugin/gate-stop`. |
| `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_shape_check.sh` | Stop: sends the definitions the turn wrote (the write hooks' `<sid>.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`. |
+46
View File
@@ -1081,6 +1081,52 @@ grimoire_checkpoint_allowed() {
return 0
}
grimoire_gate_report() {
# $1 session id, $2 gate (enforce|hold|checkpoint|fence), $3 outcome
# (stopped|let_through|asked), $4 tool name, $5 rule id or "", $6 where the
# rule was reached (a moment or an arm) or "", $7 the target project or "",
# $8 the tool call's id or "".
#
# Tells the server a gate stood in front of this call. The hook reports it,
# not the server, because whether a hold actually stops is decided here, by
# `grimoire_checkpoint_allowed`'s caps. Needs `url`, `token` and
# `plugin_version` from grimoire_config. Short deadline and silent: it runs
# only on a stop, and a stop the server never heard of costs one row, while
# a hook that hangs costs the call it was deciding.
local sid="${1:-}" gate="${2:-}" outcome="${3:-}" tool="${4:-}" rule rest="" v pair
[ -n "$sid" ] && [ -n "$gate" ] && [ -n "$outcome" ] && [ -n "$tool" ] || return 0
[ -n "${url:-}" ] && [ -n "${token:-}" ] || return 0
command -v curl >/dev/null 2>&1 || return 0
rule=$(printf '%s' "${5:-}" | tr -cd '0-9')
for pair in "at=${6:-}" "target=${7:-}" "call_id=${8:-}"; do
v=${pair#*=}
[ -n "$v" ] || continue
rest="${rest},\"${pair%%=*}\":\"$(printf '%s' "$v" | grimoire_json_escape)\""
done
printf '{"session_id":"%s","gate":"%s","outcome":"%s","tool":"%s","rule_id":%s%s}' \
"$(printf '%s' "$sid" | grimoire_json_escape)" "$gate" "$outcome" \
"$(printf '%s' "$tool" | grimoire_json_escape)" "${rule:-null}" "$rest" \
| curl -fsS --max-time 2 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/gate-stop" >/dev/null 2>&1 || true
return 0
}
grimoire_checkpoint_spent() {
# $1 ledger file, $2 rule id. True when `grimoire_checkpoint_allowed` just
# refused because the SESSION's budget is spent, as against this rule
# having held an act already. Only the first is a call the cap let through;
# the second is the per-rule once, working as meant.
local f="$1" id
id=$(printf '%s' "${2:-}" | tr -cd '0-9')
[ -n "$f" ] && [ -n "$id" ] && [ -f "$f" ] || return 1
grep -qx "$id" "$f" 2>/dev/null && return 1
return 0
}
grimoire_json_deny() {
# $1 hook event name, $2 the reason the agent reads INSTEAD of the result.
#
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Grimoire — the operator's answer to a project fence ask, read from what ran.
#
# grimoire_project_fence.sh asks the operator before an act lands in another
# project, reports the ask to the server, and leaves the tool call's id in
# `grimoire-fence/<sid>.fence.pending`. The answer itself never reaches a
# hook, but Claude Code sends PostToolUse only for a call that ran. So when
# this fires for the pending call, the operator said yes, and the server is
# told (POST /api/plugin/gate-ran). An ask that is never followed by this was
# declined, or the call failed.
#
# Registered PostToolUse on the tools the fence checks. Nearly every call has
# no ask pending, so the first thing it does is look for a pending file, and
# with none it exits before reading the event.
#
# EXIT 0, ALWAYS, and silent: it decorates a record.
set -uo pipefail
fence_dir="${TMPDIR:-/tmp}/grimoire-fence"
pending=""
for pending in "$fence_dir"/*.fence.pending; do
[ -e "$pending" ] && break
done
[ -e "$pending" ] || exit 0
# shellcheck source=plugin/hooks/grimoire_defs.sh
. "$(dirname "${BASH_SOURCE[0]}")/grimoire_defs.sh"
event=$(cat 2>/dev/null || true)
[ -n "$event" ] || exit 0
event_flat=$(printf '%s' "$event" | grimoire_json_flat)
session_id=$(grimoire_json_pick "$event_flat" '.session_id')
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
[ -n "$session_id" ] && [ -n "$call_id" ] || exit 0
safe_sid=$(printf '%s' "$session_id" | tr -c 'A-Za-z0-9._-' '_')
pending_file="$fence_dir/${safe_sid}.fence.pending"
[ -s "$pending_file" ] || exit 0
[ "$(cat "$pending_file" 2>/dev/null)" = "$call_id" ] || exit 0
rm -f "$pending_file" 2>/dev/null || true
grimoire_config || exit 0
command -v curl >/dev/null 2>&1 || exit 0
printf '{"session_id":"%s","call_id":"%s"}' \
"$(printf '%s' "$session_id" | grimoire_json_escape)" \
"$(printf '%s' "$call_id" | grimoire_json_escape)" \
| curl -fsS --max-time 2 \
-H "Authorization: Bearer ${token}" \
-H "X-Grimoire-Plugin: ${plugin_version:-}" \
-H "Content-Type: application/json" \
--data-binary @- \
"${url%/}/api/plugin/gate-ran" >/dev/null 2>&1 || true
exit 0
+13 -2
View File
@@ -160,21 +160,32 @@ grimoire_json_list "$body_flat" '.shape_keys' | grimoire_shapes_append "$shapefi
# before the act, once per rule and under the session cap that the act
# checkpoint and the reply hold share, so a mis-set rule costs one round trip
# rather than a session that cannot move.
#
# Every stop is reported (`grimoire_gate_report`), and so is a hold the
# session's budget let through, so how often each gate stops work, and
# whether the cap is what lets calls past, can be read on the server.
d_kind=$(grimoire_json_pick "$body_flat" '.decision.kind')
d_reason=$(grimoire_json_pick "$body_flat" '.decision.reason')
d_rule=$(grimoire_json_list "$body_flat" '.decision.rule_ids' | head -n 1)
d_at=$(grimoire_json_pick "$body_flat" '.decision.at')
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
if [ -n "$d_reason" ]; then
case "$d_kind" in
enforce)
grimoire_json_deny PreToolUse "$d_reason"
grimoire_gate_report "$session_id" enforce stopped "$tool_key" "$d_rule" "$d_at" "" "$call_id"
exit 0
;;
hold)
if [ -n "$d_rule" ] \
&& grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$d_rule"; then
stops="$state_dir/${safe_sid}.checkpoint.ids"
if [ -n "$d_rule" ] && grimoire_checkpoint_allowed "$stops" "$d_rule"; then
grimoire_json_deny PreToolUse "$d_reason"
grimoire_gate_report "$session_id" hold stopped "$tool_key" "$d_rule" "$d_at" "" "$call_id"
exit 0
fi
if [ -n "$d_rule" ] && grimoire_checkpoint_spent "$stops" "$d_rule"; then
grimoire_gate_report "$session_id" hold let_through "$tool_key" "$d_rule" "$d_at" "" "$call_id"
fi
;;
esac
fi
+18
View File
@@ -34,6 +34,12 @@
#
# Run as PostToolUse on enter_project, it records the project a session
# without one has entered, and says nothing.
#
# EVERY ASK IS REPORTED (POST /api/plugin/gate-stop), with the tool call's
# id, which is left in `<sid>.fence.pending`. The operator's answer never
# reaches a hook, but a PostToolUse arrives only for a call that ran, so
# grimoire_fence_ran.sh reports the matching call as run: the operator said
# yes. An ask with no run after it was declined, or the call failed.
set -uo pipefail
# shellcheck source=plugin/hooks/grimoire_defs.sh
@@ -56,6 +62,8 @@ cwd=$(grimoire_json_pick "$event_flat" '.cwd')
state_dir="${TMPDIR:-/tmp}/grimoire-fence"
safe_sid=$(printf '%s' "${session_id:-none}" | tr -c 'A-Za-z0-9._-' '_')
entered_file="$state_dir/${safe_sid}.entered"
pending_file="$state_dir/${safe_sid}.fence.pending"
call_id=$(grimoire_json_pick "$event_flat" '.tool_use_id')
# ── PostToolUse on enter_project: remember the first project entered ─────
if [ "$hook_event" = "PostToolUse" ]; then
@@ -238,6 +246,16 @@ while IFS= read -r check; do
reason=$(grimoire_json_pick "$flat" '.reason')
esc=$(printf '%s' "$reason" | grimoire_json_escape) || exit 0
printf '{"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"ask","permissionDecisionReason":"%s"}}\n' "$esc"
# The ask, and the call it is about, so the run that follows a yes can
# be matched to it. `at` is what the act was: the tool for a Grimoire
# call, the act phrase ("git push in") for a file or a git command.
if [ "$check" = "tool" ]; then fence_at="$short"; fence_tool="$short"; else fence_at="$act"; fence_tool="$tool_name"; fi
if [ -n "$call_id" ] && [ -n "$session_id" ]; then
mkdir -p "$state_dir" 2>/dev/null || true
printf '%s' "$call_id" > "$pending_file" 2>/dev/null || true
fi
grimoire_gate_report "$session_id" fence asked "$fence_tool" "" "$fence_at" \
"$(grimoire_json_pick "$flat" '.targets[0].id')" "$call_id"
exit 0
fi
done <<EOF
+10 -1
View File
@@ -153,13 +153,22 @@ fi
# 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
if grimoire_checkpoint_allowed "$state_dir/${safe_sid}.checkpoint.ids" "$cp_rule"; 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
+9
View File
@@ -116,6 +116,15 @@
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_project_fence.sh\""
}
]
},
{
"matcher": "Write|Edit|MultiEdit|NotebookEdit|Bash|mcp__.*grimoire.*",
"hooks": [
{
"type": "command",
"command": "bash \"${CLAUDE_PLUGIN_ROOT}/hooks/grimoire_fence_ran.sh\""
}
]
}
],
"PreCompact": [
+7
View File
@@ -402,6 +402,13 @@ SMOKE_EVENTS: dict[str, str] = {
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PreToolUse",
"tool_name": "mcp__grimoire__update_task", "tool_input": {"task_id": 1}}
),
# The fence's after-call half: with no ask pending it exits before
# reading anything, which is the case on nearly every call.
"grimoire_fence_ran.sh": json.dumps(
{"session_id": "smoke", "cwd": ".", "hook_event_name": "PostToolUse",
"tool_name": "Bash", "tool_use_id": "toolu_smoke",
"tool_input": {"command": "true"}, "tool_response": {}}
),
# The shared library is sourced, never run; executed bare it defines
# functions and exits — silent by construction.
"grimoire_defs.sh": "",
+21
View File
@@ -537,6 +537,27 @@ async def retrieval_telemetry(
pushed or by being asked for, which `usage` cannot: a pull there does not
say which door led to it. Counts only sessions whose plugin reports opens.
`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:
- `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;
- `misfired`: stops whose rule the session then reported with
`rule_misfired`, a stop at the wrong moment;
- `let_through`: calls a hold would have stopped, let through because
the session's stop budget was spent;
- `ran`: stopped calls that ran after all. For the fence that is the
operator's yes; an ask without it was declined, or the call failed.
`by_rule` gives the same per rule and place, most stops first. `fence`
gives the asks per tool and target project. Read `misfired` and
`let_through` before changing a rule's enforcement. A rule that stops
work and is then called a misfire has the wrong moment or trigger; a
budget that keeps letting calls through is spent on rules that stop
too often. `gates_failed: true` means the read broke.
`judged` — whether the lines RELATED, from `retrieval_judgments`:
per source, a reviewer's verdicts (`on_point` / `adjacent` / `unrelated`)
on a sample of logged menus, `within_budget` against `beyond_budget` and
+1
View File
@@ -63,6 +63,7 @@ from grimoire.models.rule_usage import RuleUsageEvent # noqa: E402, F401
from grimoire.models.rule_delivery import RuleDelivery # noqa: E402, F401
from grimoire.models.rule_adherence import RuleAdherence # noqa: E402, F401
from grimoire.models.record_delivery import RecordDelivery # noqa: E402, F401
from grimoire.models.gate_stop import GateStop # noqa: E402, F401
from grimoire.models.system_usage import SystemUsageEvent # noqa: E402, F401
from grimoire.models.retrieval_judgment import RetrievalJudgment # noqa: E402, F401
from grimoire.models.moment_mapping import MomentMapping # noqa: E402, F401
+88
View File
@@ -0,0 +1,88 @@
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, Index, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from grimoire.models import Base
from grimoire.models.base import iso
# The gates that can stop a tool call, as the plugin hooks name them.
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)
# What the hook did with it.
STOPPED = "stopped" # the call was denied, the reason shown instead
LET_THROUGH = "let_through" # would have held, but the session cap was spent
ASKED = "asked" # the fence put the call to the operator
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
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
`grimoire_checkpoint_allowed`), so the server's own decision is not the
record: the hook reports what it did, here.
`cleared_at` is stamped when the session opened the rule after the stop,
which is how a hold is meant to clear. `ran_at` is stamped when the
stopped call ran after all, which for the fence means the operator said
yes (the harness reports a PostToolUse only for a call that ran); the
tool call's own id (`call_id`) ties the two. A fence ask with no `ran_at`
was declined, or the call failed.
`at` is the moment the rule was reached at, or the arm that found it.
`target` is the project a fenced act would have landed in.
FK-free, like the other telemetry tables: the record that a rule kept
stopping work outlives the rule, since it is the case for changing it.
"""
__tablename__ = "gate_stops"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
user_id: Mapped[int] = mapped_column(BigInteger, nullable=False)
session_id: Mapped[str] = mapped_column(Text, nullable=False)
gate: Mapped[str] = mapped_column(Text, nullable=False)
outcome: Mapped[str] = mapped_column(Text, nullable=False)
rule_id: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
tool: Mapped[str] = mapped_column(Text, nullable=False)
at: Mapped[str | None] = mapped_column(Text, nullable=True)
target: Mapped[str | None] = mapped_column(Text, nullable=True)
call_id: Mapped[str | None] = mapped_column(Text, nullable=True)
stopped_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, server_default=func.now(),
)
cleared_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
ran_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
plugin: Mapped[str | None] = mapped_column(Text, nullable=True)
__table_args__ = (
Index("ix_gate_stops_session_rule", "user_id", "session_id", "rule_id", "stopped_at"),
Index("ix_gate_stops_stopped_at", "stopped_at"),
)
def to_dict(self) -> dict:
return {
"id": self.id,
"user_id": self.user_id,
"session_id": self.session_id,
"gate": self.gate,
"outcome": self.outcome,
"rule_id": self.rule_id,
"tool": self.tool,
"at": self.at,
"target": self.target,
"call_id": self.call_id,
"stopped_at": iso(self.stopped_at),
"cleared_at": iso(self.cleared_at),
"ran_at": iso(self.ran_at),
"plugin": self.plugin,
}
+53
View File
@@ -14,6 +14,7 @@ from quart import Blueprint, g, jsonify, request
from grimoire.auth import admin_required, get_current_user_id, login_required
from grimoire.config import Config
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
@@ -455,6 +456,10 @@ async def rule_opened():
await rule_deliveries_svc.mark_opened(
g.user.id, str(data.get("session_id") or ""), rule_id,
)
# And against the stop it cleared, when a gate had stopped a call on it.
await gate_stops_svc.mark_cleared(
g.user.id, str(data.get("session_id") or ""), rule_id,
)
acts = data.get("acts")
if rule_id <= 0 or not isinstance(acts, list) or not acts:
return jsonify({"moments": [], "context": ""})
@@ -465,6 +470,54 @@ async def rule_opened():
))
@plugin_bp.post("/gate-stop")
@login_required
async def gate_stop():
"""A hook stood in front of a tool call.
Body: `{"session_id", "gate", "outcome", "tool", "rule_id"?, "at"?,
"target"?, "call_id"?}`. `gate` is `enforce`, `hold`, `checkpoint` or
`fence`; `outcome` is `stopped` (denied), `let_through` (a hold the
session's stop budget no longer covered) or `asked` (put to the
operator). Posted by the hook that made the stop, since whether a hold
actually stops is decided by caps kept in the plugin. Answers
`{"recorded"}`.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"recorded": False})
try:
rule_id = int(data.get("rule_id") or 0)
except (TypeError, ValueError):
rule_id = 0
recorded = await gate_stops_svc.record(
g.user.id, str(data.get("session_id") or ""),
gate=str(data.get("gate") or ""), outcome=str(data.get("outcome") or ""),
tool=str(data.get("tool") or ""), rule_id=rule_id or None,
at=data.get("at"), target=data.get("target"), call_id=data.get("call_id"),
plugin=rule_deliveries_svc.current_plugin(),
)
return jsonify({"recorded": recorded})
@plugin_bp.post("/gate-ran")
@login_required
async def gate_ran():
"""A tool call a gate stood in front of ran after all.
Body: `{"session_id", "call_id"}`, posted after the call by the hook that
asked about it. For the project fence that is the operator's yes: the
harness reports a call only once it has run. Answers `{"recorded"}`.
"""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict):
return jsonify({"recorded": False})
recorded = await gate_stops_svc.mark_ran(
g.user.id, str(data.get("session_id") or ""), str(data.get("call_id") or ""),
)
return jsonify({"recorded": recorded})
@plugin_bp.post("/record-opened")
@login_required
async def record_opened():
+15
View File
@@ -21,6 +21,7 @@ from grimoire.auth import get_current_user_id, login_required
from grimoire.services import moment_actions as moment_actions_svc
from grimoire.services import moments as moments_svc
from grimoire.services import reply_shapes as shapes_svc
from grimoire.services import gate_stops as gate_stops_svc
from grimoire.services import record_deliveries as record_deliveries_svc
from grimoire.services import record_kinds as record_kinds_svc
from grimoire.services import rule_adherence as adherence_svc
@@ -306,6 +307,20 @@ async def record_reach_route():
return jsonify(await record_deliveries_svc.summary(get_current_user_id(), days=days))
@retrieval_bp.route("/gate-stops", methods=["GET"])
@login_required
async def gate_stops_route():
"""How often each gate stood in front of this user's tool calls: per gate
and per rule, stops, cleared by a read, reported as misfires, let through
once the session's stop budget was spent; and the project fence's asks
and how many then ran. `?days=` sets the window (default 30)."""
try:
days = int(request.args.get("days") or 30)
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
return jsonify(await gate_stops_svc.summary(get_current_user_id(), days=days))
@retrieval_bp.route("/weights/proposals", methods=["GET"])
@login_required
async def weight_proposals_route():
+3
View File
@@ -206,6 +206,9 @@ _NOT_INCLUDED = [
"rule_adherence",
# The same per-session ledger for every other record kind.
"record_deliveries",
# Each time a gate stopped a tool call, keyed by the same session ids and
# pruned with the deliveries.
"gate_stops",
# Verdicts on retrieval_logs rows, so they go where their subject
# goes: a restore that carried a judgment of a call it did not carry would
# leave a verdict on nothing. A sample, re-takeable by the review pass.
+217
View File
@@ -0,0 +1,217 @@
"""Each time a Grimoire gate stood in front of a tool call, and what followed.
Three calls, one table (`gate_stops`):
- `record` — from the plugin, the moment a hook stops a call (a moment rule
set to enforce or hold, the act checkpoint), lets one through because the
session's stop budget is spent, or puts one to the operator (the project
fence). The hook reports it, not the server's decision, because the caps
that decide whether a hold actually stops are kept client-side.
- `mark_cleared` — the session opened the rule after the stop: the latest
uncleared stop of it in that session gets the stamp. That is how a hold is
meant to clear.
- `mark_ran` — the stopped call ran after all, matched by its tool-call id.
For the fence that is the operator's yes.
`summary` reads it back per gate and per rule: how often each stops work,
how often a stop cleared by a read, how often the session then reported the
rule as a misfire, and how often the session cap let a call through.
Kept as long as rule deliveries (`rule_deliveries.RETAIN_DAYS`) and pruned
with them.
"""
from __future__ import annotations
import logging
from datetime import datetime, timedelta, timezone
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,
)
from grimoire.models.rule_adherence import MISFIRE, RuleAdherence
from grimoire.models.rulebook import Rule
from grimoire.services import rule_deliveries
logger = logging.getLogger(__name__)
# A field longer than this is not a tool name, a moment or a project id.
_FIELD_MAX = 200
# Rules listed in the readout, most stops first.
_BY_RULE_LIMIT = 25
def _field(value, limit: int = _FIELD_MAX) -> str | None:
text = str(value or "").strip()[:limit]
return text or None
async def record(
user_id: int, session_id: str | None, *, gate: str, outcome: str, tool: str,
rule_id: int | None = None, at: str | None = None, target: str | None = None,
call_id: str | None = None, plugin: str | None = None,
) -> bool:
"""One stop, as the hook made it. Returns whether a row was written: an
unknown gate or outcome, or a stop with no session, records nothing,
since nothing could later clear it."""
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:
return False
async with async_session() as session:
session.add(GateStop(
user_id=int(user_id), session_id=sid, gate=gate, outcome=outcome,
rule_id=int(rule_id) if rule_id else None, tool=_field(tool),
at=_field(at), target=_field(target), call_id=_field(call_id),
plugin=_field(plugin, 64),
))
await session.commit()
return True
async def mark_cleared(user_id: int, session_id: str | None, rule_id: int) -> bool:
"""Stamp the session's latest uncleared stop of this rule as cleared by a
read. A stop older than the open window was made to a context that is
gone, and stays uncleared."""
sid = rule_deliveries.clean_session(session_id)
if not sid or not rule_id:
return False
now = datetime.now(timezone.utc)
async with async_session() as session:
latest = (await session.execute(
select(GateStop.id).where(
GateStop.user_id == user_id, GateStop.session_id == sid,
GateStop.rule_id == int(rule_id), GateStop.cleared_at.is_(None),
GateStop.stopped_at >= now - rule_deliveries.OPEN_WINDOW,
).order_by(GateStop.stopped_at.desc(), GateStop.id.desc()).limit(1)
)).scalar_one_or_none()
if latest is None:
return False
await session.execute(update(GateStop).where(GateStop.id == latest).values(cleared_at=now))
await session.commit()
return True
async def mark_ran(user_id: int, session_id: str | None, call_id: str | None) -> bool:
"""Stamp the stop of this tool call as having run after all."""
sid = rule_deliveries.clean_session(session_id)
cid = _field(call_id)
if not sid or not cid:
return False
async with async_session() as session:
result = await session.execute(
update(GateStop).where(
GateStop.user_id == user_id, GateStop.session_id == sid,
GateStop.call_id == cid, GateStop.ran_at.is_(None),
).values(ran_at=datetime.now(timezone.utc))
)
await session.commit()
return bool(result.rowcount)
def _misfired():
"""Whether the session reported the stopped rule as a misfire."""
return exists().where(
RuleAdherence.user_id == GateStop.user_id,
RuleAdherence.session_id == GateStop.session_id,
RuleAdherence.rule_id == GateStop.rule_id,
RuleAdherence.source == MISFIRE,
)
def _count(cond):
return func.sum(case((cond, 1), else_=0))
async def summary(user_id: int, days: int = 30, *, since: datetime | None = None,
until: datetime | None = None) -> dict:
"""How often each gate stood in front of this user's tool calls over the
last `days`, or over [`since`, `until`).
`by_gate`: per gate, `stops` (calls denied, or put to the operator for
the fence), `let_through` (calls a hold would have stopped once the
session's stop budget was spent), `cleared` (stops the session cleared
by opening the rule), `misfired` (stops whose rule the session then
reported with `rule_misfired`), `ran` (stopped calls that ran after all:
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
recorded, so a window reaching further back says so.
"""
until = until or datetime.now(timezone.utc)
if since is None:
days = max(1, min(int(days or 30), rule_deliveries.RETAIN_DAYS))
since = until - timedelta(days=days)
else:
days = round((until - since).total_seconds() / 86400, 2)
window = and_(GateStop.user_id == user_id, GateStop.stopped_at >= since,
GateStop.stopped_at < until)
stopped = GateStop.outcome.in_((STOPPED, ASKED))
counts = (
_count(stopped),
_count(GateStop.outcome == LET_THROUGH),
_count(and_(stopped, GateStop.cleared_at.is_not(None))),
_count(and_(stopped, _misfired())),
_count(and_(stopped, GateStop.ran_at.is_not(None))),
)
async with async_session() as session:
gate_rows = (await session.execute(
select(GateStop.gate, *counts, func.count(func.distinct(GateStop.session_id)))
.where(window).group_by(GateStop.gate)
)).all()
rule_rows = (await session.execute(
select(GateStop.rule_id, GateStop.gate, GateStop.at, Rule.title, *counts,
func.count(func.distinct(GateStop.session_id)),
func.max(GateStop.stopped_at))
.outerjoin(Rule, Rule.id == GateStop.rule_id)
.where(window, GateStop.rule_id.is_not(None))
.group_by(GateStop.rule_id, GateStop.gate, GateStop.at, Rule.title)
.order_by(_count(stopped).desc(), GateStop.rule_id)
.limit(_BY_RULE_LIMIT)
)).all()
fence_rows = (await session.execute(
select(GateStop.tool, GateStop.target, func.count(GateStop.id),
_count(GateStop.ran_at.is_not(None)))
.where(window, GateStop.gate == FENCE)
.group_by(GateStop.tool, GateStop.target)
.order_by(func.count(GateStop.id).desc(), GateStop.tool)
)).all()
first = (await session.execute(
select(func.min(GateStop.stopped_at)).where(GateStop.user_id == user_id)
)).scalar_one_or_none()
def block(s, lt, cl, mis, ran) -> dict:
return {"stops": int(s or 0), "let_through": int(lt or 0), "cleared": int(cl or 0),
"misfired": int(mis or 0), "ran": int(ran or 0)}
by_gate = {g: {**block(0, 0, 0, 0, 0), "sessions": 0} for g in GATES}
for gate, s, lt, cl, mis, ran, sessions in gate_rows:
if gate in by_gate:
by_gate[gate] = {**block(s, lt, cl, mis, ran), "sessions": int(sessions or 0)}
return {
"days": days,
"by_gate": by_gate,
"by_rule": [
{"rule_id": int(rid), "gate": gate, "at": at, "title": title,
**block(s, lt, cl, mis, ran), "sessions": int(sessions or 0),
"last_stopped_at": last.isoformat() if last else None}
for rid, gate, at, title, s, lt, cl, mis, ran, sessions, last in rule_rows
],
"fence": [
{"tool": tool, "target": target, "asks": int(n or 0), "ran": int(ran or 0)}
for tool, target, n, ran in fence_rows
],
"complete_from": first.isoformat() if first else None,
"covers_window": None if first is None else first <= since,
}
async def prune(cutoff: datetime) -> int:
async with async_session() as session:
result = await session.execute(delete(GateStop).where(GateStop.stopped_at < cutoff))
await session.commit()
return int(result.rowcount or 0)
+5 -2
View File
@@ -1914,15 +1914,18 @@ def act_decision(reached: list[tuple], *, held: frozenset[int] = frozenset()) ->
checkpoint.
- Otherwise `{}`: the act goes ahead, with any lines beside it.
`at` is where the deciding rule was reached (a moment, or the trigger),
which the plugin reports with the stop (`gate_stops`).
A preference never refuses or holds (`rule_order.force`).
"""
enforced = [item for item in reached if rule_order.force(item[0]) == "enforce"]
if enforced:
return {"kind": "enforce", "rule_ids": [rule.id for rule, _a, _w in enforced],
"reason": enforce_reason(enforced)}
"at": enforced[0][1], "reason": enforce_reason(enforced)}
for rule, at, where in reached:
if rule_order.force(rule) == "hold" and rule.id not in held:
return {"kind": "hold", "rule_ids": [rule.id],
return {"kind": "hold", "rule_ids": [rule.id], "at": at,
"reason": hold_reason(rule, at=at, where=where)}
return {}
@@ -1781,6 +1781,17 @@ async def retrieval_summary(
out["record_reach"] = None
out["record_reach_failed"] = True
# How often each gate stood in front of a tool call, and what followed.
# Its own guard, for record_reach's reason.
try:
from grimoire.services import gate_stops
out["gates"] = (await gate_stops.summary(user_id, since=since, until=until)
if user_id else None)
except Exception:
logger.exception("gate stops read failed")
out["gates"] = None
out["gates_failed"] = True
# ── Judged lines ─────────────────────────────────────────────────────
#
# The relevance readout the usage blocks cannot be: a reviewer's verdict
+4 -2
View File
@@ -262,7 +262,8 @@ async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
async def prune(retain_days: int = RETAIN_DAYS) -> int:
"""Delete deliveries older than `retain_days`, the adherence verdicts on
them (`rule_adherence`), which mean nothing without their delivery, and
the record deliveries of the same age (`record_deliveries`)."""
the record deliveries and gate stops of the same age (`record_deliveries`,
`gate_stops`)."""
from grimoire.services import rule_adherence
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
@@ -272,8 +273,9 @@ async def prune(retain_days: int = RETAIN_DAYS) -> int:
)
await session.commit()
await rule_adherence.prune(cutoff)
from grimoire.services import record_deliveries
from grimoire.services import gate_stops, record_deliveries
await record_deliveries.prune(cutoff)
await gate_stops.prune(cutoff)
return int(result.rowcount or 0)
+196
View File
@@ -0,0 +1,196 @@
"""Every gate that stands in front of a tool call reports it, end to end.
The moment hook (a rule set to enforce or hold), the act checkpoint on a
command and the project fence are run through a real shell against a
stand-in server. Each stop is posted to `/api/plugin/gate-stop` with what
the hook did: `stopped`, `let_through` when the session's stop budget is
spent, or `asked` for the fence. A fenced call that then runs is posted to
`/api/plugin/gate-ran` by grimoire_fence_ran.sh, matched by the call's id.
"""
from __future__ import annotations
import json
import os
import subprocess
from pathlib import Path
from tests.helpers import http_sink, need_tools
HOOKS = Path(__file__).resolve().parents[1] / "plugin" / "hooks"
MOMENT = HOOKS / "grimoire_moment.sh"
TOOL_RULES = HOOKS / "grimoire_tool_rules.sh"
FENCE = HOOKS / "grimoire_project_fence.sh"
FENCE_RAN = HOOKS / "grimoire_fence_ran.sh"
STOP = "/api/plugin/gate-stop"
RAN = "/api/plugin/gate-ran"
TOOLS = {"/api/plugin/moment-tools": b'{"tools":["bash"]}'}
def _env(tmp_path, port, **extra):
return {"PATH": os.environ["PATH"], "GRIMOIRE_URL": f"http://127.0.0.1:{port}",
"GRIMOIRE_TOKEN": "t", "TMPDIR": str(tmp_path / "tmp"), "HOME": str(tmp_path), **extra}
def _run(hook, tmp_path, port, event, **extra):
need_tools("bash", "curl", "awk")
(tmp_path / "tmp").mkdir(exist_ok=True)
out = subprocess.run(["bash", str(hook)], input=json.dumps(event), capture_output=True,
text=True, env=_env(tmp_path, port, **extra), timeout=30)
assert out.returncode == 0, out.stderr
return out.stdout.strip()
def _bash_event(session="s-gate", call="toolu_1", command="git push origin dev", cwd="."):
return {"session_id": session, "cwd": cwd, "hook_event_name": "PreToolUse",
"tool_name": "Bash", "tool_use_id": call, "tool_input": {"command": command}}
def _stops(seen):
return [json.loads(e["_body"]) for e in seen if e.get("_path") == STOP]
def _denied(out):
return json.loads(out)["hookSpecificOutput"].get("permissionDecision") == "deny"
def _moment_replies(decision):
replies = dict(TOOLS)
replies["/api/plugin/moment"] = json.dumps(
{"context": "", "rule_ids": [], "moments": ["work.deliver"], "decision": decision}).encode()
return replies
# ── the moment hook ──────────────────────────────────────────────────────
def test_an_enforced_refusal_is_reported_every_time_with_where_it_was_reached(tmp_path):
decision = {"kind": "enforce", "rule_ids": [6], "at": "work.deliver", "reason": "Not run: rule 6"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
outs = [_run(MOMENT, tmp_path, port, _bash_event(call=f"toolu_{i}"), CLAUDE_PROJECT_DIR=str(tmp_path))
for i in range(2)]
assert all(_denied(o) for o in outs)
stops = _stops(seen)
assert [s["call_id"] for s in stops] == ["toolu_0", "toolu_1"]
assert stops[0] == {"session_id": "s-gate", "gate": "enforce", "outcome": "stopped",
"tool": "bash", "rule_id": 6, "at": "work.deliver", "call_id": "toolu_0"}
def test_a_hold_is_reported_once_and_its_repeat_is_not_a_cap_let_through(tmp_path):
"""The per-rule once is the hold working as meant, so the second call on
the same rule reports nothing: only a spent session budget is a call the
cap let through."""
decision = {"kind": "hold", "rule_ids": [7], "at": "work.deliver", "reason": "Read rule 7"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
first = _run(MOMENT, tmp_path, port, _bash_event(call="toolu_a"))
second = _run(MOMENT, tmp_path, port, _bash_event(call="toolu_b"))
assert _denied(first)
assert second == ""
assert [(s["gate"], s["outcome"], s["rule_id"]) for s in _stops(seen)] == [("hold", "stopped", 7)]
def test_a_hold_the_spent_session_budget_lets_through_is_reported_as_such(tmp_path):
state = tmp_path / "tmp" / "grimoire-priorart"
state.mkdir(parents=True)
(state / "s-gate.checkpoint.ids").write_text("1\n2\n3\n4\n5\n")
decision = {"kind": "hold", "rule_ids": [7], "at": "work.deliver", "reason": "Read rule 7"}
with http_sink(by_path=_moment_replies(decision)) as (port, seen):
out = _run(MOMENT, tmp_path, port, _bash_event())
assert out == ""
assert [(s["gate"], s["outcome"], s["rule_id"]) for s in _stops(seen)] == [("hold", "let_through", 7)]
def test_a_call_no_gate_stops_reports_nothing(tmp_path):
with http_sink(by_path=_moment_replies({})) as (port, seen):
_run(MOMENT, tmp_path, port, _bash_event())
assert _stops(seen) == []
# ── the act checkpoint ───────────────────────────────────────────────────
def _checkpoint_replies(rule_id=9):
return {"/api/plugin/tool-rules": json.dumps(
{"context": "", "rule_ids": [rule_id],
"checkpoint": {"rule_id": rule_id, "reason": f"Read rule {rule_id} first"}}).encode()}
def test_a_checkpoint_stop_is_reported_with_the_tool_and_the_arm(tmp_path):
with http_sink(by_path=_checkpoint_replies()) as (port, seen):
out = _run(TOOL_RULES, tmp_path, port, _bash_event(command="git commit -m x", cwd=str(tmp_path)))
assert _denied(out)
assert _stops(seen) == [{"session_id": "s-gate", "gate": "checkpoint", "outcome": "stopped",
"tool": "Bash", "rule_id": 9, "at": "pre_tool_rule", "call_id": "toolu_1"}]
def test_a_checkpoint_past_the_session_cap_is_reported_as_let_through(tmp_path):
state = tmp_path / "tmp" / "grimoire-priorart"
state.mkdir(parents=True)
(state / "s-gate.checkpoint.ids").write_text("1\n2\n3\n4\n5\n")
with http_sink(by_path=_checkpoint_replies()) as (port, seen):
out = _run(TOOL_RULES, tmp_path, port, _bash_event(command="git commit -m x", cwd=str(tmp_path)))
assert out == ""
assert [(s["gate"], s["outcome"]) for s in _stops(seen)] == [("checkpoint", "let_through")]
# ── the project fence ────────────────────────────────────────────────────
HOME_URL = "https://forge.example/team/home.git"
ASK = json.dumps({"allowed": False, "targets": [{"id": 9, "title": "Other"}], "issue": False,
"reason": "Retire family idea in Other, but this session is working in Home."}).encode()
def _home(tmp_path):
home = tmp_path / "home"
home.mkdir()
subprocess.run(["git", "init", "-q"], cwd=home, check=True)
subprocess.run(["git", "remote", "add", "origin", HOME_URL], cwd=home, check=True)
return home
def _grimoire_write(home, call="toolu_f"):
return {"session_id": "s-gate", "cwd": str(home), "hook_event_name": "PreToolUse",
"tool_name": "mcp__plugin_grimoire_grimoire__retire_family_idea",
"tool_use_id": call, "tool_input": {"idea_id": 188, "why": "x"}}
def _ran(home, call):
return {"session_id": "s-gate", "cwd": str(home), "hook_event_name": "PostToolUse",
"tool_name": "mcp__plugin_grimoire_grimoire__retire_family_idea",
"tool_use_id": call, "tool_input": {"idea_id": 188}, "tool_response": {}}
def test_a_fence_ask_is_reported_and_the_run_after_a_yes_is_matched_to_it(tmp_path):
need_tools("git")
home = _home(tmp_path)
with http_sink(by_path={"/api/plugin/write-scope": ASK}) as (port, seen):
out = _run(FENCE, tmp_path, port, _grimoire_write(home), CLAUDE_PROJECT_DIR=str(home))
assert json.loads(out)["hookSpecificOutput"]["permissionDecision"] == "ask"
# Another call ran in between: not the one asked about.
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_other"))
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_f"))
# Matched once; the same id again reports nothing.
_run(FENCE_RAN, tmp_path, port, _ran(home, "toolu_f"))
assert _stops(seen) == [{"session_id": "s-gate", "gate": "fence", "outcome": "asked",
"tool": "retire_family_idea", "rule_id": None,
"at": "retire_family_idea", "target": "9", "call_id": "toolu_f"}]
ran = [json.loads(e["_body"]) for e in seen if e["_path"] == RAN]
assert ran == [{"session_id": "s-gate", "call_id": "toolu_f"}]
def test_with_no_ask_pending_the_after_call_hook_sends_nothing(tmp_path):
with http_sink() as (port, seen):
out = _run(FENCE_RAN, tmp_path, port, _ran(tmp_path, "toolu_x"))
assert out == "" and seen == []
def test_the_after_call_hook_is_registered_only_after_calls_and_on_the_fenced_tools():
"""It must never run before a call: it has nothing to decide there, and the
fence itself is what answers a PreToolUse."""
hooks = json.loads((HOOKS / "hooks.json").read_text())["hooks"]
def matchers(event):
return [m.get("matcher") for m in hooks.get(event, [])
for h in m["hooks"] if "grimoire_fence_ran.sh" in h["command"]]
fence_pre = [m.get("matcher") for m in hooks["PreToolUse"]
for h in m["hooks"] if "grimoire_project_fence.sh" in h["command"]]
assert matchers("PreToolUse") == []
assert matchers("PostToolUse") == fence_pre
+122
View File
@@ -0,0 +1,122 @@
"""Real-Postgres tests for `gate_stops`: each time a gate stood in front of a
tool call, the read that cleared it, the run that followed a yes, and the
readout per gate and per rule."""
from datetime import datetime, timedelta, timezone
import pytest
from sqlalchemy import delete, select, update
from grimoire.models import async_session
from grimoire.models.gate_stop import GateStop
from grimoire.models.rule_adherence import MISFIRE, NOT_APPLICABLE, RuleAdherence
from grimoire.services import gate_stops, rule_adherence
from tests.helpers import ensure_user
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
RULE = 9_300_001
OTHER = 9_300_002
async def _user(name: str = "gate_stop_owner") -> int:
async with async_session() as s:
user = await ensure_user(s, name)
uid = user.id
await s.commit()
await s.execute(delete(GateStop).where(GateStop.user_id == uid))
await s.execute(delete(RuleAdherence).where(RuleAdherence.user_id == uid))
await s.commit()
return uid
async def _rows(uid) -> list[GateStop]:
async with async_session() as s:
return list((await s.execute(
select(GateStop).where(GateStop.user_id == uid).order_by(GateStop.id)
)).scalars().all())
async def test_a_stop_without_a_session_gate_or_rule_records_nothing():
uid = await _user()
assert not await gate_stops.record(uid, "", gate="hold", outcome="stopped", tool="bash", rule_id=RULE)
assert not await gate_stops.record(uid, "s", gate="nonsense", outcome="stopped", tool="bash", rule_id=RULE)
assert not await gate_stops.record(uid, "s", gate="hold", outcome="stopped", tool="bash")
# The fence is the one gate with no rule behind it.
assert await gate_stops.record(uid, "s", gate="fence", outcome="asked", tool="update_task", target="9")
assert [(r.gate, r.rule_id, r.target) for r in await _rows(uid)] == [("fence", None, "9")]
async def test_an_open_clears_the_latest_stop_of_that_rule_in_that_session_only():
uid = await _user()
for sid in ("s-1", "s-2"):
await gate_stops.record(uid, sid, gate="hold", outcome="stopped", tool="bash",
rule_id=RULE, at="work.deliver")
assert await gate_stops.mark_cleared(uid, "s-1", RULE)
# Nothing left to clear for it there, and another rule's open clears nothing.
assert not await gate_stops.mark_cleared(uid, "s-1", RULE)
assert not await gate_stops.mark_cleared(uid, "s-2", OTHER)
cleared = {r.session_id: r.cleared_at is not None for r in await _rows(uid)}
assert cleared == {"s-1": True, "s-2": False}
async def test_an_open_long_after_the_stop_does_not_clear_it():
uid = await _user()
await gate_stops.record(uid, "s-old", gate="checkpoint", outcome="stopped", tool="Bash", rule_id=RULE)
async with async_session() as s:
await s.execute(update(GateStop).where(GateStop.user_id == uid).values(
stopped_at=datetime.now(timezone.utc) - timedelta(days=1)))
await s.commit()
assert not await gate_stops.mark_cleared(uid, "s-old", RULE)
async def test_the_run_after_a_fence_ask_is_matched_by_its_call_id():
uid = await _user()
await gate_stops.record(uid, "s-f", gate="fence", outcome="asked", tool="retire_family_idea",
target="9", call_id="toolu_1")
assert not await gate_stops.mark_ran(uid, "s-f", "toolu_2")
assert await gate_stops.mark_ran(uid, "s-f", "toolu_1")
assert not await gate_stops.mark_ran(uid, "s-f", "toolu_1")
assert (await _rows(uid))[0].ran_at is not None
async def test_the_readout_counts_stops_reads_misfires_and_the_cap_per_gate_and_rule():
uid = await _user()
# Rule RULE held in three sessions: one cleared by a read, one called a
# misfire, one never answered. Then once let through by a spent budget.
for sid in ("a", "b", "c"):
await gate_stops.record(uid, sid, gate="hold", outcome="stopped", tool="bash",
rule_id=RULE, at="work.deliver")
await gate_stops.mark_cleared(uid, "a", RULE)
await rule_adherence.record(uid, "b", RULE, "work.deliver", NOT_APPLICABLE, MISFIRE, "not this act")
await gate_stops.record(uid, "d", gate="hold", outcome="let_through", tool="bash",
rule_id=RULE, at="work.deliver")
await gate_stops.record(uid, "a", gate="checkpoint", outcome="stopped", tool="Bash",
rule_id=OTHER, at="pre_tool_rule")
await gate_stops.record(uid, "a", gate="fence", outcome="asked", tool="update_task",
target="9", call_id="t1")
await gate_stops.record(uid, "a", gate="fence", outcome="asked", tool="update_task",
target="9", call_id="t2")
await gate_stops.mark_ran(uid, "a", "t1")
out = await gate_stops.summary(uid, days=7)
hold = out["by_gate"]["hold"]
assert (hold["stops"], hold["cleared"], hold["misfired"], hold["let_through"], hold["sessions"]) == (3, 1, 1, 1, 4)
assert out["by_gate"]["checkpoint"]["stops"] == 1
assert out["by_gate"]["enforce"] == {"stops": 0, "let_through": 0, "cleared": 0,
"misfired": 0, "ran": 0, "sessions": 0}
assert (out["by_gate"]["fence"]["stops"], out["by_gate"]["fence"]["ran"]) == (2, 1)
first = out["by_rule"][0]
assert (first["rule_id"], first["gate"], first["at"], first["stops"]) == (RULE, "hold", "work.deliver", 3)
assert out["fence"] == [{"tool": "update_task", "target": "9", "asks": 2, "ran": 1}]
assert out["complete_from"] is not None
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)
async with async_session() as s:
await s.execute(update(GateStop).where(GateStop.user_id == uid).values(
stopped_at=datetime.now(timezone.utc) - timedelta(days=400)))
await s.commit()
await gate_stops.prune(datetime.now(timezone.utc) - timedelta(days=180))
assert await _rows(uid) == []