Files
FabledGrimoire/src/grimoire/services/rule_triggers.py
T
bvandeusenandClaude Opus 5.5 c9e64450ba
CI & Build / TypeScript typecheck (push) Successful in 34s
CI & Build / Plugin hooks (push) Successful in 22s
CI & Build / Python lint (push) Successful in 3s
CI & Build / Python tests (push) Failing after 1m48s
CI & Build / integration (push) Successful in 2m8s
CI & Build / Build & push image (push) Skipped
feat(7728): typed triggers on a rule, and a rule says its piece once per session
Triggers (migration 0130, table rule_triggers): a rule can name the act it
applies to, as a tool, a path glob, a command head or a keyword, checked
exactly against the act rather than by resemblance. With no moment a
trigger delivers its rule on any matching act, even one that reaches no
moment; scoped to a moment, it makes the rule's mount there conditional
on the act matching. A triggered line ranks above a mounted one in the
delivery order and names the trigger that fired. Writable through every
MCP and REST rule door, carried by backup (version 29), and edited in the
rule editor under "Acts that trigger it". The plugin's catch-all hook is
told which tools a trigger can reach.

Lifecycle: a rule's life in a session is one full line, one reminder,
then silence. A repeat whose latest delivery in the session was already a
reminder is left out of both rule arms. A rule that holds stays armed
until it is opened, an opened rule keeps its line, and a full delivery
(after a compaction or once the ledger ages it out) re-arms it. Read from
the delivery records, so it needs no new plugin ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:24:39 -05:00

290 lines
12 KiB
Python

