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
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:
@@ -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")
|
||||||
@@ -62,6 +62,17 @@ export type RuleKind = "rule" | "preference";
|
|||||||
export type RuleEnforcement = "enforce" | "hold" | "inform";
|
export type RuleEnforcement = "enforce" | "hold" | "inform";
|
||||||
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
|
/** How a rule ranks among rules of the same enforcement at a crowded moment. */
|
||||||
export type RuleSalience = "high" | "normal" | "low";
|
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 —
|
/** 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
|
* "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,
|
/** The moments this rule arrives at whenever they happen,
|
||||||
* in catalog order. Present only when the rule is mounted. */
|
* in catalog order. Present only when the rule is mounted. */
|
||||||
moments?: string[];
|
moments?: string[];
|
||||||
|
/** Present only when the rule has triggers. */
|
||||||
|
triggers?: RuleTrigger[];
|
||||||
relations?: RuleRelation[];
|
relations?: RuleRelation[];
|
||||||
/** The lessons that point at this rule — the concrete
|
/** The lessons that point at this rule — the concrete
|
||||||
* situations judged instances of it, plus any suggested and awaiting a
|
* situations judged instances of it, plus any suggested and awaiting a
|
||||||
@@ -241,6 +254,8 @@ export interface RuleWrite {
|
|||||||
system_ids: number[];
|
system_ids: number[];
|
||||||
/** Replaces the set; [] unmounts the rule from every moment. */
|
/** Replaces the set; [] unmounts the rule from every moment. */
|
||||||
moments: string[];
|
moments: string[];
|
||||||
|
/** Replaces the set; [] clears every trigger. */
|
||||||
|
triggers: RuleTrigger[];
|
||||||
arose_from_id: number | null;
|
arose_from_id: number | null;
|
||||||
verify_with: string;
|
verify_with: string;
|
||||||
expires_when: string;
|
expires_when: string;
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { apiErrorMessage } from "@/api/client";
|
|||||||
import {
|
import {
|
||||||
listRulebooks, listTopics,
|
listRulebooks, listTopics,
|
||||||
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
|
type Rule, type RuleEnforcement, type RuleKind, type RulePreset, type RuleSalience,
|
||||||
|
type RuleTrigger, type RuleTriggerKind,
|
||||||
} from "@/api/rulebooks";
|
} from "@/api/rulebooks";
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
@@ -50,6 +51,44 @@ const momentCatalog = computed(() => momentsStore.data?.moments ?? []);
|
|||||||
const procedureMoments = computed(() =>
|
const procedureMoments = computed(() =>
|
||||||
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
|
ruleMoments.value.filter((m) => m.startsWith(SKILL_PREFIX)),
|
||||||
);
|
);
|
||||||
|
// The acts this rule is triggered by, checked exactly on the server.
|
||||||
|
const triggers = ref<RuleTrigger[]>([]);
|
||||||
|
const triggerKind = ref<RuleTriggerKind>("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 why = ref("");
|
||||||
const howToApply = ref("");
|
const howToApply = ref("");
|
||||||
const verifyWith = ref("");
|
const verifyWith = ref("");
|
||||||
@@ -138,6 +177,7 @@ async function load() {
|
|||||||
salience.value = r.salience ?? "normal";
|
salience.value = r.salience ?? "normal";
|
||||||
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
|
systemIds.value = (r.systems ?? []).map((sys) => sys.id);
|
||||||
ruleMoments.value = [...(r.moments ?? [])];
|
ruleMoments.value = [...(r.moments ?? [])];
|
||||||
|
triggers.value = (r.triggers ?? []).map((t) => ({ ...t }));
|
||||||
why.value = r.why || "";
|
why.value = r.why || "";
|
||||||
howToApply.value = r.how_to_apply || "";
|
howToApply.value = r.how_to_apply || "";
|
||||||
verifyWith.value = r.verify_with || "";
|
verifyWith.value = r.verify_with || "";
|
||||||
@@ -152,6 +192,7 @@ async function load() {
|
|||||||
salience.value = "normal";
|
salience.value = "normal";
|
||||||
systemIds.value = [];
|
systemIds.value = [];
|
||||||
ruleMoments.value = [...(props.preset?.moments ?? [])];
|
ruleMoments.value = [...(props.preset?.moments ?? [])];
|
||||||
|
triggers.value = [];
|
||||||
why.value = "";
|
why.value = "";
|
||||||
howToApply.value = "";
|
howToApply.value = "";
|
||||||
verifyWith.value = "";
|
verifyWith.value = "";
|
||||||
@@ -159,6 +200,9 @@ async function load() {
|
|||||||
}
|
}
|
||||||
procedureDraft.value = "";
|
procedureDraft.value = "";
|
||||||
procedureError.value = "";
|
procedureError.value = "";
|
||||||
|
triggerPattern.value = "";
|
||||||
|
triggerMoment.value = "";
|
||||||
|
triggerError.value = "";
|
||||||
await Promise.all([canon.fetchCatalog(), momentsStore.load(), loadHomes()]);
|
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
|
// Always sent, for system_ids' reason: the server reads the list as the
|
||||||
// whole set, so unticking the last moment actually unmounts the rule.
|
// whole set, so unticking the last moment actually unmounts the rule.
|
||||||
moments: ruleMoments.value,
|
moments: ruleMoments.value,
|
||||||
|
// Always sent, for the same reason: the list is the whole set.
|
||||||
|
triggers: triggers.value,
|
||||||
why: why.value,
|
why: why.value,
|
||||||
how_to_apply: howToApply.value,
|
how_to_apply: howToApply.value,
|
||||||
// Always sent, including empty. The REST door maps "" to NULL, so
|
// Always sent, including empty. The REST door maps "" to NULL, so
|
||||||
@@ -391,6 +437,55 @@ watch(() => props.ruleId, load);
|
|||||||
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
|
<p v-if="procedureError" class="trigger-warning">{{ procedureError }}</p>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
|
|
||||||
|
<fieldset class="moments triggers">
|
||||||
|
<legend>Acts that trigger it</legend>
|
||||||
|
<p class="field-note intro">
|
||||||
|
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.
|
||||||
|
</p>
|
||||||
|
<ul v-if="triggers.length" class="trigger-list">
|
||||||
|
<li v-for="(t, i) in triggers" :key="`${t.kind}:${t.pattern}:${t.moment ?? ''}`" class="rule-chip">
|
||||||
|
<span class="trigger-kind">{{ triggerLabel(t) }}</span>
|
||||||
|
<code>{{ t.pattern }}</code>
|
||||||
|
<span v-if="t.moment" class="trigger-at">at <code>{{ t.moment }}</code></span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="chip-remove"
|
||||||
|
:aria-label="`Remove the ${triggerLabel(t).toLowerCase()} trigger ${t.pattern}`"
|
||||||
|
@click="removeTrigger(i)"
|
||||||
|
>×</button>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
<p v-else class="field-note">No triggers: this rule arrives by its moments and by resemblance.</p>
|
||||||
|
<div class="trigger-add">
|
||||||
|
<select v-model="triggerKind" class="fs-input" aria-label="What the trigger matches">
|
||||||
|
<option v-for="k in TRIGGER_KINDS" :key="k.value" :value="k.value">{{ k.label }}</option>
|
||||||
|
</select>
|
||||||
|
<input
|
||||||
|
v-model="triggerPattern"
|
||||||
|
class="fs-input"
|
||||||
|
aria-label="The pattern the act must match"
|
||||||
|
:placeholder="triggerPlaceholder"
|
||||||
|
@keydown.enter.prevent="addTrigger"
|
||||||
|
/>
|
||||||
|
<select v-model="triggerMoment" class="fs-input" aria-label="Only at this moment">
|
||||||
|
<option value="">Any act</option>
|
||||||
|
<option v-for="m in momentCatalog" :key="m.name" :value="m.name">Only at {{ m.name }}</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
class="btn-secondary btn-sm"
|
||||||
|
:disabled="!triggerPattern.trim()"
|
||||||
|
@click="addTrigger"
|
||||||
|
>Add</button>
|
||||||
|
</div>
|
||||||
|
<p v-if="triggerError" class="trigger-warning">{{ triggerError }}</p>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
<fieldset v-if="canon.catalog.length" class="areas">
|
<fieldset v-if="canon.catalog.length" class="areas">
|
||||||
<legend>Areas this rule is about</legend>
|
<legend>Areas this rule is about</legend>
|
||||||
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
|
<label v-for="entry in canon.catalog" :key="entry.id" class="area-opt">
|
||||||
@@ -569,6 +664,13 @@ legend { padding: 0 0.35rem; font-size: 0.8rem; color: var(--fs-text-tertiary);
|
|||||||
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
|
.procedure-add { display: flex; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
|
||||||
.procedure-add input { margin-top: 0; }
|
.procedure-add input { margin-top: 0; }
|
||||||
.procedure-add .btn-sm { flex: none; }
|
.procedure-add .btn-sm { flex: none; }
|
||||||
|
.trigger-list { list-style: none; padding: 0; margin: 0 0 var(--fs-space-2); display: flex; flex-wrap: wrap; gap: var(--fs-space-2); }
|
||||||
|
.trigger-list .rule-chip { display: inline-flex; align-items: center; gap: var(--fs-space-1); }
|
||||||
|
.trigger-kind, .trigger-at { color: var(--fs-text-secondary); font-size: var(--fs-size-tiny); }
|
||||||
|
.trigger-add { display: flex; flex-wrap: wrap; gap: var(--fs-space-2); align-items: center; margin-top: var(--fs-space-2); }
|
||||||
|
.trigger-add input { flex: 1 1 14rem; margin-top: 0; }
|
||||||
|
.trigger-add select { flex: none; width: auto; margin-top: 0; }
|
||||||
|
.trigger-add .btn-sm { flex: none; }
|
||||||
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction
|
/* --fs-warning-fg, not --fs-warning: the token set draws the distinction
|
||||||
between the warning HUE and warning text, and this is text. */
|
between the warning HUE and warning text, and this is text. */
|
||||||
.trigger-warning {
|
.trigger-warning {
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ from datetime import datetime, timedelta, timezone
|
|||||||
from grimoire.mcp._context import current_user_id
|
from grimoire.mcp._context import current_user_id
|
||||||
from grimoire.services import dedup as dedup_svc
|
from grimoire.services import dedup as dedup_svc
|
||||||
from grimoire.services import moments as moments_svc
|
from grimoire.services import moments as moments_svc
|
||||||
|
from grimoire.services import rule_triggers as rule_triggers_svc
|
||||||
from grimoire.services import rulebooks as rulebooks_svc
|
from grimoire.services import rulebooks as rulebooks_svc
|
||||||
from grimoire.services import trash as trash_svc
|
from grimoire.services import trash as trash_svc
|
||||||
from grimoire.services.lesson_rules import confirmed_lesson_counts
|
from grimoire.services.lesson_rules import confirmed_lesson_counts
|
||||||
@@ -343,6 +344,7 @@ async def create_rule(
|
|||||||
system_ids: list[int] | None = None,
|
system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None, force: bool = False,
|
moments: list[str] | None = None, force: bool = False,
|
||||||
enforcement: str = "inform", salience: str = "normal",
|
enforcement: str = "inform", salience: str = "normal",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Create a new rule in a rulebook (a SHARED rule — keep it general).
|
"""Create a new rule in a rulebook (a SHARED rule — keep it general).
|
||||||
|
|
||||||
@@ -536,6 +538,17 @@ async def create_rule(
|
|||||||
act it governs wait for one read of it — for a rule whose miss
|
act it governs wait for one read of it — for a rule whose miss
|
||||||
costs a rewrite. `enforce` checks the act itself — for a hard
|
costs a rewrite. `enforce` checks the act itself — for a hard
|
||||||
boundary. Declare hold or enforce on purpose; most rules inform.
|
boundary. Declare hold or enforce on purpose; most rules inform.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
salience: `high`, `normal` (the default) or `low` — how this record
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
ranks against others of the same enforcement when a moment has
|
ranks against others of the same enforcement when a moment has
|
||||||
more to say than fits.
|
more to say than fits.
|
||||||
@@ -548,6 +561,7 @@ async def create_rule(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
if not force:
|
if not force:
|
||||||
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
|
dup = await dedup_svc.find_duplicate_rule(title, topic_id=topic_id)
|
||||||
if dup is not None:
|
if dup is not None:
|
||||||
@@ -564,7 +578,7 @@ async def create_rule(
|
|||||||
verify_with=verify_with, expires_when=expires_when,
|
verify_with=verify_with, expires_when=expires_when,
|
||||||
enforcement=enforcement, salience=salience,
|
enforcement=enforcement, salience=salience,
|
||||||
)
|
)
|
||||||
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
||||||
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
|
return await moment_delivery.attach_moment_rules(uid, "create_rule", {}, data)
|
||||||
|
|
||||||
@@ -576,6 +590,7 @@ async def create_project_rule(
|
|||||||
system_ids: list[int] | None = None,
|
system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None, force: bool = False,
|
moments: list[str] | None = None, force: bool = False,
|
||||||
enforcement: str = "inform", salience: str = "normal",
|
enforcement: str = "inform", salience: str = "normal",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Create a rule scoped to a single project (no rulebook needed).
|
"""Create a rule scoped to a single project (no rulebook needed).
|
||||||
|
|
||||||
@@ -656,6 +671,17 @@ async def create_project_rule(
|
|||||||
act it governs wait for one read of it — for a rule whose miss
|
act it governs wait for one read of it — for a rule whose miss
|
||||||
costs a rewrite. `enforce` checks the act itself — for a hard
|
costs a rewrite. `enforce` checks the act itself — for a hard
|
||||||
boundary. Declare hold or enforce on purpose; most rules inform.
|
boundary. Declare hold or enforce on purpose; most rules inform.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
salience: `high`, `normal` (the default) or `low` — how this record
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
ranks against others of the same enforcement when a moment has
|
ranks against others of the same enforcement when a moment has
|
||||||
more to say than fits.
|
more to say than fits.
|
||||||
@@ -667,6 +693,7 @@ async def create_project_rule(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
derived_title = title.strip() or statement.strip().split(".")[0][:50]
|
derived_title = title.strip() or statement.strip().split(".")[0][:50]
|
||||||
if not force:
|
if not force:
|
||||||
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
|
dup = await dedup_svc.find_duplicate_rule(derived_title, project_id=project_id)
|
||||||
@@ -683,7 +710,7 @@ async def create_project_rule(
|
|||||||
verify_with=verify_with, expires_when=expires_when,
|
verify_with=verify_with, expires_when=expires_when,
|
||||||
enforcement=enforcement, salience=salience,
|
enforcement=enforcement, salience=salience,
|
||||||
)
|
)
|
||||||
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
data.update(dedup_svc.overlap_response(overlaps, "rule"))
|
||||||
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
|
return await moment_delivery.attach_moment_rules(uid, "create_project_rule", {"project_id": project_id}, data)
|
||||||
|
|
||||||
@@ -696,6 +723,7 @@ async def update_rule(
|
|||||||
verify_with: str = "", expires_when: str = "", kind: str = "",
|
verify_with: str = "", expires_when: str = "", kind: str = "",
|
||||||
clear_fields: list[str] | None = None,
|
clear_fields: list[str] | None = None,
|
||||||
enforcement: str = "", salience: str = "",
|
enforcement: str = "", salience: str = "",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged.
|
"""Update a rule. Empty strings / order_index=-1 leave fields unchanged.
|
||||||
|
|
||||||
@@ -761,6 +789,17 @@ async def update_rule(
|
|||||||
act it governs wait for one read of it — for a rule whose miss
|
act it governs wait for one read of it — for a rule whose miss
|
||||||
costs a rewrite. `enforce` checks the act itself — for a hard
|
costs a rewrite. `enforce` checks the act itself — for a hard
|
||||||
boundary. Declare hold or enforce on purpose; most rules inform.
|
boundary. Declare hold or enforce on purpose; most rules inform.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
salience: `high`, `normal` (the default) or `low` — how this record
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
ranks against others of the same enforcement when a moment has
|
ranks against others of the same enforcement when a moment has
|
||||||
more to say than fits.
|
more to say than fits.
|
||||||
@@ -768,6 +807,7 @@ async def update_rule(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
fields: dict = {}
|
fields: dict = {}
|
||||||
if title:
|
if title:
|
||||||
fields["title"] = title
|
fields["title"] = title
|
||||||
@@ -798,7 +838,7 @@ async def update_rule(
|
|||||||
)
|
)
|
||||||
if rule is None:
|
if rule is None:
|
||||||
raise ValueError(f"rule {rule_id} not found")
|
raise ValueError(f"rule {rule_id} not found")
|
||||||
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
|
|
||||||
|
|
||||||
# ── Preferences ─────────────────────────────────────────────────────────
|
# ── Preferences ─────────────────────────────────────────────────────────
|
||||||
@@ -821,6 +861,7 @@ async def create_preference(
|
|||||||
order_index: int = 0, system_ids: list[int] | None = None,
|
order_index: int = 0, system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None,
|
moments: list[str] | None = None,
|
||||||
force: bool = False, salience: str = "normal",
|
force: bool = False, salience: str = "normal",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Record how the operator wants work done. No approval loop — write it.
|
"""Record how the operator wants work done. No approval loop — write it.
|
||||||
|
|
||||||
@@ -894,6 +935,17 @@ async def create_preference(
|
|||||||
done rather than what it is about: a rule on when work counts as
|
done rather than what it is about: a rule on when work counts as
|
||||||
finished belongs at work.finish and reply.report, where nothing
|
finished belongs at work.finish and reply.report, where nothing
|
||||||
said resembles it. Replaces the set; [] clears it.
|
said resembles it. Replaces the set; [] clears it.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
salience: `high`, `normal` (the default) or `low` — how this record
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
ranks against others of the same enforcement when a moment has
|
ranks against others of the same enforcement when a moment has
|
||||||
more to say than fits.
|
more to say than fits.
|
||||||
@@ -906,6 +958,7 @@ async def create_preference(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
if not when_to_apply.strip():
|
if not when_to_apply.strip():
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"when_to_apply is required: a preference with no trigger never "
|
"when_to_apply is required: a preference with no trigger never "
|
||||||
@@ -932,7 +985,7 @@ async def create_preference(
|
|||||||
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
why=why, how_to_apply=how_to_apply, order_index=order_index,
|
||||||
salience=salience,
|
salience=salience,
|
||||||
)
|
)
|
||||||
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
data = await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
data.update(dedup_svc.overlap_response(overlaps, "preference"))
|
data.update(dedup_svc.overlap_response(overlaps, "preference"))
|
||||||
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
|
return await moment_delivery.attach_moment_rules(uid, "create_preference", {}, data)
|
||||||
|
|
||||||
@@ -944,6 +997,7 @@ async def update_preference(
|
|||||||
system_ids: list[int] | None = None,
|
system_ids: list[int] | None = None,
|
||||||
moments: list[str] | None = None, clear_fields: list[str] | None = None,
|
moments: list[str] | None = None, clear_fields: list[str] | None = None,
|
||||||
salience: str = "",
|
salience: str = "",
|
||||||
|
triggers: list[dict] | None = None,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Bring a preference up to date. Doing this mid-work is expected.
|
"""Bring a preference up to date. Doing this mid-work is expected.
|
||||||
|
|
||||||
@@ -998,6 +1052,17 @@ async def update_preference(
|
|||||||
moments: Replaces the moments this preference arrives at (see
|
moments: Replaces the moments this preference arrives at (see
|
||||||
create_preference); omit to leave them alone.
|
create_preference); omit to leave them alone.
|
||||||
when_to_apply: The moment it applies, in session vocabulary. See above.
|
when_to_apply: The moment it applies, in session vocabulary. See above.
|
||||||
|
triggers: What ACT this record applies to, checked exactly rather
|
||||||
|
than by resemblance — a list of {kind, pattern, moment?}. Kinds:
|
||||||
|
`tool` (a tool key, `*` allowed: "update_task"), `path` (a glob
|
||||||
|
over the file an act touches: "alembic/versions/*.py",
|
||||||
|
"frontend/**/*.vue"), `command` (a command head: "git push",
|
||||||
|
"docker compose"), `keyword` (a word or phrase in the command, the
|
||||||
|
content written or the reply). With no moment, the record arrives
|
||||||
|
on any act that matches. With a moment, its mount there becomes
|
||||||
|
conditional: it arrives at that moment only when the act matches,
|
||||||
|
so a rule about migrations can sit on work.change without arriving
|
||||||
|
at every edit. Replaces the set; [] clears it.
|
||||||
salience: `high`, `normal` (the default) or `low` — how this record
|
salience: `high`, `normal` (the default) or `low` — how this record
|
||||||
ranks against others of the same enforcement when a moment has
|
ranks against others of the same enforcement when a moment has
|
||||||
more to say than fits.
|
more to say than fits.
|
||||||
@@ -1005,6 +1070,7 @@ async def update_preference(
|
|||||||
"""
|
"""
|
||||||
uid = current_user_id()
|
uid = current_user_id()
|
||||||
moments = moments_svc.require_moments(moments)
|
moments = moments_svc.require_moments(moments)
|
||||||
|
triggers = rule_triggers_svc.require_triggers(triggers)
|
||||||
if not arose_from_id:
|
if not arose_from_id:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"arose_from_id is required: this edit is the record of how the "
|
"arose_from_id is required: this edit is the record of how the "
|
||||||
@@ -1031,7 +1097,7 @@ async def update_preference(
|
|||||||
)
|
)
|
||||||
if rule is None:
|
if rule is None:
|
||||||
raise ValueError(f"rule {rule_id} not found")
|
raise ValueError(f"rule {rule_id} not found")
|
||||||
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments)
|
return await rulebooks_svc.rule_detail(uid, rule, system_ids, moments, triggers=triggers)
|
||||||
|
|
||||||
|
|
||||||
async def rule_history(rule_id: int, version_id: int = 0) -> dict:
|
async def rule_history(rule_id: int, version_id: int = 0) -> dict:
|
||||||
|
|||||||
@@ -211,6 +211,22 @@ rule_moments = Table(
|
|||||||
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
|
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# What a rule is TRIGGERED by: a typed predicate on the act itself — the tool
|
||||||
|
# called, a path it touches, the head of a command it runs, or a word in what
|
||||||
|
# it writes — checked in code with no embedding (`services/rule_triggers.py`).
|
||||||
|
# `moment` empty means the trigger fires on any act that matches it; a moment
|
||||||
|
# name makes the rule's mount on that moment conditional on the act matching.
|
||||||
|
rule_triggers = Table(
|
||||||
|
"rule_triggers",
|
||||||
|
Base.metadata,
|
||||||
|
Column("rule_id", BigInteger, ForeignKey("rules.id", ondelete="CASCADE"), primary_key=True),
|
||||||
|
Column("kind", Text, primary_key=True),
|
||||||
|
Column("pattern", Text, primary_key=True),
|
||||||
|
Column("moment", Text, primary_key=True, default="", server_default=""),
|
||||||
|
Column("created_at", DateTime(timezone=True), default=lambda: datetime.now(timezone.utc)),
|
||||||
|
)
|
||||||
|
|
||||||
class RuleRelation(Base, CreatedAtMixin):
|
class RuleRelation(Base, CreatedAtMixin):
|
||||||
"""A typed edge between two rules. Each kind exists because without it a
|
"""A typed edge between two rules. Each kind exists because without it a
|
||||||
rulebook needs a workaround.
|
rulebook needs a workaround.
|
||||||
|
|||||||
@@ -40,6 +40,17 @@ def _moments_or_refusal(data: dict):
|
|||||||
return None, (jsonify({"error": str(exc)}), 400)
|
return None, (jsonify({"error": str(exc)}), 400)
|
||||||
|
|
||||||
|
|
||||||
|
def _triggers_or_refusal(data: dict):
|
||||||
|
"""The request's `triggers`, validated before any write, as `moments` is.
|
||||||
|
Absent means "leave them alone" (None)."""
|
||||||
|
from grimoire.services.rule_triggers import require_triggers
|
||||||
|
|
||||||
|
try:
|
||||||
|
return require_triggers(data.get("triggers")), None
|
||||||
|
except ValueError as exc:
|
||||||
|
return None, (jsonify({"error": str(exc)}), 400)
|
||||||
|
|
||||||
|
|
||||||
# ── Rulebooks ───────────────────────────────────────────────────────────
|
# ── Rulebooks ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@rulebooks_bp.get("/rulebooks")
|
@rulebooks_bp.get("/rulebooks")
|
||||||
@@ -194,6 +205,9 @@ async def create_rule(topic_id: int):
|
|||||||
if not title or not statement:
|
if not title or not statement:
|
||||||
return jsonify({"error": "title and statement are required"}), 400
|
return jsonify({"error": "title and statement are required"}), 400
|
||||||
moments, refused = _moments_or_refusal(data)
|
moments, refused = _moments_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
triggers, refused = _triggers_or_refusal(data)
|
||||||
if refused:
|
if refused:
|
||||||
return refused
|
return refused
|
||||||
declared, refused = _declared_or_refusal(data)
|
declared, refused = _declared_or_refusal(data)
|
||||||
@@ -223,7 +237,7 @@ async def create_rule(topic_id: int):
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return jsonify({"error": str(exc)}), 404
|
return jsonify({"error": str(exc)}), 404
|
||||||
return jsonify(await rulebooks_svc.rule_detail(
|
return jsonify(await rulebooks_svc.rule_detail(
|
||||||
get_current_user_id(), rule, data.get("system_ids"), moments,
|
get_current_user_id(), rule, data.get("system_ids"), moments, triggers=triggers,
|
||||||
)), 201
|
)), 201
|
||||||
|
|
||||||
|
|
||||||
@@ -258,6 +272,9 @@ async def update_rule(rule_id: int):
|
|||||||
# door needs the explicit list only because "" already means "unchanged"
|
# door needs the explicit list only because "" already means "unchanged"
|
||||||
# there — two idioms, one outcome.
|
# there — two idioms, one outcome.
|
||||||
moments, refused = _moments_or_refusal(data)
|
moments, refused = _moments_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
triggers, refused = _triggers_or_refusal(data)
|
||||||
if refused:
|
if refused:
|
||||||
return refused
|
return refused
|
||||||
try:
|
try:
|
||||||
@@ -267,7 +284,7 @@ async def update_rule(rule_id: int):
|
|||||||
if rule is None:
|
if rule is None:
|
||||||
return jsonify({"error": "rule not found"}), 404
|
return jsonify({"error": "rule not found"}), 404
|
||||||
return jsonify(await rulebooks_svc.rule_detail(
|
return jsonify(await rulebooks_svc.rule_detail(
|
||||||
uid, rule, data.get("system_ids"), moments,
|
uid, rule, data.get("system_ids"), moments, triggers=triggers,
|
||||||
))
|
))
|
||||||
|
|
||||||
|
|
||||||
@@ -443,6 +460,9 @@ async def create_project_rule(project_id: int):
|
|||||||
}), 400
|
}), 400
|
||||||
title = (data.get("title") or "").strip() or statement.split(".")[0][:50]
|
title = (data.get("title") or "").strip() or statement.split(".")[0][:50]
|
||||||
moments, refused = _moments_or_refusal(data)
|
moments, refused = _moments_or_refusal(data)
|
||||||
|
if refused:
|
||||||
|
return refused
|
||||||
|
triggers, refused = _triggers_or_refusal(data)
|
||||||
if refused:
|
if refused:
|
||||||
return refused
|
return refused
|
||||||
declared, refused = _declared_or_refusal(data)
|
declared, refused = _declared_or_refusal(data)
|
||||||
@@ -472,7 +492,7 @@ async def create_project_rule(project_id: int):
|
|||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
return jsonify({"error": str(exc)}), 404
|
return jsonify({"error": str(exc)}), 404
|
||||||
return jsonify(await rulebooks_svc.rule_detail(
|
return jsonify(await rulebooks_svc.rule_detail(
|
||||||
get_current_user_id(), rule, data.get("system_ids"), moments,
|
get_current_user_id(), rule, data.get("system_ids"), moments, triggers=triggers,
|
||||||
)), 201
|
)), 201
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -23,6 +23,7 @@ from grimoire.models.family import (
|
|||||||
)
|
)
|
||||||
from grimoire.models.rulebook import (
|
from grimoire.models.rulebook import (
|
||||||
RuleRelation, rule_moments as rule_moments_t, rule_systems as rule_systems_t,
|
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.lesson_rule_link import LessonNoRule, LessonRuleLink
|
||||||
from grimoire.models.rule_moment_judgment import RuleMomentJudgment
|
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.
|
# section still restore — the key is simply not read.
|
||||||
# v28 instance_id in the header: the id lineage of the store the backup came
|
# 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.
|
# 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
|
# 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
|
# below, these two lists must together account for the entire schema — which is
|
||||||
@@ -158,6 +161,7 @@ _BACKED_UP = [
|
|||||||
"moment_mappings",
|
"moment_mappings",
|
||||||
"rule_moments",
|
"rule_moments",
|
||||||
"rule_moment_judgments",
|
"rule_moment_judgments",
|
||||||
|
"rule_triggers",
|
||||||
# Family canon. `platforms` is global like
|
# Family canon. `platforms` is global like
|
||||||
# canonical_systems and rides every export for the same reason: the rows
|
# canonical_systems and rides every export for the same reason: the rows
|
||||||
# below name platforms by slug, and a partial catalog restores partial
|
# 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]
|
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]:
|
def _rule_moment_judgment_rows(rows) -> list[dict]:
|
||||||
"""Proposals and judgments about a rule's moments (v23). The rule id is a
|
"""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."""
|
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)
|
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)
|
.order_by(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||||
)).all()
|
)).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(
|
rule_moment_judgments = (await session.execute(
|
||||||
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
|
select(RuleMomentJudgment).order_by(RuleMomentJudgment.id)
|
||||||
)).scalars().all()
|
)).scalars().all()
|
||||||
@@ -1112,6 +1131,7 @@ async def export_full_backup() -> dict:
|
|||||||
"canonical_systems": _canonical_system_rows(canonical_systems),
|
"canonical_systems": _canonical_system_rows(canonical_systems),
|
||||||
"rule_systems": _rule_system_rows(rule_system_rows),
|
"rule_systems": _rule_system_rows(rule_system_rows),
|
||||||
"rule_moments": _rule_moment_rows(rule_moment_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_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
|
||||||
"rule_relations": _rule_relation_rows(rule_relations),
|
"rule_relations": _rule_relation_rows(rule_relations),
|
||||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
"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)
|
select(rule_moments_t.c.rule_id, rule_moments_t.c.moment)
|
||||||
.where(rule_moments_t.c.rule_id.in_(_rule_ids))
|
.where(rule_moments_t.c.rule_id.in_(_rule_ids))
|
||||||
)).all() if _rule_ids else []
|
)).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(
|
rule_moment_judgments = (await session.execute(
|
||||||
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
|
select(RuleMomentJudgment).where(RuleMomentJudgment.rule_id.in_(_rule_ids))
|
||||||
)).scalars().all() if _rule_ids else []
|
)).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),
|
"canonical_systems": _canonical_system_rows(canonical_systems),
|
||||||
"rule_systems": _rule_system_rows(rule_system_rows),
|
"rule_systems": _rule_system_rows(rule_system_rows),
|
||||||
"rule_moments": _rule_moment_rows(rule_moment_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_moment_judgments": _rule_moment_judgment_rows(rule_moment_judgments),
|
||||||
"rule_relations": _rule_relation_rows(rule_relations),
|
"rule_relations": _rule_relation_rows(rule_relations),
|
||||||
"lesson_rule_links": _lesson_rule_link_rows(lesson_rule_links),
|
"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,
|
"note_supersessions": 0, "code_shapes": 0, "code_shape_events": 0,
|
||||||
"code_shape_uses": 0, "canonical_systems": 0,
|
"code_shape_uses": 0, "canonical_systems": 0,
|
||||||
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
|
"rule_systems": 0, "rule_moments": 0, "rule_moment_judgments": 0,
|
||||||
|
"rule_triggers": 0,
|
||||||
"rule_relations": 0, "rule_versions": 0,
|
"rule_relations": 0, "rule_versions": 0,
|
||||||
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
|
"retrieval_tuning_events": 0, "lesson_rule_links": 0,
|
||||||
"lesson_no_rule": 0, "moment_mappings": 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
|
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
|
# Proposals and judgments about those mounts (v23); archives before
|
||||||
# v23 carry none, and every rule restores unjudged.
|
# v23 carry none, and every rule restores unjudged.
|
||||||
for rj in data.get("rule_moment_judgments", []):
|
for rj in data.get("rule_moment_judgments", []):
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ def _io() -> rp.MomentIO:
|
|||||||
record_rule_surfaced=rule_usage.record_rule_surfaced,
|
record_rule_surfaced=rule_usage.record_rule_surfaced,
|
||||||
history=rule_deliveries.history if bound else None,
|
history=rule_deliveries.history if bound else None,
|
||||||
record_delivery=rule_deliveries.record 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,
|
# request whether or not anything is mounted on it: the shape is product,
|
||||||
# so every install has it.
|
# so every install has it.
|
||||||
shaped = {s.moment for s in reply_shapes.SHAPES.values() if s.key != reply_shapes.CORE_KEY}
|
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))
|
mounted = set(await rulebooks.mounted_moments(user_id))
|
||||||
wanted = mounted | shaped
|
wanted = mounted | shaped
|
||||||
mappings = await moment_actions.list_mappings(user_id)
|
mappings = await moment_actions.list_mappings(user_id)
|
||||||
@@ -62,19 +65,45 @@ async def reachable_tools(user_id: int) -> list[str]:
|
|||||||
}
|
}
|
||||||
if mounted:
|
if mounted:
|
||||||
keys.add(moment_actions.SKILL_TOOL)
|
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)
|
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(
|
async def deliver_moments(
|
||||||
user_id: int, reached: list[dict], *, project_id: int | None = None,
|
user_id: int, reached: list[dict], *, project_id: int | None = None,
|
||||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||||
|
board=None, text: str = "",
|
||||||
) -> rp.RuleResult:
|
) -> 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(
|
return await rp.run_moment_arm(
|
||||||
reached,
|
reached,
|
||||||
rp.RuleMoment(user_id=user_id, query="", project_id=project_id,
|
rp.RuleMoment(user_id=user_id, query="", project_id=project_id,
|
||||||
exclude=exclude, held=held),
|
exclude=exclude, held=held),
|
||||||
io=_io(),
|
io=_io(), board=board,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -83,12 +112,14 @@ async def deliver_for_act(
|
|||||||
project_id: int | None = None,
|
project_id: int | None = None,
|
||||||
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
exclude: frozenset[int] = frozenset(), held: frozenset[int] = frozenset(),
|
||||||
) -> tuple[list[dict], rp.RuleResult]:
|
) -> 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 {})
|
reached = await moment_actions.moments_for(user_id, tool, tool_input or {})
|
||||||
if not reached:
|
board = await _board(user_id, project_id, tool=tool, tool_input=tool_input or {})
|
||||||
return [], rp.RuleResult()
|
if not reached and not (board and board.fired):
|
||||||
|
return reached, rp.RuleResult()
|
||||||
result = await deliver_moments(
|
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
|
return reached, result
|
||||||
|
|
||||||
@@ -294,9 +325,12 @@ async def reply_hold(
|
|||||||
out: list[dict] = []
|
out: list[dict] = []
|
||||||
|
|
||||||
# The mounted half: deterministic, so every unopened RULE on these
|
# 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):
|
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
|
continue
|
||||||
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
|
out.append({"rule_id": rule.id, "title": rule.title, "moment": at,
|
||||||
"trigger": (rule.when_to_apply or "").strip()})
|
"trigger": (rule.when_to_apply or "").strip()})
|
||||||
|
|||||||
@@ -983,6 +983,7 @@ def _rule_io() -> rp.RuleIO:
|
|||||||
record_rule_surfaced=record_rule_surfaced,
|
record_rule_surfaced=record_rule_surfaced,
|
||||||
history=rule_deliveries.history if bound else None,
|
history=rule_deliveries.history if bound else None,
|
||||||
record_delivery=rule_deliveries.record if bound else None,
|
record_delivery=rule_deliveries.record if bound else None,
|
||||||
|
retired=rule_deliveries.retired if bound else None,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -583,6 +583,9 @@ class RuleIO:
|
|||||||
record_delivery: Callable[..., Any] | None = None
|
record_delivery: Callable[..., Any] | None = None
|
||||||
"""`rule_deliveries.record`: each line shown, against the session the
|
"""`rule_deliveries.record`: each line shown, against the session the
|
||||||
door bound. None records nothing."""
|
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)
|
@dataclass(frozen=True)
|
||||||
@@ -792,6 +795,31 @@ def _record_delivery(io, moment: RuleMoment, source: str, shown: list[tuple[int,
|
|||||||
_telemetry_failed(source)
|
_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]:
|
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
|
"""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."""
|
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(
|
shown, _slot_id = await _reserve_slot_for_preference(
|
||||||
io, moment, shown, floor=floor,
|
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
|
# `shown`, not `fresh`: a call whose only hit is a repeat
|
||||||
# still has something to say, it just says it differently.
|
# still has something to say, it just says it differently.
|
||||||
if not shown:
|
if not shown:
|
||||||
@@ -1650,6 +1682,8 @@ class MomentIO:
|
|||||||
"""As on `RuleIO`."""
|
"""As on `RuleIO`."""
|
||||||
record_delivery: Callable[..., Any] | None = None
|
record_delivery: Callable[..., Any] | None = None
|
||||||
"""As on `RuleIO`."""
|
"""As on `RuleIO`."""
|
||||||
|
retired: Callable[..., Any] | None = None
|
||||||
|
"""As on `RuleIO`."""
|
||||||
|
|
||||||
|
|
||||||
def _reached_by(hit: dict) -> str:
|
def _reached_by(hit: dict) -> str:
|
||||||
@@ -1659,7 +1693,7 @@ def _reached_by(hit: dict) -> str:
|
|||||||
|
|
||||||
async def run_moment_arm(
|
async def run_moment_arm(
|
||||||
reached: list[dict], moment: RuleMoment, *, io: MomentIO,
|
reached: list[dict], moment: RuleMoment, *, io: MomentIO,
|
||||||
limit: int = MOMENT_RULE_LIMIT,
|
limit: int = MOMENT_RULE_LIMIT, board: Any = None,
|
||||||
) -> RuleResult:
|
) -> RuleResult:
|
||||||
"""Deliver the rules mounted on the moments this act reached.
|
"""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
|
`unmap_action`. Fresh rules come first and carry their
|
||||||
trigger; a rule the session was already shown is cited, not repeated in
|
trigger; a rule the session was already shown is cited, not repeated in
|
||||||
full. Fails open to an empty result.
|
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:
|
try:
|
||||||
names = [hit["moment"] for hit in reached]
|
names = [hit["moment"] for hit in reached]
|
||||||
if not names:
|
fired = list(board.fired) if board is not None else []
|
||||||
return RuleResult()
|
if not names and not fired:
|
||||||
pairs = await io.lookup(moment.user_id, names, moment.project_id or None)
|
|
||||||
if not pairs:
|
|
||||||
return RuleResult()
|
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}
|
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
|
# The one delivery order (services/rule_order.py), then the cap — so
|
||||||
# what a crowded moment drops is the lowest-ranked, not the last
|
# what a crowded moment drops is the lowest-ranked, not the last
|
||||||
# mounted. Ties keep catalog order.
|
# 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 = [
|
shown = [
|
||||||
c.extra for c in rule_order.ordered(
|
c.extra for c in rule_order.ordered(
|
||||||
rule_order.Candidate(
|
rule_order.Candidate(
|
||||||
rule=rule, specificity=rule_order.BY_MOUNT,
|
rule=rule, specificity=spec,
|
||||||
opened_rate=history.get(rule.id),
|
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]
|
][:limit]
|
||||||
|
|
||||||
lines = []
|
lines = []
|
||||||
for rule, at in shown:
|
for rule, at, where in shown:
|
||||||
seen = rule.id in moment.exclude
|
seen = rule.id in moment.exclude
|
||||||
lines.append(_rule_hint_line(
|
lines.append(_rule_hint_line(
|
||||||
rule,
|
rule,
|
||||||
where=f"at {at}, reached by {_reached_by(by_moment.get(at, {}))}",
|
where=where,
|
||||||
seen=seen, held=rule.id in moment.held,
|
seen=seen, held=rule.id in moment.held,
|
||||||
# A repeat is cited rather than quoted: the session was told
|
# A repeat is cited rather than quoted: the session was told
|
||||||
# which moment brought it the first time.
|
# which moment brought it the first time.
|
||||||
compact=seen,
|
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]
|
rule_ids = [rule.id for rule, _at in fresh]
|
||||||
if rule_ids:
|
if rule_ids:
|
||||||
try:
|
try:
|
||||||
@@ -1717,12 +1775,12 @@ async def run_moment_arm(
|
|||||||
except Exception: # noqa: BLE001 - observation never breaks the observed
|
except Exception: # noqa: BLE001 - observation never breaks the observed
|
||||||
_telemetry_failed(MOMENT_RULE_SOURCE)
|
_telemetry_failed(MOMENT_RULE_SOURCE)
|
||||||
_record_delivery(io, moment, 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(
|
return RuleResult(
|
||||||
lines=lines, rule_ids=rule_ids,
|
lines=lines, rule_ids=rule_ids,
|
||||||
shown_rule_ids=[rule.id for rule, _at in shown],
|
shown_rule_ids=[rule.id for rule, _at, _where in shown],
|
||||||
shown=[(None, rule) for rule, _at in shown],
|
shown=[(None, rule) for rule, _at, _where in shown],
|
||||||
)
|
)
|
||||||
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
except Exception: # noqa: BLE001 - a recall aid never breaks its act
|
||||||
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
|
logger.debug("%s arm failed", MOMENT_RULE_SOURCE, exc_info=True)
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ from datetime import datetime, timedelta, timezone
|
|||||||
from sqlalchemy import and_, case, delete, func, select, tuple_, update
|
from sqlalchemy import and_, case, delete, func, select, tuple_, update
|
||||||
|
|
||||||
from grimoire.models import async_session
|
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 import rule_order
|
||||||
from grimoire.services.background import spawn
|
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:
|
async def prune(retain_days: int = RETAIN_DAYS) -> int:
|
||||||
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
|
cutoff = datetime.now(timezone.utc) - timedelta(days=retain_days)
|
||||||
async with async_session() as session:
|
async with async_session() as session:
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -470,9 +470,9 @@ async def co_surfaced_partners(user_id: int, rule_ids: list[int]) -> list[Rule]:
|
|||||||
|
|
||||||
async def rule_detail(
|
async def rule_detail(
|
||||||
user_id: int, rule: Rule, system_ids: list[int] | None = None,
|
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:
|
) -> 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
|
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
|
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
|
`system_ids=None` / `moments=None` mean "leave them alone"; a list
|
||||||
(including []) REPLACES them. Doors validate `moments` with
|
(including []) REPLACES them. Doors validate `moments` with
|
||||||
`moments.require_moments` BEFORE their create, so an unknown name is
|
`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:
|
if system_ids is not None:
|
||||||
await set_rule_systems(rule.id, user_id, system_ids)
|
await set_rule_systems(rule.id, user_id, system_ids)
|
||||||
if moments is not None:
|
if moments is not None:
|
||||||
await set_rule_moments(rule.id, user_id, moments)
|
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()
|
data = rule.to_dict()
|
||||||
systems = (await list_rule_systems([rule.id])).get(rule.id, [])
|
systems = (await list_rule_systems([rule.id])).get(rule.id, [])
|
||||||
mounted = (await list_rule_moments([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, [])
|
relations = (await list_rule_relations([rule.id])).get(rule.id, [])
|
||||||
# Attached only when present: an empty key reads as a capability
|
# Attached only when present: an empty key reads as a capability
|
||||||
# the record has and isn't using, which is a different claim.
|
# the record has and isn't using, which is a different claim.
|
||||||
@@ -498,6 +504,8 @@ async def rule_detail(
|
|||||||
data["systems"] = systems
|
data["systems"] = systems
|
||||||
if mounted:
|
if mounted:
|
||||||
data["moments"] = mounted
|
data["moments"] = mounted
|
||||||
|
if triggered:
|
||||||
|
data["triggers"] = triggered
|
||||||
if relations:
|
if relations:
|
||||||
data["relations"] = relations
|
data["relations"] = relations
|
||||||
# The concrete situations judged (or proposed) to be instances of this
|
# The concrete situations judged (or proposed) to be instances of this
|
||||||
|
|||||||
@@ -273,6 +273,23 @@ def _no_moment_delivery(request):
|
|||||||
yield
|
yield
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(autouse=True)
|
||||||
|
def _no_rule_triggers(request):
|
||||||
|
"""Stub the database read behind a rule's triggers.
|
||||||
|
|
||||||
|
Every act the moment door sees checks the in-scope triggers, which is a
|
||||||
|
read; stubbed to "no rule carries a trigger" so a unit test of mounts sees
|
||||||
|
mounts only. The matching itself is pure and tested unstubbed in
|
||||||
|
tests/test_rule_triggers.py; the read against Postgres in
|
||||||
|
tests/test_integration_rule_triggers.py, which this skips.
|
||||||
|
"""
|
||||||
|
if request.node.get_closest_marker("integration"):
|
||||||
|
yield
|
||||||
|
return
|
||||||
|
with patch("grimoire.services.rule_triggers._in_scope", AsyncMock(return_value=[])):
|
||||||
|
yield
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _no_rule_arm():
|
def _no_rule_arm():
|
||||||
"""Stub the write-path hint's standing-RULES arm.
|
"""Stub the write-path hint's standing-RULES arm.
|
||||||
|
|||||||
+1
-1
@@ -310,7 +310,7 @@ def plain_rule_detail():
|
|||||||
stubbing the seam slightly differently is a test asserting something
|
stubbing the seam slightly differently is a test asserting something
|
||||||
slightly different than it appears to.
|
slightly different than it appears to.
|
||||||
"""
|
"""
|
||||||
async def _detail(_uid, rule, _system_ids=None, _moments=None):
|
async def _detail(_uid, rule, _system_ids=None, _moments=None, **_kw):
|
||||||
return rule.to_dict()
|
return rule.to_dict()
|
||||||
return patch("grimoire.mcp.tools.rulebooks.rulebooks_svc.rule_detail", _detail)
|
return patch("grimoire.mcp.tools.rulebooks.rulebooks_svc.rule_detail", _detail)
|
||||||
|
|
||||||
|
|||||||
@@ -105,3 +105,23 @@ async def test_old_deliveries_are_pruned():
|
|||||||
await s.commit()
|
await s.commit()
|
||||||
assert await rule_deliveries.prune() >= 1
|
assert await rule_deliveries.prune() >= 1
|
||||||
assert [r.rule_id for r in await _rows(uid)] == [OTHER]
|
assert [r.rule_id for r in await _rows(uid)] == [OTHER]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_rule_retires_after_its_reminder_and_a_full_line_re_arms_it():
|
||||||
|
uid = await _user()
|
||||||
|
rule_deliveries.bind_session("s-life")
|
||||||
|
try:
|
||||||
|
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
|
||||||
|
assert await rule_deliveries.retired(uid, [RULE]) == set()
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "repeat")])
|
||||||
|
assert await rule_deliveries.retired(uid, [RULE, OTHER]) == {RULE}
|
||||||
|
await asyncio.sleep(0.01)
|
||||||
|
# The ledger forgot it (a compaction): the next line is full, and re-arms it.
|
||||||
|
await _record(uid, None, "moment_rule", [(RULE, "work.finish", "full")])
|
||||||
|
assert await rule_deliveries.retired(uid, [RULE]) == set()
|
||||||
|
# Another session's reminder retires nothing here.
|
||||||
|
await _record(uid, "s-other", "moment_rule", [(OTHER, "work.finish", "repeat")])
|
||||||
|
assert await rule_deliveries.retired(uid, [OTHER]) == set()
|
||||||
|
finally:
|
||||||
|
rule_deliveries.bind_session("")
|
||||||
|
|||||||
@@ -0,0 +1,107 @@
|
|||||||
|
"""Real-Postgres tests for `rule_triggers` (migration 0130): stored through the
|
||||||
|
rule's own write path, read back on the record, scoped like every rule read,
|
||||||
|
and checked against an act by the moment door."""
|
||||||
|
import pytest
|
||||||
|
import pytest_asyncio
|
||||||
|
from sqlalchemy import select
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
|
||||||
|
from grimoire.models import async_session
|
||||||
|
from grimoire.models.rulebook import Rulebook, rule_triggers
|
||||||
|
from grimoire.services import moment_delivery
|
||||||
|
from grimoire.services import rule_triggers as rt
|
||||||
|
from grimoire.services import rulebooks as rulebooks_svc
|
||||||
|
from tests.helpers import ensure_user
|
||||||
|
|
||||||
|
pytestmark = [pytest.mark.integration, pytest.mark.usefixtures("_dispose_engine")]
|
||||||
|
|
||||||
|
OWNER_USERNAME = "rule_trigger_owner"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest_asyncio.fixture
|
||||||
|
async def topic_id():
|
||||||
|
# Purged at setup, not teardown: the write path's detached embedding task
|
||||||
|
# would deadlock against a teardown deleting the rulebook.
|
||||||
|
async with async_session() as s:
|
||||||
|
owner = await ensure_user(s, OWNER_USERNAME)
|
||||||
|
uid = owner.id
|
||||||
|
await s.commit()
|
||||||
|
for book in (await s.execute(
|
||||||
|
select(Rulebook).where(Rulebook.owner_user_id == uid)
|
||||||
|
)).scalars().all():
|
||||||
|
await s.delete(book)
|
||||||
|
await s.commit()
|
||||||
|
book = await rulebooks_svc.create_rulebook(uid, "Trigger fixtures")
|
||||||
|
topic = await rulebooks_svc.create_topic(book.id, uid, "conventions")
|
||||||
|
return uid, topic.id
|
||||||
|
|
||||||
|
|
||||||
|
async def _rule(uid, topic, title, triggers, moments=None):
|
||||||
|
rule = await rulebooks_svc.create_rule(
|
||||||
|
topic_id=topic, user_id=uid, title=title, statement="s",
|
||||||
|
when_to_apply="when the fixture's act happens",
|
||||||
|
)
|
||||||
|
return await rulebooks_svc.rule_detail(
|
||||||
|
uid, rule, None, moments, triggers=rt.require_triggers(triggers),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_triggers_are_stored_with_the_rule_and_replaced_as_a_set(topic_id):
|
||||||
|
uid, topic = topic_id
|
||||||
|
data = await _rule(uid, topic, "Migrations are reviewed", [
|
||||||
|
{"kind": "path", "pattern": "alembic/versions/*.py"},
|
||||||
|
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
|
||||||
|
])
|
||||||
|
assert data["triggers"] == [
|
||||||
|
{"kind": "path", "pattern": "alembic/versions/*.py"},
|
||||||
|
{"kind": "command", "pattern": "alembic upgrade", "moment": "work.run"},
|
||||||
|
]
|
||||||
|
rule = await rulebooks_svc.get_rule(data["id"], uid)
|
||||||
|
again = await rulebooks_svc.rule_detail(uid, rule, triggers=[])
|
||||||
|
assert "triggers" not in again
|
||||||
|
# None leaves them alone.
|
||||||
|
await rulebooks_svc.rule_detail(uid, rule, triggers=rt.require_triggers([{"kind": "tool", "pattern": "bash"}]))
|
||||||
|
kept = await rulebooks_svc.rule_detail(uid, rule)
|
||||||
|
assert kept["triggers"] == [{"kind": "tool", "pattern": "bash"}]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_an_unknown_kind_is_refused_by_the_database(topic_id):
|
||||||
|
uid, topic = topic_id
|
||||||
|
data = await _rule(uid, topic, "Raw kind", [])
|
||||||
|
async with async_session() as s:
|
||||||
|
with pytest.raises(IntegrityError):
|
||||||
|
await s.execute(rule_triggers.insert().values(
|
||||||
|
rule_id=data["id"], kind="regex", pattern="x", moment="",
|
||||||
|
))
|
||||||
|
await s.commit()
|
||||||
|
|
||||||
|
|
||||||
|
async def test_an_act_fires_an_unscoped_trigger_with_no_moment_reached(topic_id):
|
||||||
|
uid, topic = topic_id
|
||||||
|
data = await _rule(uid, topic, "Notebooks keep outputs cleared",
|
||||||
|
[{"kind": "path", "pattern": "*.ipynb"}])
|
||||||
|
reached, result = await moment_delivery.deliver_for_act(
|
||||||
|
uid, "Read", {"file_path": "/r/analysis/one.ipynb"},
|
||||||
|
)
|
||||||
|
assert data["id"] in result.shown_rule_ids
|
||||||
|
assert any("path `*.ipynb`" in line for line in result.lines)
|
||||||
|
_, quiet = await moment_delivery.deliver_for_act(uid, "Read", {"file_path": "/r/a.py"})
|
||||||
|
assert data["id"] not in quiet.shown_rule_ids
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_conditional_mount_arrives_only_when_the_act_meets_it(topic_id):
|
||||||
|
uid, topic = topic_id
|
||||||
|
data = await _rule(uid, topic, "Schema changes get a migration",
|
||||||
|
[{"kind": "path", "pattern": "models/*.py", "moment": "work.change"}],
|
||||||
|
moments=["work.change"])
|
||||||
|
_, missed = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/views/a.py"})
|
||||||
|
assert data["id"] not in missed.shown_rule_ids
|
||||||
|
_, met = await moment_delivery.deliver_for_act(uid, "Edit", {"file_path": "/r/models/a.py"})
|
||||||
|
assert data["id"] in met.shown_rule_ids
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_reachable_tools_include_what_a_trigger_can_match(topic_id):
|
||||||
|
uid, topic = topic_id
|
||||||
|
await _rule(uid, topic, "Task closes carry a report",
|
||||||
|
[{"kind": "tool", "pattern": "update_task"}])
|
||||||
|
assert "update_task" in await moment_delivery.reachable_tools(uid)
|
||||||
@@ -103,7 +103,7 @@ async def test_an_unknown_moment_is_refused_before_anything_is_written():
|
|||||||
async def test_the_door_hands_rule_detail_the_normalised_moments():
|
async def test_the_door_hands_rule_detail_the_normalised_moments():
|
||||||
seen = {}
|
seen = {}
|
||||||
|
|
||||||
async def detail(_uid, rule, _system_ids=None, moments=None):
|
async def detail(_uid, rule, _system_ids=None, moments=None, **_kw):
|
||||||
seen["moments"] = moments
|
seen["moments"] = moments
|
||||||
return rule.to_dict()
|
return rule.to_dict()
|
||||||
|
|
||||||
@@ -119,7 +119,7 @@ async def test_the_door_hands_rule_detail_the_normalised_moments():
|
|||||||
async def test_omitting_moments_leaves_the_mounts_alone():
|
async def test_omitting_moments_leaves_the_mounts_alone():
|
||||||
seen = {}
|
seen = {}
|
||||||
|
|
||||||
async def detail(_uid, rule, _system_ids=None, moments="unset"):
|
async def detail(_uid, rule, _system_ids=None, moments="unset", **_kw):
|
||||||
seen["moments"] = moments
|
seen["moments"] = moments
|
||||||
return rule.to_dict()
|
return rule.to_dict()
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
"""The one delivery order, key by key, and both rule arms reading it."""
|
"""The one delivery order, key by key, and both rule arms reading it."""
|
||||||
|
import dataclasses
|
||||||
from types import SimpleNamespace
|
from types import SimpleNamespace
|
||||||
from unittest.mock import AsyncMock, MagicMock
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
@@ -129,3 +130,45 @@ async def test_history_reorders_rules_of_equal_rank_and_a_failed_read_is_unknown
|
|||||||
history=broken),
|
history=broken),
|
||||||
)
|
)
|
||||||
assert result.shown_rule_ids == [5, 6]
|
assert result.shown_rule_ids == [5, 6]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_a_repeat_already_reminded_once_is_retired_unless_it_holds_or_was_opened():
|
||||||
|
pairs = [(_r(5), "work.finish"), (_r(6), "work.finish"), (_r(7, "hold"), "work.finish"),
|
||||||
|
(_r(8), "work.finish")]
|
||||||
|
asked = {}
|
||||||
|
|
||||||
|
async def retired(_uid, ids):
|
||||||
|
asked["ids"] = sorted(ids)
|
||||||
|
return set(ids)
|
||||||
|
|
||||||
|
result = await rp.run_moment_arm(
|
||||||
|
PUSH, rp.RuleMoment(user_id=1, query="", project_id=2,
|
||||||
|
exclude=frozenset({6, 7, 8}), held=frozenset({8})),
|
||||||
|
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock(),
|
||||||
|
retired=retired),
|
||||||
|
)
|
||||||
|
# Only the unopened, non-holding repeat is asked about, and only it goes.
|
||||||
|
assert asked["ids"] == [6]
|
||||||
|
assert sorted(result.shown_rule_ids) == [5, 7, 8]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_the_semantic_arm_retires_the_same_way_and_a_failed_read_retires_nothing():
|
||||||
|
hits = [(0.91, _r(1)), (0.80, _r(2))]
|
||||||
|
|
||||||
|
async def retired(_uid, ids):
|
||||||
|
return {2}
|
||||||
|
|
||||||
|
io = rp.RuleIO(search=AsyncMock(return_value=hits), record_retrieval=MagicMock(),
|
||||||
|
record_rule_surfaced=MagicMock(), retired=retired)
|
||||||
|
moment = rp.RuleMoment(user_id=1, query="q", project_id=2, where="here", exclude=frozenset({2}))
|
||||||
|
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
|
||||||
|
assert result.shown_rule_ids == [1]
|
||||||
|
|
||||||
|
async def broken(_uid, ids):
|
||||||
|
raise RuntimeError("no database")
|
||||||
|
|
||||||
|
io = dataclasses.replace(io, retired=broken)
|
||||||
|
result = await rp.run_rule_arm(rp.PROMPT_RULE, moment, floor=0.5, budget=5, io=io)
|
||||||
|
assert sorted(result.shown_rule_ids) == [1, 2]
|
||||||
|
|||||||
@@ -0,0 +1,152 @@
|
|||||||
|
"""A rule's triggers: what each kind matches, what is refused, and how the
|
||||||
|
moment arm reads the board they build."""
|
||||||
|
from types import SimpleNamespace
|
||||||
|
from unittest.mock import AsyncMock, MagicMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from grimoire.services import retrieval_pipeline as rp
|
||||||
|
from grimoire.services import rule_order
|
||||||
|
from grimoire.services import rule_triggers as rt
|
||||||
|
from grimoire.services.rule_triggers import Trigger
|
||||||
|
|
||||||
|
|
||||||
|
def T(kind, pattern, moment=""):
|
||||||
|
return rt.require_trigger({"kind": kind, "pattern": pattern, "moment": moment})
|
||||||
|
|
||||||
|
|
||||||
|
# ── matching, kind by kind ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("pattern", "path", "hit"), [
|
||||||
|
("alembic/versions/*.py", "/repo/alembic/versions/0130_x.py", True),
|
||||||
|
("alembic/versions/*.py", "alembic/versions/0130_x.py", True),
|
||||||
|
("alembic/versions/*.py", "/repo/alembic/versions/sub/0130.py", False),
|
||||||
|
("frontend/**/*.vue", "/r/frontend/src/components/A.vue", True),
|
||||||
|
("frontend/**/*.vue", "/r/frontend/A.vue", True),
|
||||||
|
("*.md", "/r/docs/README.md", True),
|
||||||
|
("/etc/*.conf", "/etc/nginx.conf", True),
|
||||||
|
("/etc/*.conf", "/srv/etc/nginx.conf", False),
|
||||||
|
("versions/*.py", "/repo/myversions/x.py", False),
|
||||||
|
])
|
||||||
|
def test_a_path_glob_matches_from_any_directory_unless_anchored(pattern, path, hit):
|
||||||
|
assert rt.matches(T("path", pattern), "Write", {"file_path": path}) is hit
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_path_trigger_reads_every_file_field_and_needs_an_act():
|
||||||
|
trig = T("path", "*.ipynb")
|
||||||
|
assert rt.matches(trig, "NotebookEdit", {"notebook_path": "/a/b.ipynb"})
|
||||||
|
assert rt.matches(trig, "Glob", {"path": "/a/b.ipynb"})
|
||||||
|
assert not rt.matches(trig, None, None, text="b.ipynb")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(("command", "hit"), [
|
||||||
|
("git push origin dev", True),
|
||||||
|
("make test && git push", True),
|
||||||
|
("FOO=1 git push", True),
|
||||||
|
("git pushx", False),
|
||||||
|
("echo git push", False),
|
||||||
|
])
|
||||||
|
def test_a_command_trigger_matches_the_head_of_any_segment(command, hit):
|
||||||
|
assert rt.matches(T("command", "git push"), "Bash", {"command": command}) is hit
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_tool_trigger_matches_the_key_with_or_without_a_server_prefix():
|
||||||
|
assert rt.matches(T("tool", "update_task"), "mcp__plugin_grimoire_grimoire__update_task", {})
|
||||||
|
assert rt.matches(T("tool", "*_task"), "mcp__x__create_task", {})
|
||||||
|
assert not rt.matches(T("tool", "update_task"), "mcp__x__get_task", {})
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_keyword_matches_a_whole_word_in_what_the_act_writes_or_the_reply():
|
||||||
|
trig = T("keyword", "migration")
|
||||||
|
assert rt.matches(trig, "Edit", {"new_string": "add a Migration for it"})
|
||||||
|
assert rt.matches(trig, None, None, text="this migration is done")
|
||||||
|
assert not rt.matches(trig, "Edit", {"new_string": "migrations"})
|
||||||
|
assert not rt.matches(trig, "Write", {"file_path": "migration.py"})
|
||||||
|
|
||||||
|
|
||||||
|
# ── validation ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def test_validation_normalises_and_refuses_what_could_never_fire():
|
||||||
|
assert T("tool", "mcp__x__Update_Task") == Trigger("tool", "update_task")
|
||||||
|
assert T("command", " Git Push ") == Trigger("command", "git push")
|
||||||
|
assert T("path", "src/**", " Work.Change ") == Trigger("path", "src/**", "work.change")
|
||||||
|
for bad in ({"kind": "regex", "pattern": "x"}, {"kind": "path", "pattern": " "},
|
||||||
|
{"kind": "path", "pattern": "x", "moment": "work.finished"}, "path:x"):
|
||||||
|
with pytest.raises(ValueError):
|
||||||
|
rt.require_trigger(bad)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_set_is_deduplicated_capped_and_none_leaves_it_alone():
|
||||||
|
assert rt.require_triggers(None) is None
|
||||||
|
assert rt.require_triggers([]) == []
|
||||||
|
same = {"kind": "path", "pattern": "a/*"}
|
||||||
|
assert rt.require_triggers([same, same]) == [Trigger("path", "a/*")]
|
||||||
|
with pytest.raises(ValueError, match="at most"):
|
||||||
|
rt.require_triggers([{"kind": "keyword", "pattern": f"w{i}"} for i in range(rt.TRIGGERS_MAX + 1)])
|
||||||
|
|
||||||
|
|
||||||
|
def test_each_kind_names_the_tools_the_catch_all_hook_must_forward():
|
||||||
|
assert rt.tools_for(T("tool", "update_task")) == {"update_task"}
|
||||||
|
assert rt.tools_for(T("tool", "*_task")) == set()
|
||||||
|
assert rt.tools_for(T("command", "git push")) == {"bash"}
|
||||||
|
assert "write" in rt.tools_for(T("path", "a/*")) and "edit" in rt.tools_for(T("path", "a/*"))
|
||||||
|
|
||||||
|
|
||||||
|
# ── the board ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _r(rid, enforcement="inform"):
|
||||||
|
return SimpleNamespace(id=rid, title=f"rule {rid}", kind="rule", when_to_apply="when",
|
||||||
|
enforcement=enforcement, salience="normal")
|
||||||
|
|
||||||
|
|
||||||
|
async def test_the_board_gates_a_conditional_mount_the_act_missed(monkeypatch):
|
||||||
|
scoped = _r(1)
|
||||||
|
free = _r(2)
|
||||||
|
monkeypatch.setattr(rt, "_in_scope", AsyncMock(return_value=[
|
||||||
|
(scoped, [T("path", "alembic/**", "work.change")]),
|
||||||
|
(free, [T("command", "git push"), T("keyword", "deploy")]),
|
||||||
|
]))
|
||||||
|
edit = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/src/app.py"})
|
||||||
|
assert edit.gated == {(1, "work.change")} and not edit.matched and not edit.fired
|
||||||
|
mig = await rt.board(1, 2, tool="Edit", tool_input={"file_path": "/r/alembic/v/1.py"})
|
||||||
|
assert mig.matched == {(1, "work.change")} and not mig.gated
|
||||||
|
push = await rt.board(1, 2, tool="Bash", tool_input={"command": "git push"})
|
||||||
|
assert [(r.id, t.kind) for r, t in push.fired] == [(2, "command")]
|
||||||
|
|
||||||
|
|
||||||
|
# ── the arm reading it ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
CHANGE = [{"moment": "work.change", "tool": "Edit", "match": "", "via": "default"}]
|
||||||
|
|
||||||
|
|
||||||
|
async def _arm(pairs, board, reached=CHANGE, **kw):
|
||||||
|
return await rp.run_moment_arm(
|
||||||
|
reached, rp.RuleMoment(user_id=1, query="", project_id=2, **kw),
|
||||||
|
io=rp.MomentIO(lookup=AsyncMock(return_value=pairs), record_rule_surfaced=MagicMock()),
|
||||||
|
board=board,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_gated_mount_is_not_delivered_and_a_met_one_ranks_as_triggered():
|
||||||
|
pairs = [(_r(1), "work.change"), (_r(2), "work.change")]
|
||||||
|
result = await _arm(pairs, rt.Board(gated={(1, "work.change")}))
|
||||||
|
assert result.shown_rule_ids == [2]
|
||||||
|
result = await _arm(pairs, rt.Board(matched={(2, "work.change")}))
|
||||||
|
assert result.shown_rule_ids == [2, 1]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_an_unscoped_trigger_delivers_with_no_moment_reached_and_says_what_fired():
|
||||||
|
board = rt.Board(fired=[(_r(7), T("path", "alembic/**"))])
|
||||||
|
result = await _arm([], board, reached=[])
|
||||||
|
assert result.shown_rule_ids == [7]
|
||||||
|
assert "path `alembic/**`" in result.lines[0]
|
||||||
|
|
||||||
|
|
||||||
|
async def test_a_rule_both_mounted_and_fired_is_delivered_once():
|
||||||
|
board = rt.Board(fired=[(_r(1), T("command", "git push"))])
|
||||||
|
result = await _arm([(_r(1), "work.change")], board)
|
||||||
|
assert result.shown_rule_ids == [1]
|
||||||
|
|
||||||
|
|
||||||
|
def test_triggered_outranks_mounted_in_the_one_order():
|
||||||
|
assert rule_order.BY_TRIGGER > rule_order.BY_MOUNT > rule_order.BY_RESEMBLANCE
|
||||||
@@ -22,7 +22,7 @@ def test_backup_version_is_current():
|
|||||||
"""The bump is the point of the test — a payload section added without
|
"""The bump is the point of the test — a payload section added without
|
||||||
moving the version produces backups that are structurally different and
|
moving the version produces backups that are structurally different and
|
||||||
indistinguishable by inspection."""
|
indistinguishable by inspection."""
|
||||||
assert backup.BACKUP_VERSION == 28
|
assert backup.BACKUP_VERSION == 29
|
||||||
|
|
||||||
|
|
||||||
def _exportable_note(**over):
|
def _exportable_note(**over):
|
||||||
@@ -483,7 +483,7 @@ def test_the_column_guard_covers_every_table_with_a_row_helper():
|
|||||||
# REAL table names, as _BACKED_UP holds them — not the shorter keys the
|
# REAL table names, as _BACKED_UP holds them — not the shorter keys the
|
||||||
# payload uses for the same sections. Getting this wrong is what the guard
|
# payload uses for the same sections. Getting this wrong is what the guard
|
||||||
# caught on its own first run.
|
# caught on its own first run.
|
||||||
join_tables = {"rule_systems", "rule_moments"}
|
join_tables = {"rule_systems", "rule_moments", "rule_triggers"}
|
||||||
covered = set(_column_guard_targets()) | join_tables
|
covered = set(_column_guard_targets()) | join_tables
|
||||||
assert set(backup._BACKED_UP) - covered == set()
|
assert set(backup._BACKED_UP) - covered == set()
|
||||||
# And no stale entries: every declaration must name a real target.
|
# And no stale entries: every declaration must name a real target.
|
||||||
|
|||||||
Reference in New Issue
Block a user