"""Whether the rules in force at each moment were followed there. A rule is IN FORCE at a moment of a session when it was delivered there: one `rule_deliveries` row or more for that (session, rule, place). Each such triple gets at most one verdict (`models/rule_adherence.py`), from the strongest evidence there is: - `note_refused` — an `enforce` rule refused the act, so the act did not happen: followed, by construction. Recorded by the moment arm as it decides. - `from_session` — the session declared what the rule did (`rule_outcome`: applied → followed, departed → departed) or that it did not bear on the work (`rule_misfired` → not applicable). The plugin watches both calls and posts them with the session id, so the verdict lands on the delivery the session was answering. - `judge` — a review read the session's transcript and says followed, broken, departed or not applicable, with the evidence. `to_judge` lists what is waiting for one. `summary` is the readout: per rule and per place (a moment or an arm), how many sessions it was in force in, opened in, and each verdict, with the rest counted as unjudged. Only deliveries whose plugin reports opens are counted (`rule_deliveries.REPORTS_OPENS`), so "opened" beside "followed" means the same thing on every row. """ from __future__ import annotations import logging from datetime import datetime, timedelta, timezone from sqlalchemy import and_, case, delete, func, select, true from sqlalchemy.dialects.postgresql import insert from grimoire.models import async_session from grimoire.models.rule_adherence import ( BROKEN, DEPARTED, FOLLOWED, JUDGE, MISFIRE, NOT_APPLICABLE, OUTCOME, REFUSED, VERDICTS, RuleAdherence, ) from grimoire.models.rule_delivery import RuleDelivery from grimoire.models.rulebook import Rule from grimoire.services import rule_deliveries from grimoire.services.background import spawn logger = logging.getLogger(__name__) SUMMARY_DAYS = 30 _EVIDENCE_CHARS = 1000 _EXCERPT_CHARS = 400 JUDGE_SESSIONS = 3 JUDGE_PER_SESSION = 40 # A session's own word, mapped to a verdict. OUTCOME_VERDICTS = {"applied": FOLLOWED, "departed": DEPARTED} # Where Claude Code keeps a session's transcript, for the reviewer: the file # is named for the session id the deliveries carry. TRANSCRIPT_HINT = ( "Each session's transcript is a JSONL file named for its session id. Claude Code keeps " "them under ~/.claude/projects//.jsonl, so " "`ls ~/.claude/projects/*/.jsonl` finds one. Read it around each rule's " "delivered times: what was the work at that moment, and did it keep the rule?" ) def _evidence(text) -> str: return " ".join(str(text or "").split())[:_EVIDENCE_CHARS] def _excerpt(text) -> str: text = " ".join(str(text or "").split()) return text if len(text) <= _EXCERPT_CHARS else text[:_EXCERPT_CHARS - 1] + "…" async def record( user_id: int, session_id: str, rule_id: int, at: str, verdict: str, source: str, evidence: str = "", ) -> bool: """Set the verdict for one rule at one place in one session. Replaces an earlier verdict unless that one came from a refusal, which is a fact about the act and stands. Returns whether a row was written. """ if verdict not in VERDICTS or not session_id or not at: return False stmt = insert(RuleAdherence).values( user_id=int(user_id), session_id=session_id, rule_id=int(rule_id), at=str(at), verdict=verdict, source=source, evidence=_evidence(evidence) or None, ) stmt = stmt.on_conflict_do_update( constraint="uq_rule_adherence_session_rule_at", set_={"verdict": stmt.excluded.verdict, "source": stmt.excluded.source, "evidence": stmt.excluded.evidence, "judged_at": func.now()}, where=RuleAdherence.source != REFUSED, ) async with async_session() as session: result = await session.execute(stmt) await session.commit() return bool(result.rowcount) def note_refused(user_id: int, refused: list[tuple[int, str, str]]) -> None: """Record that `enforce` rules refused an act in the bound session. `refused` is `(rule_id, at, where)` for each rule that drew the line; `where` says what reached it and goes in as the evidence. A no-op outside a plugin request, which has no session to record against. """ sid = rule_deliveries.current_session() if not sid or not refused: return async def _write() -> None: for rid, at, where in refused: await record(user_id, sid, rid, at, FOLLOWED, REFUSED, f"The act was refused ({where}).") spawn(_write(), site="rule_adherence_refused") async def from_session( user_id: int, session_id: str, rule_id: int, *, outcome: str = "", misfired_at: str = "", why: str = "", ) -> dict: """Turn a session's own `rule_outcome` or `rule_misfired` into a verdict. The verdict lands on the place the session last had the rule delivered — for a misfire, the moment it names. A rule the session was never delivered (looked up unprompted) gets none: adherence is about rules that reached a moment. Returns `{"recorded": bool, "at": str}`. """ sid = rule_deliveries.clean_session(session_id) if misfired_at: verdict, source = NOT_APPLICABLE, MISFIRE else: verdict, source = OUTCOME_VERDICTS.get((outcome or "").strip().lower(), ""), OUTCOME if not sid or not rule_id or not verdict: return {"recorded": False, "at": ""} clauses = [RuleDelivery.user_id == user_id, RuleDelivery.session_id == sid, RuleDelivery.rule_id == int(rule_id)] if misfired_at: clauses.append(RuleDelivery.at == misfired_at.strip()) async with async_session() as session: at = (await session.execute( select(RuleDelivery.at).where(*clauses) .order_by(RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc()).limit(1) )).scalar_one_or_none() if at is None: return {"recorded": False, "at": ""} done = await record(user_id, sid, int(rule_id), at, verdict, source, why) return {"recorded": done, "at": at} def _triples(user_id: int, since): """One row per (session, rule, place) delivered since `since`, from plugins that report opens: how often, when, and whether it was opened.""" return ( select( RuleDelivery.session_id, RuleDelivery.rule_id, RuleDelivery.at, func.count(RuleDelivery.id).label("delivered"), func.min(RuleDelivery.delivered_at).label("first_at"), func.max(RuleDelivery.delivered_at).label("last_at"), func.bool_or(RuleDelivery.opened_at.is_not(None)).label("opened"), ) .where(RuleDelivery.user_id == user_id, RuleDelivery.delivered_at >= since, rule_deliveries.REPORTS_OPENS) .group_by(RuleDelivery.session_id, RuleDelivery.rule_id, RuleDelivery.at) .subquery() ) def _verdict_join(t, user_id: int): return and_(RuleAdherence.user_id == user_id, RuleAdherence.session_id == t.c.session_id, RuleAdherence.rule_id == t.c.rule_id, RuleAdherence.at == t.c.at) async def to_judge( user_id: int, session_id: str = "", *, sessions: int = JUDGE_SESSIONS, per_session: int = JUDGE_PER_SESSION, ) -> dict: """The rules in force at a moment of a session that have no verdict yet. Grouped by session, most recent first, each with what the reviewer needs to judge it from the transcript: the rule's statement and when it applies, the place it arrived, how often and when, and whether it was opened. `session_id` narrows to one session. """ sessions = max(1, min(int(sessions or JUDGE_SESSIONS), 10)) per_session = max(1, min(int(per_session or JUDGE_PER_SESSION), 100)) since = datetime.now(timezone.utc) - timedelta(days=rule_deliveries.RETAIN_DAYS) t = _triples(user_id, since) one = rule_deliveries.clean_session(session_id) if session_id else "" waiting = and_(RuleAdherence.id.is_(None), t.c.session_id == one if one else true()) async with async_session() as session: total = (await session.execute( select(func.count()).select_from(t).outerjoin(RuleAdherence, _verdict_join(t, user_id)) .where(waiting) )).scalar_one() recent = (await session.execute( select(t.c.session_id, func.min(t.c.first_at), func.max(t.c.last_at)) .select_from(t).outerjoin(RuleAdherence, _verdict_join(t, user_id)) .where(waiting) .group_by(t.c.session_id) .order_by(func.max(t.c.last_at).desc()) .limit(sessions) )).all() out = [] for sid, first_at, last_at in recent: rows = (await session.execute( select(t.c.rule_id, t.c.at, t.c.delivered, t.c.first_at, t.c.last_at, t.c.opened, Rule.title, Rule.statement, Rule.when_to_apply, Rule.kind) .select_from(t) .outerjoin(RuleAdherence, _verdict_join(t, user_id)) .outerjoin(Rule, Rule.id == t.c.rule_id) .where(RuleAdherence.id.is_(None), t.c.session_id == sid) .order_by(t.c.first_at, t.c.rule_id) .limit(per_session) )).all() out.append({ "session_id": sid, "first_at": first_at.isoformat() if first_at else None, "last_at": last_at.isoformat() if last_at else None, "items": [{ "rule_id": int(rid), "at": at, "title": title, "kind": kind, "statement": _excerpt(statement), "when_to_apply": _excerpt(when), "delivered": int(n), "opened": bool(opened), "first_at": f.isoformat() if f else None, "last_at": last.isoformat() if last else None, } for rid, at, n, f, last, opened, title, statement, when, kind in rows], }) return {"sessions": out, "unjudged": int(total or 0), "how": TRANSCRIPT_HINT} async def judge(user_id: int, items: list[dict]) -> dict: """Record a review's verdicts: `{session_id, rule_id, at, verdict, evidence}` each. `verdict` is followed, broken, departed or not_applicable, and `evidence` — what in the transcript shows it — is required: a verdict a later reader cannot check is no better than none. The triple must be one this user was delivered. A bad item is refused alone; a refusal's verdict is never replaced. """ done: list[dict] = [] refused: list[dict] = [] for item in items or []: if not isinstance(item, dict): refused.append({"item": item, "error": "each verdict is an object"}) continue sid = rule_deliveries.clean_session(str(item.get("session_id") or "")) at = str(item.get("at") or "").strip() verdict = str(item.get("verdict") or "").strip().lower() evidence = _evidence(item.get("evidence")) try: rid = int(item.get("rule_id") or 0) except (TypeError, ValueError): rid = 0 key = {"session_id": sid, "rule_id": rid, "at": at} if not sid or rid <= 0 or not at: refused.append({**key, "error": "needs session_id, rule_id and at"}) continue if verdict not in VERDICTS: refused.append({**key, "error": f"verdict is one of {', '.join(VERDICTS)}"}) continue if not evidence: refused.append({**key, "error": "evidence is required: what in the transcript shows it"}) continue async with async_session() as session: delivered = (await session.execute( select(RuleDelivery.id).where( RuleDelivery.user_id == user_id, RuleDelivery.session_id == sid, RuleDelivery.rule_id == rid, RuleDelivery.at == at, ).limit(1) )).scalar_one_or_none() if delivered is None: refused.append({**key, "error": "no delivery of this rule there in that session"}) continue if not await record(user_id, sid, rid, at, verdict, JUDGE, evidence): refused.append({**key, "error": "an enforce refusal already settled it"}) continue done.append({**key, "verdict": verdict}) return {"judged": done, "refused": refused} def _counts() -> dict: return {"in_force": 0, "opened": 0, FOLLOWED: 0, DEPARTED: 0, BROKEN: 0, NOT_APPLICABLE: 0, "unjudged": 0} def _add(slot: dict, row: dict) -> None: for k in _counts(): slot[k] += row[k] async def summary(user_id: int, days: int = SUMMARY_DAYS, rule_id: int | None = None) -> dict: """Adherence per rule and per place, over the last `days`. For each (rule, place): `in_force` is how many sessions the rule was delivered there in; `opened` how many of those opened it; then one count per verdict, and `unjudged` for the sessions with none yet. `by_rule` lists each rule with its places; `by_moment` lists each place with its rules; `totals` sums them. Counts only — a person reads "in force 12, followed 9, broken 1, unjudged 2" more truly than a rate that hides the unjudged. """ days = max(1, min(int(days or SUMMARY_DAYS), rule_deliveries.RETAIN_DAYS)) since = datetime.now(timezone.utc) - timedelta(days=days) t = _triples(user_id, since) v = RuleAdherence.verdict def n(cond): return func.sum(case((cond, 1), else_=0)) stmt = ( select( t.c.rule_id, t.c.at, Rule.title, func.count().label("in_force"), n(t.c.opened).label("opened"), n(v == FOLLOWED).label(FOLLOWED), n(v == DEPARTED).label(DEPARTED), n(v == BROKEN).label(BROKEN), n(v == NOT_APPLICABLE).label(NOT_APPLICABLE), n(RuleAdherence.id.is_(None)).label("unjudged"), ) .select_from(t) .outerjoin(RuleAdherence, _verdict_join(t, user_id)) .outerjoin(Rule, Rule.id == t.c.rule_id) .group_by(t.c.rule_id, t.c.at, Rule.title) .order_by(t.c.rule_id, t.c.at) ) if rule_id: stmt = stmt.where(t.c.rule_id == int(rule_id)) async with async_session() as session: rows = (await session.execute(stmt)).mappings().all() by_rule: dict[int, dict] = {} by_moment: dict[str, dict] = {} totals = _counts() for raw in rows: row = {k: int(raw[k] or 0) for k in _counts()} rid, at = int(raw["rule_id"]), raw["at"] rule_slot = by_rule.setdefault(rid, {"rule_id": rid, "title": raw["title"], **_counts(), "by_moment": []}) _add(rule_slot, row) rule_slot["by_moment"].append({"at": at, **row}) moment_slot = by_moment.setdefault(at, {"at": at, **_counts(), "by_rule": []}) _add(moment_slot, row) moment_slot["by_rule"].append({"rule_id": rid, "title": raw["title"], **row}) _add(totals, row) return { "days": days, "totals": totals, "by_rule": sorted(by_rule.values(), key=lambda r: (-r["in_force"], r["rule_id"])), "by_moment": sorted(by_moment.values(), key=lambda m: (-m["in_force"], m["at"])), } async def prune(cutoff) -> int: """Delete verdicts older than `cutoff`, with the deliveries they describe.""" async with async_session() as session: result = await session.execute(delete(RuleAdherence).where(RuleAdherence.judged_at < cutoff)) await session.commit() return int(result.rowcount or 0)