"""A rule's triggers: typed predicates on the act, checked in code.
A mount says WHEN a rule applies (a moment of work); a trigger says WHAT act
it applies to, in terms the act itself carries, so it is matched exactly and
never by resemblance:
- `tool` — the tool called, as its key (`bash`, `write`, `update_task`); a
`*` in the pattern matches any run of characters (`*_task`).
- `path` — a file the act touches (`file_path`, `path`, `notebook_path`),
against a glob: `*` within one directory, `**` across directories, `?` one
character. A glob without a leading `/` matches from any directory, so
`migrations/*.py` matches `/repo/alembic/migrations/0001.py`.
- `command` — the head of a command the act runs, segment by segment, the way
moment mappings match it: `git push` matches `git push origin dev` and
`make && git push`, not `git pushx`.
- `keyword` — a word or phrase in the command, the content written or the
reply, matched whole and case-insensitively.
A trigger with no moment delivers its rule on any act that matches it. A
trigger scoped to a moment makes the rule's mount on that moment conditional:
the mount delivers only on an act that matches one of its triggers there, so
a rule about migrations can sit on `work.change` without arriving at every
edit. Where no act is known (the turn's own reply), only keyword triggers can
be checked, against the reply text.
"""
from __future__ import annotations
import re
from dataclasses import dataclass, field
from sqlalchemy import delete, select
from grimoire.models import async_session
from grimoire.services import moment_actions
TOOL, PATH, COMMAND, KEYWORD = "tool", "path", "command", "keyword"
KINDS = (TOOL, PATH, COMMAND, KEYWORD)
PATTERN_MAX = 200
TRIGGERS_MAX = 20
# The input fields a path trigger reads, across the file tools.
PATH_FIELDS = ("file_path", "path", "notebook_path")
# The input fields a keyword trigger reads.
TEXT_FIELDS = ("command", "content", "new_string", "query", "prompt")
# The tools a path, command or keyword trigger can be reached through — what
# the plugin's catch-all hook must forward for such a trigger to be checked.
PATH_TOOLS = frozenset({"write", "edit", "multiedit", "notebookedit", "read"})
COMMAND_TOOLS = moment_actions.COMMAND_TOOLS
KEYWORD_TOOLS = COMMAND_TOOLS | frozenset({"write", "edit", "multiedit", "notebookedit"})
@dataclass(frozen=True)
class Trigger:
kind: str
pattern: str
moment: str = ""
def to_dict(self) -> dict:
out = {"kind": self.kind, "pattern": self.pattern}
if self.moment:
out["moment"] = self.moment
return out
def describe(self) -> str:
"""How a delivered line names what fired: "path `alembic/**`"."""
return f"{self.kind} `{self.pattern}`"
@property
def key(self) -> str:
"""Where a trigger delivers, for the delivery record and its history."""
return f"{self.kind}:{self.pattern}"
# ── validation ───────────────────────────────────────────────────────────
def require_trigger(raw) -> Trigger:
"""One trigger, normalised, or a refusal that says what is accepted."""
from grimoire.services.moments import require_moment
if not isinstance(raw, dict):
raise ValueError("a trigger is {kind, pattern, moment?}")
kind = str(raw.get("kind") or "").strip().lower()
if kind not in KINDS:
raise ValueError(f"unknown trigger kind {raw.get('kind')!r}. Kinds are: {', '.join(KINDS)}")
pattern = " ".join(str(raw.get("pattern") or "").split())
if not pattern:
raise ValueError(f"a {kind} trigger needs a pattern")
if len(pattern) > PATTERN_MAX:
raise ValueError(f"a trigger pattern is at most {PATTERN_MAX} characters")
if kind == TOOL:
pattern = moment_actions.tool_key(pattern)
elif kind in (COMMAND, KEYWORD):
pattern = pattern.lower()
moment = str(raw.get("moment") or "").strip()
return Trigger(kind, pattern, require_moment(moment) if moment else "")
def require_triggers(raw) -> list[Trigger] | None:
"""A rule's triggers, or the first refusal. None leaves them alone; a
list, [] included, is the whole set after the write. All are checked
before any is stored."""
if raw is None:
return None
if not isinstance(raw, list):
raise ValueError("triggers is a list of {kind, pattern, moment?}")
out = list(dict.fromkeys(require_trigger(item) for item in raw))
if len(out) > TRIGGERS_MAX:
raise ValueError(f"a rule carries at most {TRIGGERS_MAX} triggers")
return out
# ── matching ─────────────────────────────────────────────────────────────
def _glob(pattern: str) -> re.Pattern:
out, i = [], 0
while i < len(pattern):
if pattern.startswith("**/", i):
out.append("(?:.*/)?")
i += 3
elif pattern.startswith("**", i):
out.append(".*")
i += 2
elif pattern[i] == "*":
out.append("[^/]*")
i += 1
elif pattern[i] == "?":
out.append("[^/]")
i += 1
else:
out.append(re.escape(pattern[i]))
i += 1
body = "".join(out)
anchor = "^" if pattern.startswith("/") else "(?:^|/)"
return re.compile(anchor + body + "$")
def _tool_glob(pattern: str) -> re.Pattern:
return re.compile("^" + ".*".join(re.escape(p) for p in pattern.split("*")) + "$")
def _texts(tool_input: dict) -> list[str]:
return [v for k in TEXT_FIELDS if isinstance(v := tool_input.get(k), str)]
def _has_phrase(text: str, phrase: str) -> bool:
return re.search(r"(?<!\w)" + re.escape(phrase) + r"(?!\w)", text, re.IGNORECASE) is not None
def matches(trigger: Trigger, tool: str | None, tool_input: dict | None, text: str = "") -> bool:
"""Whether this act — or, with no tool, this text — fires the trigger."""
tool_input = tool_input if isinstance(tool_input, dict) else {}
if trigger.kind == KEYWORD:
return any(_has_phrase(t, trigger.pattern) for t in [text, *_texts(tool_input)] if t)
if not tool:
return False
if trigger.kind == TOOL:
return _tool_glob(trigger.pattern).match(moment_actions.tool_key(tool)) is not None
if trigger.kind == PATH:
rx = _glob(trigger.pattern)
return any(isinstance(p := tool_input.get(f), str) and rx.search(p) for f in PATH_FIELDS)
if trigger.kind == COMMAND:
command = tool_input.get(moment_actions.COMMAND_FIELD)
return moment_actions.action_matches(
moment_actions.Action(tool=tool, match=trigger.pattern, moment=""),
tool, {moment_actions.COMMAND_FIELD: command},
) if isinstance(command, str) else False
return False
def tools_for(trigger: Trigger) -> set[str]:
"""The tool keys an act must be made through for this trigger to fire.
A tool pattern with a `*` cannot be listed, and reaches nothing here."""
if trigger.kind == TOOL:
return set() if "*" in trigger.pattern else {trigger.pattern}
if trigger.kind == PATH:
return set(PATH_TOOLS)
if trigger.kind == COMMAND:
return set(COMMAND_TOOLS)
return set(KEYWORD_TOOLS)
# ── storage ──────────────────────────────────────────────────────────────
async def set_rule_triggers(rule_id: int, triggers: list[Trigger]) -> None:
"""Replace a rule's triggers with these. The caller has checked write access."""
from grimoire.models.rulebook import rule_triggers as t
async with async_session() as session:
await session.execute(delete(t).where(t.c.rule_id == rule_id))
if triggers:
await session.execute(t.insert(), [
{"rule_id": rule_id, "kind": tr.kind, "pattern": tr.pattern, "moment": tr.moment}
for tr in triggers
])
await session.commit()
async def list_rule_triggers(rule_ids: list[int]) -> dict[int, list[dict]]:
"""Each rule's triggers, unscoped first, in a stable order."""
from grimoire.models.rulebook import rule_triggers as t
if not rule_ids:
return {}
async with async_session() as session:
rows = (await session.execute(
select(t.c.rule_id, t.c.kind, t.c.pattern, t.c.moment)
.where(t.c.rule_id.in_(rule_ids))
.order_by(t.c.rule_id, t.c.moment, t.c.kind, t.c.pattern)
)).all()
out: dict[int, list[dict]] = {}
for rule_id, kind, pattern, moment in rows:
out.setdefault(rule_id, []).append(Trigger(kind, pattern, moment or "").to_dict())
return out
async def _in_scope(user_id: int, project_id: int | None, *, everywhere: bool = False):
"""Every live rule with a trigger that this caller may be shown here, with
its triggers: `[(Rule, [Trigger, ...])]`."""
from grimoire.models.rulebook import Rule
from grimoire.models.rulebook import rule_triggers as t
from grimoire.services.rule_scope import joined_to_homes, rule_home
home = await rule_home(user_id, project_id, everywhere=everywhere)
async with async_session() as session:
rows = (await session.execute(
joined_to_homes(
select(Rule, t.c.kind, t.c.pattern, t.c.moment)
.select_from(t)
.join(Rule, Rule.id == t.c.rule_id)
)
.where(Rule.deleted_at.is_(None), home)
.order_by(Rule.id, t.c.kind, t.c.pattern)
)).all()
by_rule: dict[int, tuple] = {}
for rule, kind, pattern, moment in rows:
by_rule.setdefault(rule.id, (rule, []))[1].append(Trigger(kind, pattern, moment or ""))
return list(by_rule.values())
# ── the eligibility board ────────────────────────────────────────────────
@dataclass
class Board:
"""What the triggers say about one act, for the moment arm.
`gated` — (rule_id, moment) mounts that are conditional and whose
condition this act did not meet: not delivered. `matched` — conditional
mounts this act met: delivered as triggered. `fired` — rules an unscoped
trigger delivers on this act, each with the trigger that fired.
"""
gated: set[tuple[int, str]] = field(default_factory=set)
matched: set[tuple[int, str]] = field(default_factory=set)
fired: list[tuple[object, Trigger]] = field(default_factory=list)
async def board(
user_id: int, project_id: int | None, *,
tool: str | None = None, tool_input: dict | None = None, text: str = "",
) -> Board:
"""Check every in-scope trigger against this act (or this text)."""
out = Board()
for rule, triggers in await _in_scope(user_id, project_id):
first_unscoped = None
for trig in triggers:
hit = matches(trig, tool, tool_input, text)
if trig.moment:
pair = (rule.id, trig.moment)
if hit:
out.matched.add(pair)
out.gated.discard(pair)
elif pair not in out.matched:
out.gated.add(pair)
elif hit and first_unscoped is None:
first_unscoped = trig
if first_unscoped is not None:
out.fired.append((rule, first_unscoped))
return out
async def reachable_tools(user_id: int) -> set[str]:
"""The tool keys a call to which could fire an unscoped trigger, in any
home — a superset, for the plugin's catch-all filter."""
keys: set[str] = set()
for _rule, triggers in await _in_scope(user_id, None, everywhere=True):
for trig in triggers:
if not trig.moment:
keys |= tools_for(trig)
return keys