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:
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
@@ -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():
|
||||
|
||||
@@ -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():
|
||||
|
||||
@@ -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