"""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, PROJECT_CHECK, RULELESS_GATES, 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 not in RULELESS_GATES 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) async def asked(user_id: int, session_id: str | None, *, gate: str, target: str) -> bool: """Whether this gate already stood in front of this session about this target, so a session is asked about one other project once.""" sid = rule_deliveries.clean_session(session_id) if not sid: return False async with async_session() as session: return (await session.execute( select(exists().where( GateStop.user_id == user_id, GateStop.session_id == sid, GateStop.gate == gate, GateStop.target == _field(target), )) )).scalar_one() 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. `project_check`: per other project, how often a message was flagged as reading like its work rather than the session's. `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() check_rows = (await session.execute( select(GateStop.target, func.count(GateStop.id), func.max(GateStop.stopped_at)) .where(window, GateStop.gate == PROJECT_CHECK) .group_by(GateStop.target) .order_by(func.count(GateStop.id).desc(), GateStop.target) )).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 ], "project_check": [ {"target": target, "asks": int(n or 0), "last_asked_at": last.isoformat() if last else None} for target, n, last in check_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)