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:
@@ -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.
|
||||
|
||||
@@ -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)
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user