Files
FabledGrimoire/src/grimoire/routes/retrieval.py
T
bvandeusenandClaude Opus 5.5 65f1be80b6 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>
2026-11-27 14:12:14 -05:00

347 lines
15 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The operator's view of retrieval tuning — what the dials are, and who moved them.
WHY THIS EXISTS SEPARATELY FROM /api/settings
The numbers themselves are ordinary settings rows and could be written through
the generic KV endpoint. They must not be, and that is the whole point of this
blueprint: a floor changed through `/api/settings` moves silently, leaving the
history saying nothing happened. Those dials are moved by the model on the
operator's behalf, so a trail with holes in it is worse than
no trail — it reads as complete.
So every change to a retrieval dial goes through `set_dial`, from the UI as
much as from the MCP tool, and the only difference is the `actor` recorded.
"""
import logging
from datetime import datetime, timedelta, timezone
from quart import Blueprint, jsonify, request
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
from grimoire.services import rule_field_judgments as weights_svc
from grimoire.services import rule_moment_judgments as judgments_svc
from grimoire.services import rulebooks as rulebooks_svc
from grimoire.services.retrieval_telemetry import moment_usage
from grimoire.services.retrieval_tuning import set_dial, current_settings, tuning_history
logger = logging.getLogger(__name__)
retrieval_bp = Blueprint("retrieval", __name__, url_prefix="/api/retrieval")
# What is recorded when the operator changes a dial in Settings and says
# nothing about why.
#
# The MCP tool REFUSES a blank reason, and this endpoint does not, which is a
# deliberate asymmetry rather than an oversight. The requirement exists to make
# the model look at the records before it moves a number on someone else's
# behalf. The operator IS that someone: they are the audience the trail is
# written for, they cannot be uninformed about their own decision, and a
# mandatory justification textarea on every control would be friction charged
# to the one participant who owes no explanation.
#
# The event is still written, because "the operator set this by hand" is the
# single most useful thing the history can tell a later session — it is the one
# entry the model must not quietly tune back.
_OPERATOR_DEFAULT_REASON = "Set directly in Settings by the operator."
@retrieval_bp.route("/surfaces", methods=["GET"])
@login_required
async def get_surfaces_route():
"""Every tunable surface: its live floor and budget, what it asks and over
what, and the reason each dial was last moved."""
uid = get_current_user_id()
surfaces = await current_settings(uid)
return jsonify({"surfaces": surfaces, "total": len(surfaces)})
@retrieval_bp.route("/gate", methods=["GET"])
@login_required
async def get_gate_route():
"""The cue-swap gate on each surface it holds: the rate it speaks at, the
bar that rate comes to on the user's own recent cues, and how often each
surface actually spoke over the last week."""
from grimoire.services import cue_gate
from grimoire.services import retrieval_pipeline as rp
uid = get_current_user_id()
surfaces = [(arm.source, "records") for arm in rp.NOTE_ARMS if arm.gated] + [
(arm.source, "preferences") for arm in rp.RULE_ARMS if arm.gates_preferences
]
rows = await cue_gate.readout(uid, surfaces)
return jsonify({"surfaces": rows, "rate": rows[0]["rate"] if rows else cue_gate.RATE_DEFAULT,
"lines": cue_gate.LINES, "min_sample": cue_gate.MIN_SAMPLE})
@retrieval_bp.route("/surfaces/<surface>", methods=["PUT"])
@login_required
async def tune_surface_route(surface: str):
"""Move one dial, recorded as a human change.
`actor` is fixed here rather than taken from the payload: this endpoint is
reached with a session cookie from the Settings form, so the actor is known
and accepting a claim about it would let the one field a reviewer relies on
be set to anything.
"""
uid = get_current_user_id()
data = await request.get_json()
if not isinstance(data, dict):
return jsonify({"error": "Expected a JSON object"}), 400
if "dial" not in data or "value" not in data:
return jsonify({"error": "dial and value are required"}), 400
try:
value = float(data["value"])
except (TypeError, ValueError):
return jsonify({"error": f"value must be a number, got {data['value']!r}"}), 400
reason = str(data.get("reason") or "").strip() or _OPERATOR_DEFAULT_REASON
try:
result = await set_dial(
uid, surface, str(data["dial"]), value, reason=reason, actor="human",
)
except ValueError as e:
# Unknown surface, unknown dial — the service names the alternatives,
# so the message is worth passing through rather than flattening.
return jsonify({"error": str(e)}), 400
return jsonify(result)
@retrieval_bp.route("/tuning-history", methods=["GET"])
@login_required
async def tuning_history_route():
"""What has been changed about retrieval on this install, newest first.
The review surface. Unscoped by default because the operator's question
here is "what has been done on my behalf", not "why is this one arm set
like that" — the per-surface scoping is for the model.
"""
uid = get_current_user_id()
surface = request.args.get("surface") or None
try:
limit = int(request.args.get("limit", 50))
except ValueError:
return jsonify({"error": "limit must be a whole number"}), 400
try:
events = await tuning_history(uid, surface=surface, limit=limit)
except ValueError as e:
return jsonify({"error": str(e)}), 400
return jsonify({"events": events, "total": len(events)})
@retrieval_bp.route("/moments", methods=["GET"])
@login_required
async def moments_route():
"""The moments of work that rules mount on, with the
actions that reach each one on this install.
The same payload `list_moments` returns, from the same services, so the
session and the Settings view cannot name different moments — plus what
the view shows beside each one: `mounted`, how many rules each
carries, and `usage`, the deliveries and opens per moment over `days`
(the block `retrieval_telemetry` reports as `moment_usage`).
"""
uid = get_current_user_id()
try:
days = max(1, min(int(request.args.get("days", 30)), 365))
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
out = moments_svc.catalog()
out.update(await moment_actions_svc.actions_by_moment(uid))
# The catalog is the page; the counts beside it are not worth losing it
# over. A failed count is flagged rather than shown as "nothing mounted".
try:
out["mounted"] = await rulebooks_svc.mount_counts(uid)
except Exception:
logger.warning("mount counts unreadable", exc_info=True)
out["mounted"], out["mounted_failed"] = {}, True
out["usage"] = await moment_usage(uid, datetime.now(timezone.utc) - timedelta(days=days))
out["usage"]["days"] = days
return jsonify(out)
@retrieval_bp.route("/reply-shapes", methods=["GET"])
@login_required
async def reply_shapes_route():
"""The default reply shapes and the moment each rides.
`list_reply_shapes`' payload from the same service, so the Settings view
and the session cannot show different defaults — plus what only the
operator's view needs: per shape, the preferences mounted on its
moment and its deliveries over `days` (default 30, 1–90).
"""
try:
days = min(90, max(1, int(request.args.get("days") or shapes_svc.OVERVIEW_DAYS)))
except ValueError:
days = shapes_svc.OVERVIEW_DAYS
return jsonify(await shapes_svc.overview(get_current_user_id(), days=days))
async def _mapping_change(change):
"""map/unmap from the browser: the MCP tools' service, recorded as human.
The mapping comes as a JSON body, or — for DELETE, whose body many
clients will not send — as query parameters of the same names.
"""
data = await request.get_json(silent=True)
if data is None and request.args:
data = request.args.to_dict()
if not isinstance(data, dict):
return jsonify({"error": "Expected a JSON object"}), 400
if not data.get("tool") or not data.get("moment"):
return jsonify({"error": "tool and moment are required"}), 400
try:
result = await change(
get_current_user_id(), str(data["tool"]), str(data.get("match") or ""),
str(data["moment"]), reason=str(data.get("reason") or ""), actor="human",
)
except ValueError as e:
# Unknown moment, a match the tool cannot take, nothing to remove —
# the service says what would work, so pass it through.
return jsonify({"error": str(e)}), 400
return jsonify(result)
@retrieval_bp.route("/moments/mappings", methods=["POST"])
@login_required
async def map_action_route():
return await _mapping_change(moment_actions_svc.map_action)
@retrieval_bp.route("/moments/mappings", methods=["DELETE"])
@login_required
async def unmap_action_route():
return await _mapping_change(moment_actions_svc.unmap_action)
@retrieval_bp.route("/moments/proposals", methods=["GET"])
@login_required
async def moment_proposals_route():
"""The moment proposals waiting on a judgment —
`rule_moment_proposals`' payload, from the same service. `?rule_id=`
narrows to one rule, for the rule editor."""
try:
rule_id = int(request.args.get("rule_id") or 0)
except ValueError:
return jsonify({"error": "rule_id must be a whole number"}), 400
return jsonify(await judgments_svc.pending(get_current_user_id(), rule_id=rule_id or None))
@retrieval_bp.route("/moments/proposals/judge", methods=["POST"])
@login_required
async def judge_moment_proposals_route():
"""Confirm or reject proposals: `{"judgments": [{rule_id, moment, verdict,
note}]}` — `judge_rule_moments` from the browser. A confirm mounts."""
data = await request.get_json(silent=True)
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
return jsonify(await judgments_svc.judge(get_current_user_id(), data["judgments"]))
@retrieval_bp.route("/adherence", methods=["GET"])
@login_required
async def adherence_route():
"""Whether the rules in force at each moment were followed there —
`rule_adherence`'s payload, from the same service. `?days=` sets the
window (default 30); `?rule_id=` narrows to one rule."""
try:
days = int(request.args.get("days") or adherence_svc.SUMMARY_DAYS)
rule_id = int(request.args.get("rule_id") or 0)
except ValueError:
return jsonify({"error": "days and rule_id must be whole numbers"}), 400
return jsonify(await adherence_svc.summary(
get_current_user_id(), days=days, rule_id=rule_id or None,
))
@retrieval_bp.route("/record-kinds", methods=["GET"])
@login_required
async def record_kinds_route():
"""The kind×moment table: which kinds of record each door's search may
consider, the shipped default beside each, and each cell's lines and
opens over `?days=` (default 30)."""
try:
days = max(1, min(int(request.args.get("days") or 30), 365))
except ValueError:
return jsonify({"error": "days must be a whole number"}), 400
return jsonify(await record_kinds_svc.table(get_current_user_id(), days=days))
@retrieval_bp.route("/record-kinds", methods=["PUT"])
@login_required
async def set_record_kinds_route():
"""Set one door's kinds. Body: `{"door", "kinds": [...]}`, or
`{"door", "kinds": null}` to put the door back to its shipped default.
Answers with the whole table."""
data = await request.get_json(silent=True) or {}
if not isinstance(data, dict) or not isinstance(data.get("door"), str):
return jsonify({"error": "door is required"}), 400
kinds = data.get("kinds")
if kinds is not None and (
not isinstance(kinds, list) or not all(isinstance(k, str) for k in kinds)
):
return jsonify({"error": "kinds must be a list of kinds, or null"}), 400
try:
return jsonify(await record_kinds_svc.set_kinds(get_current_user_id(), data["door"], kinds))
except ValueError as e:
return jsonify({"error": str(e)}), 400
@retrieval_bp.route("/record-reach", methods=["GET"])
@login_required
async def record_reach_route():
"""How non-rule records reached this user's sessions: per kind, pushed by
a hook, returned by the session's own search, or opened directly, and how
many were opened each way. `?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 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():
"""The enforcement, salience and trigger suggestions waiting on a judgment
— `rule_weight_proposals`' payload, from the same service. `?rule_id=`
narrows to one rule."""
try:
rule_id = int(request.args.get("rule_id") or 0)
except ValueError:
return jsonify({"error": "rule_id must be a whole number"}), 400
return jsonify(await weights_svc.pending(get_current_user_id(), rule_id=rule_id or None))
@retrieval_bp.route("/weights/proposals/judge", methods=["POST"])
@login_required
async def judge_weight_proposals_route():
"""Confirm or reject suggestions: `{"judgments": [{rule_id, field, value,
verdict, note}]}` — `judge_rule_weights` from the browser. A confirm
changes the rule."""
data = await request.get_json(silent=True)
if not isinstance(data, dict) or not isinstance(data.get("judgments"), list):
return jsonify({"error": "Expected {\"judgments\": [...]}"}), 400
return jsonify(await weights_svc.judge(get_current_user_id(), data["judgments"]))