From c9e64450ba6fac6b2d42d5a416f02667616923ca Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Sun, 22 Nov 2026 18:24:39 -0500 Subject: [PATCH] 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 --- alembic/versions/0130_rule_triggers.py | 38 +++ frontend/src/api/rulebooks.ts | 15 + .../components/rules/RuleEditorSlideOver.vue | 102 +++++++ src/grimoire/mcp/tools/rulebooks.py | 76 ++++- src/grimoire/models/rulebook.py | 16 + src/grimoire/routes/rulebooks.py | 26 +- src/grimoire/services/backup.py | 41 ++- src/grimoire/services/moment_delivery.py | 50 ++- src/grimoire/services/plugin_context.py | 1 + src/grimoire/services/retrieval_pipeline.py | 88 +++++- src/grimoire/services/rule_deliveries.py | 29 +- src/grimoire/services/rule_triggers.py | 289 ++++++++++++++++++ src/grimoire/services/rulebooks.py | 14 +- tests/conftest.py | 17 ++ tests/helpers.py | 2 +- tests/test_integration_rule_deliveries.py | 20 ++ tests/test_integration_rule_triggers.py | 107 +++++++ tests/test_rule_moment_doors.py | 4 +- tests/test_rule_order.py | 43 +++ tests/test_rule_triggers.py | 152 +++++++++ tests/test_services_backup.py | 4 +- 21 files changed, 1093 insertions(+), 41 deletions(-) create mode 100644 alembic/versions/0130_rule_triggers.py create mode 100644 src/grimoire/services/rule_triggers.py create mode 100644 tests/test_integration_rule_triggers.py create mode 100644 tests/test_rule_triggers.py diff --git a/alembic/versions/0130_rule_triggers.py b/alembic/versions/0130_rule_triggers.py new file mode 100644 index 00000000..c0504d29 --- /dev/null +++ b/alembic/versions/0130_rule_triggers.py @@ -0,0 +1,38 @@ +"""rule triggers — typed predicates on the act that deliver a rule, checked in code + +Revision ID: 0130 +Revises: 0129 +Create Date: 2026-11-22 + +A trigger is a kind (tool, path, command, keyword) and a pattern, optionally +scoped to a moment. Unscoped, it delivers the rule on any act that matches; +scoped, it makes the rule's mount on that moment conditional on the act +matching. Matched in code against the act, never by embedding. +""" +import sqlalchemy as sa +from alembic import op + +revision = "0130" +down_revision = "0129" +branch_labels = None +depends_on = None + + +def upgrade() -> None: + op.create_table( + "rule_triggers", + sa.Column("rule_id", sa.BigInteger(), + sa.ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True), + sa.Column("kind", sa.Text(), primary_key=True), + sa.Column("pattern", sa.Text(), primary_key=True), + sa.Column("moment", sa.Text(), primary_key=True, server_default=""), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=True), + sa.CheckConstraint( + "kind IN ('tool', 'path', 'command', 'keyword')", name="ck_rule_triggers_kind", + ), + sa.CheckConstraint("length(pattern) > 0", name="ck_rule_triggers_pattern"), + ) + + +def downgrade() -> None: + op.drop_table("rule_triggers") diff --git a/frontend/src/api/rulebooks.ts b/frontend/src/api/rulebooks.ts index d3c19573..7f20f6b1 100644 --- a/frontend/src/api/rulebooks.ts +++ b/frontend/src/api/rulebooks.ts @@ -62,6 +62,17 @@ export type RuleKind = "rule" | "preference"; export type RuleEnforcement = "enforce" | "hold" | "inform"; /** How a rule ranks among rules of the same enforcement at a crowded moment. */ export type RuleSalience = "high" | "normal" | "low"; +/** What a trigger is matched against on the act: the tool called, a path it + * touches, the head of a command it runs, or a word in what it writes. */ +export type RuleTriggerKind = "tool" | "path" | "command" | "keyword"; +/** A typed predicate on the act, checked exactly. With no `moment` it + * delivers the rule on any matching act; with one, it makes the rule's + * mount on that moment conditional on the act matching. */ +export interface RuleTrigger { + kind: RuleTriggerKind; + pattern: string; + moment?: string; +} /** A new record opened from somewhere that already knows what it is for — * "Adjust this" on a reply shape opens a preference mounted on that shape's @@ -105,6 +116,8 @@ export interface Rule { /** The moments this rule arrives at whenever they happen, * in catalog order. Present only when the rule is mounted. */ moments?: string[]; + /** Present only when the rule has triggers. */ + triggers?: RuleTrigger[]; relations?: RuleRelation[]; /** The lessons that point at this rule — the concrete * situations judged instances of it, plus any suggested and awaiting a @@ -241,6 +254,8 @@ export interface RuleWrite { system_ids: number[]; /** Replaces the set; [] unmounts the rule from every moment. */ moments: string[]; + /** Replaces the set; [] clears every trigger. */ + triggers: RuleTrigger[]; arose_from_id: number | null; verify_with: string; expires_when: string; diff --git a/frontend/src/components/rules/RuleEditorSlideOver.vue b/frontend/src/components/rules/RuleEditorSlideOver.vue index b0f9954f..7fcdbd52 100644 --- a/frontend/src/components/rules/RuleEditorSlideOver.vue +++ b/frontend/src/components/rules/RuleEditorSlideOver.vue @@ -9,6 +9,7 @@ import { apiErrorMessage } from "@/api/client"; import { listRulebooks, listTopics, type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience, + type RuleTrigger, type RuleTriggerKind, } from "@/api/rulebooks"; const props = defineProps<{ @@ -50,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []); const procedureMoments = computed(() => ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)), ); +// The acts this rule is triggered by, checked exactly on the server. +const triggers = ref([]); +const triggerKind = ref("path"); +const triggerPattern = ref(""); +const triggerMoment = ref(""); +const triggerError = ref(""); +const TRIGGER_KINDS: { value: RuleTriggerKind; label: string; placeholder: string }[] = [ + { value: "path", label: "Path", placeholder: "alembic/versions/*.py — a file the act touches" }, + { value: "command", label: "Command", placeholder: "git push — the head of a command it runs" }, + { value: "tool", label: "Tool", placeholder: "update_task — the tool it calls" }, + { value: "keyword", label: "Keyword", placeholder: "migration — a word in what it writes" }, +]; +const triggerPlaceholder = computed( + () => TRIGGER_KINDS.find((k) => k.value === triggerKind.value)?.placeholder ?? "", +); + +function triggerLabel(t: RuleTrigger) { + return TRIGGER_KINDS.find((k) => k.value === t.kind)?.label ?? t.kind; +} + +function addTrigger() { + const pattern = triggerPattern.value.trim().replace(/\s+/g, " "); + if (!pattern) return; + const moment = triggerMoment.value || undefined; + const same = (t: RuleTrigger) => + t.kind === triggerKind.value && t.pattern === pattern && (t.moment ?? "") === (moment ?? ""); + if (triggers.value.some(same)) { + triggerError.value = "This rule already has that trigger."; + return; + } + triggerError.value = ""; + triggers.value.push({ kind: triggerKind.value, pattern, ...(moment ? { moment } : {}) }); + triggerPattern.value = ""; +} + +function removeTrigger(at: number) { + triggers.value.splice(at, 1); +} const why = ref(""); const howToApply = ref(""); const verifyWith = ref(""); @@ -138,6 +177,7 @@ async function load() { salience.value = r.salience ?? "normal"; systemIds.value = (r.systems ?? []).map((sys) => sys.id); ruleMoments.value = [...(r.moments ?? [])]; + triggers.value = (r.triggers ?? []).map((t) => ({ ...t })); why.value = r.why || ""; howToApply.value = r.how_to_apply || ""; verifyWith.value = r.verify_with || ""; @@ -152,6 +192,7 @@ async function load() { salience.value = "normal"; systemIds.value = []; ruleMoments.value = [...(props.preset?.moments ?? [])]; + triggers.value = []; why.value = ""; howToApply.value = ""; verifyWith.value = ""; @@ -159,6 +200,9 @@ async function load() { } procedureDraft.value = ""; procedureError.value = ""; + triggerPattern.value = ""; + triggerMoment.value = ""; + triggerError.value = ""; await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]); } @@ -204,6 +248,8 @@ async function save() { // Always sent, for system_ids' reason: the server reads the list as the // whole set, so unticking the last moment actually unmounts the rule. moments: ruleMoments.value, + // Always sent, for the same reason: the list is the whole set. + triggers: triggers.value, why: why.value, how_to_apply: howToApply.value, // Always sent, including empty. The REST door maps "" to NULL, so @@ -391,6 +437,55 @@ watch(() => props.ruleId, load);

{{ procedureError }}

+
+ Acts that trigger it +

+ Matched exactly against what the work does, not by resemblance: a + path it touches, a command it runs, a tool it calls, a word in what it + writes. With no moment, the rule arrives on any act that matches. + With a moment, it arrives at that moment only when the act matches, + so a rule about migrations can sit where files change without arriving + at every edit. +

+
    +
  • + {{ triggerLabel(t) }} + {{ t.pattern }} + at {{ t.moment }} + +
  • +
+

No triggers: this rule arrives by its moments and by resemblance.

+
+ + + + +
+

{{ triggerError }}

+
+
Areas this rule is about