CI & Build / Python lint (push) Successful in 2s
CI & Build / Plugin hooks (push) Successful in 16s
CI & Build / TypeScript typecheck (push) Successful in 36s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m26s
CI & Build / Build & push image (push) Skipped
A rule is in force at a moment of a session when it was delivered there. Each (session, rule, place) now carries at most one verdict (rule_adherence, migration 0134): followed, departed, broken or not applicable, with where it came from: - an enforce rule refusing the act: followed, recorded by the moment arm, and never replaced; - the session's own rule_outcome (applied, departed) and rule_misfired calls, which the plugin's outcome hook now also posts with the session id (/api/plugin/rule-verdict) onto the delivery being answered; - a transcript review: adherence_to_judge lists what has no verdict yet, by session, and judge_adherence records verdicts with their evidence. rule_adherence (MCP) and /api/retrieval/adherence give the readout: sessions in force, opened and each verdict per rule and per place. Settings > Moments shows it in a "Were they followed" panel, beside each moment's delivered and opened counts, and per rule inside each moment. Verdicts are pruned with their deliveries and left out of backups like them. Plugin 2026.11.23.2227. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
431 lines
19 KiB
Python
431 lines
19 KiB
Python
"""Delivering the rules mounted on a moment, through every door.
|
|
|
|
One function decides what an act reaches and what arrives with it; the doors
|
|
differ only in how they carry the answer:
|
|
|
|
- the plugin's catch-all PreToolUse hook → `/api/plugin/moment`, with the
|
|
session ledger, so a rule already named this session is cited not repeated;
|
|
- Grimoire's own MCP tools → `attach_moment_rules`, in the tool's response, so
|
|
a client without the plugin still gets `work.finish` when a task closes;
|
|
- the Stop hook → `deliver_moments`, for the reply moments no tool call marks.
|
|
|
|
The pipeline stage is `retrieval_pipeline.run_moment_arm`; this module only
|
|
resolves the act to its moments and hands both doors the same result.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from grimoire.services import hook_payload, moment_actions, reply_shapes, rule_order
|
|
from grimoire.services import retrieval_pipeline as rp
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
def _io() -> rp.MomentIO:
|
|
"""Resolved at CALL time, so a test patching either module's name is seen."""
|
|
from grimoire.services import rule_adherence, rule_deliveries, rule_usage, rulebooks
|
|
|
|
bound = rule_deliveries.bound()
|
|
return rp.MomentIO(
|
|
lookup=rulebooks.rules_on_moments,
|
|
record_rule_surfaced=rule_usage.record_rule_surfaced,
|
|
history=rule_deliveries.history if bound else None,
|
|
record_delivery=rule_deliveries.record if bound else None,
|
|
retired=rule_deliveries.retired if bound else None,
|
|
record_refusal=rule_adherence.note_refused if bound else None,
|
|
)
|
|
|
|
|
|
async def reachable_tools(user_id: int) -> list[str]:
|
|
"""The tools a call to which could deliver a mounted rule, as tool keys.
|
|
|
|
What the plugin's catch-all hook reads once per session window, so the
|
|
calls that cannot reach a mounted rule — most of them, and every one on
|
|
an install that has mounted nothing — never leave the machine. An action
|
|
counts when its moment carries a mount or a default reply shape. The
|
|
skill loader counts whenever anything is mounted: a stored process
|
|
declares its own moments, which only the load itself can resolve, and a
|
|
load is rare enough that asking costs nothing.
|
|
"""
|
|
from grimoire.services import rulebooks
|
|
|
|
# A moment that carries a default reply shape is worth a
|
|
# request whether or not anything is mounted on it: the shape is product,
|
|
# so every install has it.
|
|
shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY}
|
|
from grimoire.services import rule_triggers
|
|
|
|
mounted = set(await rulebooks.mounted_moments(user_id))
|
|
wanted = mounted | shaped
|
|
mappings = await moment_actions.list_mappings(user_id)
|
|
keys = {
|
|
moment_actions.tool_key(action.tool)
|
|
for action, _via in moment_actions.effective_actions(mappings)
|
|
if action.moment in wanted
|
|
}
|
|
if mounted:
|
|
keys.add(moment_actions.SKILL_TOOL)
|
|
# A rule triggered with no moment is reached by whatever tool its trigger
|
|
# can match, whatever moments those calls reach.
|
|
try:
|
|
keys |= await rule_triggers.reachable_tools(user_id)
|
|
except Exception: # noqa: BLE001 - the mounts' tools are still worth listing
|
|
logger.debug("rule trigger tools unreadable", exc_info=True)
|
|
return sorted(keys)
|
|
|
|
|
|
async def _board(user_id: int, project_id: int | None, **act):
|
|
"""The triggers' answer for this act; None when it cannot be read, which
|
|
delivers the mounts unconditionally rather than not at all."""
|
|
from grimoire.services import rule_triggers
|
|
|
|
try:
|
|
return await rule_triggers.board(user_id, project_id or None, **act)
|
|
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
|
logger.debug("rule triggers unreadable", exc_info=True)
|
|
return None
|
|
|
|
|
|
async def deliver_moments(
|
|
user_id: int, reached: list[dict], *, project_id: int | None = None,
|
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
|
board=None, text: str = "",
|
|
) -> rp.RuleResult:
|
|
"""The mounted rules for moments already known to have happened.
|
|
|
|
With no `board`, one is built from `text` alone: no act is known here, so
|
|
only keyword triggers can be checked, and a mount conditional on any other
|
|
kind does not deliver.
|
|
"""
|
|
if board is None:
|
|
board = await _board(user_id, project_id, text=text)
|
|
return await rp.run_moment_arm(
|
|
reached,
|
|
rp.RuleMoment(user_id=user_id, query="", project_id=project_id,
|
|
exclude=exclude, held=held),
|
|
io=_io(), board=board,
|
|
)
|
|
|
|
|
|
async def deliver_for_act(
|
|
user_id: int, tool: str, tool_input: dict | None, *,
|
|
project_id: int | None = None,
|
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
|
) -> tuple[list[dict], rp.RuleResult]:
|
|
"""Which moments this act reached, and the rules its mounts and triggers
|
|
deliver. An act that reaches no moment can still fire a trigger."""
|
|
reached = await moment_actions.moments_for(user_id, tool, tool_input or {})
|
|
board = await _board(user_id, project_id, tool=tool, tool_input=tool_input or {})
|
|
if not reached and not (board and board.fired):
|
|
return reached, rp.RuleResult()
|
|
result = await deliver_moments(
|
|
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
|
|
)
|
|
# A write is never held for a read: a recall aid does not stand in the
|
|
# way of the work. A rule set to enforce still refuses one — that is a
|
|
# boundary the operator drew, not a reminder.
|
|
if result.decision.get("kind") == "hold" and moment_actions.tool_key(tool) in WRITE_TOOLS:
|
|
result.decision = {}
|
|
return reached, result
|
|
|
|
|
|
# The file-writing tools, as tool keys: a `hold` rule never holds these.
|
|
WRITE_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit"})
|
|
|
|
|
|
async def routed_to_acts(user_id: int, project_id: int | None = None) -> frozenset[int]:
|
|
"""The rules that arrive at an act, so the prompt arm leaves them there.
|
|
|
|
A rule mounted on a moment some action is mapped to (every moment but the
|
|
reply moments), or carrying a `tool`, `path` or `command` trigger, reaches
|
|
the session at the call it governs. Delivered at the prompt too, it would
|
|
arrive twice, and the first time beside a request it competes with. A
|
|
keyword trigger can also match a reply, so it does not count.
|
|
"""
|
|
from grimoire.services import rule_triggers, rulebooks
|
|
|
|
mappings = await moment_actions.list_mappings(user_id)
|
|
act_moments = sorted({
|
|
action.moment for action, _via in moment_actions.effective_actions(mappings)
|
|
if not action.moment.startswith("reply.")
|
|
})
|
|
out = {rule.id for rule, _at in await rulebooks.rules_on_moments(
|
|
user_id, act_moments, project_id or None,
|
|
)} if act_moments else set()
|
|
for rule, triggers in await rule_triggers._in_scope(user_id, project_id or None):
|
|
if any(t.kind in ("tool", "path", "command") and not t.moment for t in triggers):
|
|
out.add(rule.id)
|
|
return frozenset(out)
|
|
|
|
|
|
def shapes_for_act(reached: list[dict], seen: frozenset[str] = frozenset()) -> tuple[list[str], dict[str, str]]:
|
|
"""The default reply shapes riding the moments this act reached.
|
|
|
|
Closing a task comes just before a completion report, a structured
|
|
question is an ask, opening a plan comes before a plan is put up for
|
|
review — so the shape for that reply arrives at the act, before the reply
|
|
is written. In full the first time a session meets it, as its reminder
|
|
after that; a door with no ledger passes `seen` empty.
|
|
"""
|
|
return reply_shapes.deliver(
|
|
reply_shapes.for_moments([hit["moment"] for hit in reached]), seen,
|
|
)
|
|
|
|
|
|
# What the per-turn delivery says reached `reply.report`: the turn has not
|
|
# ended yet, but every turn ends in a reply, and this is the last point
|
|
# before it is written.
|
|
_REACHED_BY_TURN = "the reply this turn will end with"
|
|
|
|
|
|
async def deliver_for_turn(
|
|
user_id: int, *, seen: frozenset[str] = frozenset(), project_id: int | None = None,
|
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
|
record: bool = True,
|
|
) -> dict:
|
|
"""What every turn carries before its reply is written.
|
|
|
|
The core reply shape — in full once per session and again after a
|
|
compaction (the ledger is swept then), otherwise its one-line reminder —
|
|
and the rules and preferences mounted on `reply.report`, under the same
|
|
rule ledger as every other arm. The Stop hook's reply moment fires after
|
|
the reply exists, which is too late to shape it and is kept as the
|
|
backstop; this is the point before.
|
|
|
|
Returns `{context, rule_ids, shape_forms, shape_parts, rule_parts}`; the
|
|
parts are for a door that fits its payload, which passes `record=False`
|
|
and records the shapes it kept. Fails open to the core alone, and the
|
|
core itself never fails: it is a constant.
|
|
"""
|
|
blocks, forms = reply_shapes.deliver([reply_shapes.core()], seen)
|
|
shape_parts = [
|
|
hook_payload.Part(text=block, ids={hook_payload.SHAPE: (key,)})
|
|
for block, key in zip(blocks, forms, strict=False)
|
|
]
|
|
rule_parts: list[hook_payload.Part] = []
|
|
rule_ids: list[int] = []
|
|
try:
|
|
reached = [{"moment": "reply.report", "tool": "", "match": _REACHED_BY_TURN,
|
|
"via": moment_actions.DEFAULT}]
|
|
result = await deliver_moments(
|
|
user_id, reached, project_id=project_id, exclude=exclude, held=held,
|
|
)
|
|
blocks.extend(result.lines)
|
|
rule_ids = result.rule_ids
|
|
rule_parts = hook_payload.rule_parts(
|
|
result.lines, result.rule_per_line(), block="rules",
|
|
)
|
|
except Exception: # noqa: BLE001 - the mounted half never costs the core
|
|
logger.debug("reply.report mounts not delivered for the turn", exc_info=True)
|
|
if record:
|
|
await reply_shapes.record_delivery(user_id, forms, via="turn")
|
|
return {
|
|
"context": "\n\n".join(blocks), "rule_ids": rule_ids, "shape_forms": forms,
|
|
"shape_parts": shape_parts, "rule_parts": rule_parts,
|
|
}
|
|
|
|
|
|
async def attach_moment_rules(
|
|
user_id: int, tool: str, arguments: dict | None, data: dict,
|
|
) -> dict:
|
|
"""Carry the rules mounted on this tool call's moments in its own response.
|
|
|
|
The MCP door: an in-band decoration on a payload
|
|
already being returned, fail-open, and absent when there is nothing to
|
|
say. The project is the record's own when it has one, else the caller's
|
|
argument — a project's mounted rules belong to work in that project.
|
|
|
|
No session ledger reaches this door, so a mounted rule arrives every time
|
|
its moment happens here. That is the right failure for the moments these
|
|
tools mark: closing a task is exactly when a rule about finishing applies,
|
|
however many tasks were closed before it.
|
|
"""
|
|
if not isinstance(data, dict):
|
|
return data
|
|
try:
|
|
project_id = data.get("project_id") or (arguments or {}).get("project_id") or None
|
|
_reached, result = await deliver_for_act(
|
|
user_id, tool, arguments or {}, project_id=project_id,
|
|
)
|
|
if result.lines:
|
|
data["moment_rules"] = {
|
|
"lines": result.lines,
|
|
"rule_ids": result.shown_rule_ids,
|
|
"open_with": "get_rule(id)",
|
|
}
|
|
# The reply shape for this moment, in full: no ledger reaches this
|
|
# door, and an act like closing a task is rare enough that the shape
|
|
# arriving each time costs less than one report written without it.
|
|
blocks, forms = shapes_for_act(_reached)
|
|
if blocks:
|
|
data["reply_shape"] = "\n\n".join(blocks)
|
|
await reply_shapes.record_delivery(user_id, forms, via="mcp")
|
|
except Exception: # noqa: BLE001 - a decoration never breaks the payload
|
|
logger.debug("moment rules for %s could not be attached", tool, exc_info=True)
|
|
return data
|
|
|
|
|
|
# ── The reply moment: the backstop at the end of a turn ─────────────────
|
|
#
|
|
# The Stop hook's door. A reply is the
|
|
# one act no tool call marks, and the moment where "please verify this on
|
|
# your end" gets said — so it is checked twice over: the rules MOUNTED on the
|
|
# reply moments (deterministic, somebody said they belong here), and the
|
|
# reply text against every rule's trigger (the backstop for whatever the
|
|
# earlier arms missed). An unopened rule set to hold, from either half, HOLDS
|
|
# the reply for one read, in these words; the hook never holds the rewrite.
|
|
|
|
# The reply's head and tail. The embedder reads ~512 tokens, and the part of
|
|
# a report that asks something of the reader — "let me know if it works" —
|
|
# is at the END, where a head-only query would cut it off.
|
|
_REPLY_HEAD_CHARS = 600
|
|
_REPLY_TAIL_CHARS = 1200
|
|
|
|
_REACHED_BY_REPLY = "the reply that ends this turn"
|
|
|
|
|
|
def reply_moments(reply: str) -> list[dict]:
|
|
"""The moments a finished reply reaches: always `reply.report`, and
|
|
`reply.ask` when a line of its prose ends in a question."""
|
|
reached = [{"moment": "reply.report", "tool": "", "match": _REACHED_BY_REPLY,
|
|
"via": moment_actions.DEFAULT}]
|
|
in_code = False
|
|
for line in (reply or "").splitlines():
|
|
stripped = line.strip()
|
|
if stripped.startswith("```"):
|
|
in_code = not in_code
|
|
continue
|
|
if not in_code and stripped.endswith("?"):
|
|
reached.append({"moment": "reply.ask", "tool": "", "match": "a question in the reply",
|
|
"via": moment_actions.DEFAULT})
|
|
break
|
|
return reached
|
|
|
|
|
|
def _reply_query(reply: str) -> str:
|
|
text = " ".join((reply or "").split())
|
|
if len(text) <= _REPLY_HEAD_CHARS + _REPLY_TAIL_CHARS:
|
|
return text
|
|
return text[:_REPLY_HEAD_CHARS] + " … " + text[-_REPLY_TAIL_CHARS:]
|
|
|
|
|
|
def reply_hold_reason(held: list[dict]) -> str:
|
|
"""The text the agent reads INSTEAD of its reply going out.
|
|
|
|
A practice, not a prohibition, on the act checkpoint's model:
|
|
nothing here knows the reply is wrong. It names each rule with why it was
|
|
raised, gives the remedy as one call per rule, and says the reply may go
|
|
out unchanged — so a reader who finds the rules beside the point is out in
|
|
as many calls as there are rules, and is never held twice.
|
|
"""
|
|
if not held:
|
|
return ""
|
|
parts = []
|
|
for item in held:
|
|
why = (f"mounted on {item['moment']}" if item.get("moment")
|
|
else f"scores {item['score']} against this reply")
|
|
trigger = f"; it applies when {item['trigger']}" if item.get("trigger") else ""
|
|
parts.append(f"“{item['title']}” ({why}{trigger}) — get_rule({item['rule_id']})")
|
|
noun = "a standing rule" if len(held) == 1 else "standing rules"
|
|
# A mount that does not bear on this reply is a misfire worth one call:
|
|
# reports gather into an unmount proposal for the operator.
|
|
mounted = [item for item in held if item.get("moment")]
|
|
misfire = (
|
|
" If one mounted on a moment has nothing to do with this reply, "
|
|
f"rule_misfired({mounted[0]['rule_id']}, \"{mounted[0]['moment']}\", why) "
|
|
"records that."
|
|
if mounted else ""
|
|
)
|
|
return (
|
|
f"Held for one read before this reply goes out: {noun} this session "
|
|
f"has not opened: " + "; ".join(parts) + ". Read "
|
|
+ ("it" if len(held) == 1 else "them")
|
|
+ ", then send the reply — unchanged if it already does what the rule "
|
|
"asks, which is a judgement only you can make." + misfire
|
|
+ " This check runs once per rule; the rewrite is never held."
|
|
)
|
|
|
|
|
|
async def reply_hold(
|
|
user_id: int, reply: str, *, project_id: int | None = None,
|
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
|
stopped: frozenset[int] = frozenset(),
|
|
) -> dict:
|
|
"""Whether this finished reply is held, and in what words.
|
|
|
|
`held` is what the session OPENED (the act checkpoint's exemption);
|
|
`stopped` is what an earlier hold already put in front of it, so a rule
|
|
holds a session once. Past the act checkpoint's per-session cap nothing
|
|
holds — a mis-set bar degrades to a quiet session, never a stuck one.
|
|
|
|
Returns {} or {"reason", "rule_ids", "moments"}. Fails open to {}.
|
|
"""
|
|
from grimoire.services import plugin_context as pc
|
|
from grimoire.services import rule_usage, rulebooks
|
|
from grimoire.services.retrieval_surfaces import budget_for, floor_for
|
|
|
|
try:
|
|
if not (reply or "").strip() or len(stopped) >= pc.CHECKPOINT_SESSION_CAP:
|
|
return {}
|
|
reached = reply_moments(reply)
|
|
names = [hit["moment"] for hit in reached]
|
|
skip = set(held) | set(stopped)
|
|
room = pc.CHECKPOINT_SESSION_CAP - len(stopped)
|
|
out: list[dict] = []
|
|
|
|
# The mounted half: deterministic, so every unopened rule on these
|
|
# moments that is declared to hold (`hold` or `enforce`) holds. An
|
|
# `inform` rule was put in front of the turn before the reply was
|
|
# written, and a preference claims no force. A mount conditional on
|
|
# a trigger holds only when the reply meets it.
|
|
board = await _board(user_id, project_id, text=reply)
|
|
gated = board.gated if board is not None else set()
|
|
for rule, at in await rulebooks.rules_on_moments(user_id, names, project_id or None):
|
|
if rule.id in skip or not rule_order.holds(rule) or (rule.id, at) in gated:
|
|
continue
|
|
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
|
|
"trigger": (rule.when_to_apply or "").strip()})
|
|
# Trimmed BEFORE recording: a rule the cap cut was shown to nobody.
|
|
out = out[:room]
|
|
mounted = [item["rule_id"] for item in out]
|
|
fresh = [rid for rid in mounted if rid not in exclude]
|
|
if fresh:
|
|
try:
|
|
rule_usage.record_rule_surfaced(
|
|
user_id=user_id, rule_ids=fresh, source=rp.MOMENT_RULE_SOURCE,
|
|
detail={item["rule_id"]: item["moment"] for item in out
|
|
if item["rule_id"] in fresh},
|
|
)
|
|
except Exception: # noqa: BLE001 - observation never breaks the observed
|
|
logger.debug("reply mount surfacing not recorded", exc_info=True)
|
|
|
|
# The semantic half: the backstop. A mounted rule already holding is
|
|
# treated as held here, so one rule is never named twice.
|
|
floor = await floor_for(user_id, rp.REPLY_RULE.source)
|
|
result = await rp.run_rule_arm(
|
|
rp.REPLY_RULE,
|
|
rp.RuleMoment(
|
|
user_id=user_id, query=_reply_query(reply), project_id=project_id,
|
|
where="to this reply", checkpoint_where="this reply",
|
|
exclude=exclude, held=frozenset(skip | set(mounted)),
|
|
),
|
|
floor=floor, budget=await budget_for(user_id, rp.REPLY_RULE.source),
|
|
io=pc._rule_io(), checkpoint_floor=floor,
|
|
)
|
|
if result.checkpoint and len(out) < room:
|
|
cp = result.checkpoint
|
|
out.append({"rule_id": cp["rule_id"], "title": cp["title"],
|
|
"score": cp["score"], "trigger": cp.get("trigger", "")})
|
|
|
|
if not out:
|
|
return {}
|
|
return {
|
|
"reason": reply_hold_reason(out),
|
|
"rule_ids": [item["rule_id"] for item in out],
|
|
"moments": names,
|
|
}
|
|
except Exception: # noqa: BLE001 - a recall aid never stops a session by failing
|
|
logger.debug("reply hold failed", exc_info=True)
|
|
return {}
|