feat(7728): typed triggers on a rule, and a rule says its piece once per session
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

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>
This commit is contained in:
2026-11-22 18:24:39 -05:00
co-authored by Claude Opus 5.5
parent 7df478550f
commit c9e64450ba
21 changed files with 1093 additions and 41 deletions
+40 -1
View File
@@ -23,6 +23,7 @@ from grimoire.models.family import (
)
from grimoire.models.rulebook import (
RuleRelation, rule_moments as rule_moments_t, rule_systems as rule_systems_t,
rule_triggers as rule_triggers_t,
)
from grimoire.models.lesson_rule_link import LessonNoRule, LessonRuleLink
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
@@ -113,7 +114,9 @@ logger = logging.getLogger(__name__)
# section still restore — the key is simply not read.
# v28 instance_id in the header: the id lineage of the store the backup came
# from. A live instance rolls back only to a backup with its own id.
BACKUP_VERSION = 28
# v29 rule_triggers: the typed predicates on the act that deliver a rule or
# make its mount conditional. Nothing in the rule's text records them.
BACKUP_VERSION = 29
# Every table this backup carries, by its REAL name. Paired with _NOT_INCLUDED
# below, these two lists must together account for the entire schema — which is
@@ -158,6 +161,7 @@ _BACKED_UP = [
"moment_mappings",
"rule_moments",
"rule_moment_judgments",
"rule_triggers",
# Family canon. `platforms` is global like
# canonical_systems and rides every export for the same reason: the rows
# below name platforms by slug, and a partial catalog restores partial
@@ -802,6 +806,15 @@ def _rule_moment_rows(rows) -> list[dict]:
return [{"rule_id": rule_id, "moment": moment} for rule_id, moment in rows]
def _rule_trigger_rows(rows) -> list[dict]:
"""A rule's triggers. Kind, pattern and moment mean the same on every
install, so only the rule id needs remapping on the way back in."""
return [
{"rule_id": rule_id, "kind": kind, "pattern": pattern, "moment": moment or ""}
for rule_id, kind, pattern, moment in rows
]
def _rule_moment_judgment_rows(rows) -> list[dict]:
"""Proposals and judgments about a rule's moments (v23). The rule id is a
SOURCE id, remapped at restore; the moment is a catalog name."""
@@ -1020,6 +1033,12 @@ async def export_full_backup() -> dict:
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
.order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
)).all()
rule_trigger_rows = (await session.execute(
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
.order_by(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
)).all()
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
)).scalars().all()
@@ -1112,6 +1131,7 @@ async def export_full_backup() -> dict:
"canonical_systems": _canonical_system_rows(canonical_systems),
"rule_systems": _rule_system_rows(rule_system_rows),
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
@@ -1273,6 +1293,11 @@ async def export_user_backup(user_id: int) -> dict:
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
.where(rule_moments_t.c.rule_id.in_(_rule_ids))
)).all() if _rule_ids else []
rule_trigger_rows = (await session.execute(
select(rule_triggers_t.c.rule_id, rule_triggers_t.c.kind,
rule_triggers_t.c.pattern, rule_triggers_t.c.moment)
.where(rule_triggers_t.c.rule_id.in_(_rule_ids))
)).all() if _rule_ids else []
rule_moment_judgments = (await session.execute(
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
)).scalars().all() if _rule_ids else []
@@ -1399,6 +1424,7 @@ async def export_user_backup(user_id: int) -> dict:
"canonical_systems": _canonical_system_rows(canonical_systems),
"rule_systems": _rule_system_rows(rule_system_rows),
"rule_moments": _rule_moment_rows(rule_moment_rows),
"rule_triggers": _rule_trigger_rows(rule_trigger_rows),
"rule_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
"rule_relations": _rule_relation_rows(rule_relations),
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
@@ -2421,6 +2447,7 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
"code_shape_uses": 0, "canonical_systems": 0,
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
"rule_triggers": 0,
"rule_relations": 0, "rule_versions": 0,
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
"lesson_no_rule": 0, "moment_mappings": 0,
@@ -2618,6 +2645,18 @@ async def _load_v2(session, data: dict, maps: "_Maps", *, keep_ids: bool) -> dic
))
stats["rule_moments"] += 1
# A rule's triggers (v29), the same join-table shape; archives before
# v29 carry none.
for rt in data.get("rule_triggers", []):
mapped_rule = maps.rules.get(rt.get("rule_id", 0))
kind, pattern = rt.get("kind"), rt.get("pattern")
if mapped_rule is None or kind not in ("tool", "path", "command", "keyword") or not pattern:
continue
await session.execute(rule_triggers_t.insert().values(
rule_id=mapped_rule, kind=kind, pattern=pattern, moment=rt.get("moment") or "",
))
stats["rule_triggers"] += 1
# Proposals and judgments about those mounts (v23); archives before
# v23 carry none, and every rule restores unjudged.
for rj in data.get("rule_moment_judgments", []):
+42 -8
View File
@@ -32,6 +32,7 @@ def _io() -> rp.MomentIO:
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,
)
@@ -52,6 +53,8 @@ async def reachable_tools(user_id: int) -> list[str]:
# 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)
@@ -62,19 +65,45 @@ async def reachable_tools(user_id: int) -> list[str]:
}
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."""
"""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(),
io=_io(), board=board,
)
@@ -83,12 +112,14 @@ async def deliver_for_act(
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 mounted rules they deliver."""
"""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 {})
if not reached:
return [], rp.RuleResult()
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,
user_id, reached, project_id=project_id, exclude=exclude, held=held, board=board,
)
return reached, result
@@ -294,9 +325,12 @@ async def reply_hold(
out: list[dict] = []
# The mounted half: deterministic, so every unopened RULE on these
# moments holds. A preference claims no such force.
# moments holds. A preference claims no such 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 rule.kind == "preference":
if rule.id in skip or rule.kind == "preference" 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()})
+1
View File
@@ -983,6 +983,7 @@ def _rule_io() -> rp.RuleIO:
record_rule_surfaced=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,
)
+73 -15
View File
@@ -583,6 +583,9 @@ class RuleIO:
record_delivery: Callable[..., Any] | None = None
"""`rule_deliveries.record`: each line shown, against the session the
door bound. None records nothing."""
retired: Callable[..., Any] | None = None
"""`rule_deliveries.retired`: the repeats this session has already had
its one reminder of. None retires nothing."""
@dataclass(frozen=True)
@@ -792,6 +795,31 @@ def _record_delivery(io, moment: RuleMoment, source: str, shown: list[tuple[int,
_telemetry_failed(source)
async def _retired(io, moment: RuleMoment, rules) -> set[int]:
"""The rules to leave out because this session has had its reminder.
A rule's life in a session is one full line, one reminder, then silence,
so a long session is not re-pointed at the same rule on every call. Only
a repeat can be retired; a rule the session opened keeps its own line,
and a rule that holds stays armed until it is opened. {} when the door
keeps no deliveries or the read fails.
"""
if io.retired is None:
return set()
ids = [
rule.id for rule in rules
if rule.id in moment.exclude and rule.id not in moment.held
and getattr(rule, "enforcement", "inform") != "hold"
]
if not ids:
return set()
try:
return set(await io.retired(moment.user_id, ids) or ())
except Exception: # noqa: BLE001 - a lifecycle read never withholds a fresh line
logger.debug("rule retirement unreadable", exc_info=True)
return set()
async def _history(io, moment: RuleMoment, pairs: list[tuple[int, str]]) -> dict[int, float]:
"""Each rule's open rate where it is about to be delivered; {} when the
door has no history to read or the read fails — unknown, never an error."""
@@ -828,6 +856,10 @@ async def run_rule_arm(
shown, _slot_id = await _reserve_slot_for_preference(
io, moment, shown, floor=floor,
)
# A repeat already reminded once this session says nothing more.
gone = await _retired(io, moment, [rule for _s, rule in shown])
if gone:
shown = [(s, rule) for s, rule in shown if rule.id not in gone]
# `shown`, not `fresh`: a call whose only hit is a repeat
# still has something to say, it just says it differently.
if not shown:
@@ -1650,6 +1682,8 @@ class MomentIO:
"""As on `RuleIO`."""
record_delivery: Callable[..., Any] | None = None
"""As on `RuleIO`."""
retired: Callable[..., Any] | None = None
"""As on `RuleIO`."""
def _reached_by(hit: dict) -> str:
@@ -1659,7 +1693,7 @@ def _reached_by(hit: dict) -> str:
async def run_moment_arm(
reached: list[dict], moment: RuleMoment, *, io: MomentIO,
limit: int = MOMENT_RULE_LIMIT,
limit: int = MOMENT_RULE_LIMIT, board: Any = None,
) -> RuleResult:
"""Deliver the rules mounted on the moments this act reached.
@@ -1670,42 +1704,66 @@ async def run_moment_arm(
`unmap_action`. Fresh rules come first and carry their
trigger; a rule the session was already shown is cited, not repeated in
full. Fails open to an empty result.
`board` is `rule_triggers.board`'s answer for this act: a conditional
mount whose condition the act missed is dropped, one it met ranks as
triggered, and a rule an unscoped trigger fired joins the mounted ones
with its trigger named as what reached it. None means no triggers.
"""
try:
names = [hit["moment"] for hit in reached]
if not names:
return RuleResult()
pairs = await io.lookup(moment.user_id, names, moment.project_id or None)
if not pairs:
fired = list(board.fired) if board is not None else []
if not names and not fired:
return RuleResult()
pairs = await io.lookup(moment.user_id, names, moment.project_id or None) if names else []
by_moment = {hit["moment"]: hit for hit in reached}
# (rule, at, where, specificity) for every candidate line.
cands = []
for rule, at in pairs or []:
if board is not None and (rule.id, at) in board.gated:
continue
met = board is not None and (rule.id, at) in board.matched
cands.append((rule, at, f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
rule_order.BY_TRIGGER if met else rule_order.BY_MOUNT))
taken = {c[0].id for c in cands}
for rule, trig in fired:
if rule.id in taken:
continue
taken.add(rule.id)
cands.append((rule, trig.key, f"its trigger {trig.describe()} matched this act",
rule_order.BY_TRIGGER))
gone = await _retired(io, moment, [rule for rule, _a, _w, _s in cands])
if gone:
cands = [c for c in cands if c[0].id not in gone]
if not cands:
return RuleResult()
# The one delivery order (services/rule_order.py), then the cap — so
# what a crowded moment drops is the lowest-ranked, not the last
# mounted. Ties keep catalog order.
history = await _history(io, moment, [(rule.id, at) for rule, at in pairs])
history = await _history(io, moment, [(rule.id, at) for rule, at, _w, _s in cands])
shown = [
c.extra for c in rule_order.ordered(
rule_order.Candidate(
rule=rule, specificity=rule_order.BY_MOUNT,
rule=rule, specificity=spec,
opened_rate=history.get(rule.id),
seen=rule.id in moment.exclude, extra=(rule, at),
seen=rule.id in moment.exclude, extra=(rule, at, where),
)
for rule, at in pairs
for rule, at, where, spec in cands
)
][:limit]
lines = []
for rule, at in shown:
for rule, at, where in shown:
seen = rule.id in moment.exclude
lines.append(_rule_hint_line(
rule,
where=f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
where=where,
seen=seen, held=rule.id in moment.held,
# A repeat is cited rather than quoted: the session was told
# which moment brought it the first time.
compact=seen,
))
fresh = [(rule, at) for rule, at in shown if rule.id not in moment.exclude]
fresh = [(rule, at) for rule, at, _where in shown if rule.id not in moment.exclude]
rule_ids = [rule.id for rule, _at in fresh]
if rule_ids:
try:
@@ -1717,12 +1775,12 @@ async def run_moment_arm(
except Exception: # noqa: BLE001 - observation never breaks the observed
_telemetry_failed(MOMENT_RULE_SOURCE)
_record_delivery(io, moment, MOMENT_RULE_SOURCE, [
(rule.id, at, rule.id in moment.exclude) for rule, at in shown
(rule.id, at, rule.id in moment.exclude) for rule, at, _where in shown
])
return RuleResult(
lines=lines, rule_ids=rule_ids,
shown_rule_ids=[rule.id for rule, _at in shown],
shown=[(None, rule) for rule, _at in shown],
shown_rule_ids=[rule.id for rule, _at, _where in shown],
shown=[(None, rule) for rule, _at, _where in shown],
)
except Exception: # noqa: BLE001 - a recall aid never breaks its act
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
+28 -1
View File
@@ -24,7 +24,7 @@ from datetime import datetime, timedelta, timezone
from sqlalchemy import and_, case, delete, func, select, tuple_, update
from grimoire.models import async_session
from grimoire.models.rule_delivery import FORMS, FULL, RuleDelivery
from grimoire.models.rule_delivery import FORMS, FULL, REPEAT, RuleDelivery
from grimoire.services import rule_order
from grimoire.services.background import spawn
@@ -151,6 +151,33 @@ async def history(user_id: int, pairs: list[tuple[int, str]]) -> dict[int, float
}
async def retired(user_id: int, rule_ids: list[int]) -> set[int]:
"""Which of these rules this session has already been reminded of.
A rule's life in a session is one full line, then one reminder, then
silence: retired is "the latest delivery of it in the bound session was a
reminder". A full delivery re-arms it, which is what happens once the
plugin's ledger forgets it (after a compaction, or as it ages out): the
next line is full again, then one reminder, then silence again.
"""
sid = _session.get()
wanted = sorted({int(r) for r in rule_ids})
if not sid or not wanted:
return set()
async with async_session() as session:
rows = (await session.execute(
select(RuleDelivery.rule_id, RuleDelivery.form)
.where(
RuleDelivery.user_id == user_id,
RuleDelivery.session_id == sid,
RuleDelivery.rule_id.in_(wanted),
)
.distinct(RuleDelivery.rule_id)
.order_by(RuleDelivery.rule_id, RuleDelivery.delivered_at.desc(), RuleDelivery.id.desc())
)).all()
return {int(rid) for rid, form in rows if form == REPEAT}
async def prune(retain_days: int = RETAIN_DAYS) -> int:
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
async with async_session() as session:
+289
View File
@@ -0,0 +1,289 @@
"""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
+11 -3
View File
@@ -470,9 +470,9 @@ async def co_surfaced_partners(user_id: int, rule_ids: list[int]) -> list[Rule]:
async def rule_detail(
user_id: int, rule: Rule, system_ids: list[int] | None = None,
moments: list[str] | None = None,
moments: list[str] | None = None, triggers: list | None = None,
) -> dict:
"""The full record, with its areas, moments and edges attached.
"""The full record, with its areas, moments, triggers and edges attached.
ONE seam for both doors and every write path, so create, update and get
cannot disagree about what a rule looks like coming back — the same
@@ -482,15 +482,21 @@ async def rule_detail(
`system_ids=None` / `moments=None` mean "leave them alone"; a list
(including []) REPLACES them. Doors validate `moments` with
`moments.require_moments` BEFORE their create, so an unknown name is
refused without leaving a rule behind.
refused without leaving a rule behind; `triggers` the same way, with
`rule_triggers.require_triggers`, and it replaces them the same way.
"""
from grimoire.services import rule_triggers
if system_ids is not None:
await set_rule_systems(rule.id, user_id, system_ids)
if moments is not None:
await set_rule_moments(rule.id, user_id, moments)
if triggers is not None:
await rule_triggers.set_rule_triggers(rule.id, triggers)
data = rule.to_dict()
systems = (await list_rule_systems([rule.id])).get(rule.id, [])
mounted = (await list_rule_moments([rule.id])).get(rule.id, [])
triggered = (await rule_triggers.list_rule_triggers([rule.id])).get(rule.id, [])
relations = (await list_rule_relations([rule.id])).get(rule.id, [])
# Attached only when present: an empty key reads as a capability
# the record has and isn't using, which is a different claim.
@@ -498,6 +504,8 @@ async def rule_detail(
data["systems"] = systems
if mounted:
data["moments"] = mounted
if triggered:
data["triggers"] = triggered
if relations:
data["relations"] = relations
# The concrete situations judged (or proposed) to be instances of this